content stringlengths 5 1.05M |
|---|
class MC(type):
classes = []
count = 0
def __prepare__(name, bases):
return {'prepared': True}
def __new__(cls, name, bases, namespace):
MC.classes.append(name)
return type.__new__(cls, name, bases, namespace)
def __call__(cls):
MC.count += 1
return type.__... |
import csv
import math
import os
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
class CancerDataset(Dataset):
'''Dataset class to feed network with images and labels
args:
df (pandas df): dataframe containing two co... |
#!/usr/bin/python3
import sys
# From AT Keyboard Scan Codes (Set 2)
scancodes = {
# letters
0x001C: "KEY_A",
0x0032: "KEY_B",
0x0021: "KEY_C",
0x0023: "KEY_D",
0x0024: "KEY_E",
0x002B: "KEY_F",
0x0034: "KEY_G",
0x0033: "KEY_H",
0x0043: "KEY_I",
0x003B: "KEY_J",
0x0042: ... |
# list(map(int, input().split()))
# int(input())
def main(X, K, D):
x = abs(X)
k = K
shou, amari = x // D, x % D
if shou >= k: # 0付近までたどり着かないとき
x -= k * D
k = 0
else:
k -= (shou + 1)
x -= (shou + 1) * D
if k % 2: # 奇数のとき
print(abs(x + D))
else:... |
# -*- coding: utf-8 -*-
# @Time : 2018/6/21 上午10:14
# @Author : Azrael.Bai
# @File : table_reflect.py
FILE_LIST = [# "ModelDef_GongShang_GSGW.py",
"ModelDef_GongShang_HZ.py",
# "ModelDef_GongShang_QCC.py",
# "ModelDef_GongShang_QXB.py",
# "ModelDef_SheSu_DFFY... |
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
conserved_variables = ('Depth', 'Momentum')
primitive_variables = ('Depth', 'Velocity')
left, middle, right = (0, 1, 2)
def pospart(x):
return np.maximum(1.e-15,x)
def primitive_to_conservative(h, u):
hu = h*u
return h, ... |
import tf_semseg, eval
import tensorflow as tf
def test_upernet_vitb_ade20k():
model = tf_semseg.model.pretrained.openmmlab.upernet_vitb_ade20k.create()
predictor = lambda x: model(x, training=False)
accuracy = eval.ade20k(predictor, tf_semseg.model.pretrained.openmmlab.upernet_vitb_ade20k.preprocess... |
x=10
print(x) # Change the value of (x) at any time
x=12
print(x) |
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from pypytranspy.cli import transpile_dir
def test_transpile_dir_excludes_out_path():
with TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
src_path = tmp_path / "src"
out_path = tmp... |
""" Views for VPN management API """
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import json
from tempfile import mkstemp
import os
from sign import repository
from models import State
from utils import *
@csrf_exempt
def post_csr(reques... |
class Knife:
length = "3in"
|
from .Client import *
__copyright__ = 'Copyright (C) 2020 Atsushi Nakatsugawa'
__version__ = '1.0.0'
__license__ = 'MIT License'
__author__ = 'Atsushi Nakatsugawa'
__author_email__ = 'atsushi@moongift.jp'
__url__ = 'https://github.com/goofmint/CustomersMailCloudPy'
__all__ = ['CustomersMai... |
multiplied_trees = 1
trees_hit = 0
with open("input.txt", "r") as puzzle_input:
horizontal_index = 0
for line in puzzle_input:
line = line.strip()
current_line = line * multiplied_trees
if horizontal_index >= len(current_line):
multiplied_trees += 1
... |
import os
from pathlib import Path
import boto3
import botocore
from moto import mock_s3
from pytest_mock import MockFixture
from ignite.engine import Engine
from smtools.torch.handlers import s3_copy
@mock_s3
def test_s3_copy(tmp_path: Path, mocker: MockFixture):
# Setup
# local files to upload
names =... |
# Copyright (c) 2019 NVIDIA Corporation
from app import app
|
from transformers import RobertaTokenizer, RobertaConfig
from fairseq.data.encoders.fastbpe import fastBPE
from fairseq.data import Dictionary
from vncorenlp import VnCoreNLP
from model.PhoBERT import PhoBERT
from train_phobert import *
import argparse
parser = argparse.ArgumentParser(description='Process some integer... |
# -*- coding: utf-8 -*-
"""
PyElectrica |1.1.4|
Modulo Python con funciones útiles para resolver problemas específicos
en Ingeniería Eléctrica relativos a los Circuitos y Máquinas Eléctricas.
Funciones integradas en el módulo PyElectrica:
----------------------------------------------
ANÁLISIS DE CIRCUITOS... |
import csv
import json
import os
import datetime
from dotenv import load_dotenv
import requests
load_dotenv()
def to_usd(my_price):
return "${0:,.2f}".format(my_price)
api_key = os.environ.get("ALPHADVANTAGE_API_KEY")
#print(api_key)
def get_response(symbol):
request_url = f"https://www.alphavantage.co/... |
import numpy as np
import pylab
data = np.frombuffer(open('out.bin','rb').read(),dtype='uint8')
dt=1.0/32000 * 1000#msec
pylab.plot(np.arange(0,len(data)*dt,dt),data)
pylab.show()
|
import datetime as dt
import pymms
from pymms.sdc import mrmms_sdc_api as sdc
from pymms.sdc import selections as sel
from metaarray import metabase, metaarray, metatime
from matplotlib import pyplot as plt
import pathlib
def time_to_orbit(time, sc='mms1', delta=10):
'''
Identify the orbit in which a time fal... |
from typing import Callable, Optional, Any
import flax.linen as nn
import jax.numpy as jnp
Dtype = Any
class SimCLR(nn.Module):
model_cls: Callable
frontend_cls: Optional[Callable] = None
embedding_dim: int = 512
dtype: Dtype = jnp.float32
@nn.compact
def __call__(self, inputs, train: bool ... |
import os.path
import glob
from .util import split2list
from .listdataset import ListDataset
from random import shuffle
def make_dataset(input_dir,split):
plyfiles = []
for dirs in os.listdir(input_dir):
tempDir = os.path.join(input_dir,dirs)
for input in glob.iglob(os.path.join(tempDir,'*.npy... |
import importlib
from django.conf import settings
def update_dns_record(dns_record, ip):
if dns_record.provider:
config = settings.DYNAMICDNS_PROVIDERS[dns_record.provider]
mod_path, mod_name = config['plugin'].rsplit('.', 1)
DnsPlugin = getattr(importlib.import_module(mod_path, package=m... |
# coding=utf-8
from numpy import mat, shape, zeros
# 隐马尔科链模型前向算法
def hmm_forward(A, PI, B, O):
M = shape(PI)[0] # 观测序列大小
N = shape(A)[1] # 状态序列大小
T = M
alpha = mat(zeros((M, N)))
P = 0.0
for i in range(N):
alpha[0, i] = PI[i, 0] * B[i, 0]
for t in range(T - 1):
for i in ... |
from django.urls import path
from . import views
app_name = 'cars'
# /cars/
urlpatterns = [
path('', views.rental_review, name='rental_review'),
path('thank_you/', views.thank_you, name='thank_you'),
]
|
"""The sample compares different boosting algorithms
on 20newsgroups dataset
"""
__copyright__ = """
Copyright © 2017-2021 ABBYY Production LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... |
from django.test import TestCase, Client
from django.urls import reverse
from django.test.utils import setup_test_environment
from bs4 import BeautifulSoup
import re
import time
from projects.models import *
from projects.forms import *
client = Client()
# length of base template, used to test for empty pages
LEN_B... |
from django.core.exceptions import ObjectDoesNotExist
from cctool.common.lib.analyses.controllability import control_analysis as CA_Analysis
from cctool.common.lib.analyses.controllability import controllability_visualization as CA_Visualization
from cctool.common.lib.analyses.downstream import downstream_analysis as ... |
# coding:utf8
# def_function.py
def print_two (*args): # 参数个数不确定
arg1, arg2 = args # 参数解包
print ("arg1: %r, arg2: %r"% (arg1, arg2)) # 传递参数
return
def print_two_again (arg1, arg2):
print ("arg1: %r, arg2: %r"% (arg1, arg2))
return
def print_one (arg1):
print ("arg1: %r"% arg1)
return
de... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 17:13:51 2019
@author: Ganesh Patil
"""
num = int(input("Enter a number = "))
if (num > 1):
for i in range (2,num):
if(num % i) == 0:
print(num, "it is not a prime number")
break
else:
print(num, "it is a... |
import traceback
def format_exception(e):
return traceback.format_exception_only(type(e), e)[0].rstrip()
|
prsnt_game_credits = 0
prsnt_game_profile_banner_selection = 1
prsnt_game_custom_battle_designer = 2
prsnt_game_multiplayer_admin_panel = 3
prsnt_multiplayer_welcome_message = 4
prsnt_multiplayer_team_select = 5
prsnt_multiplayer_troop_select = 6
prsnt_multiplayer_item_select = 7
prsnt_multiplayer_message_1 = 8
prsnt_m... |
# Liberaries
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from functools import partial
# Local modules.
from assessment.models import Question, Assessment
from assessment.middlewares.validators.field_validators import get_objec... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from setuptools import setup, find_packages
import opps
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
dependency_links = [
'http://github.com/avelino/django-googl/tarball/master#egg=django-googl',
'http://github.com/opps/opps-piston/tar... |
import csv
import pandas as pd
import math
import json
import numpy as np
import itertools
from . import dailydata_to_weeklydata as dw
from .impose_none import impose_none as impn
#TODO 因為天貓的main_info有兩個資訊 我想要在使用dw的時候可以一次把兩個資訊(Volume,Price)都處理完畢
#TODO 最大值 Max_info 有回傳出去 我想要增加最小值的回傳
#TODO 所以如果是在天貓的情況Max_info Min_info 會... |
#%% import libraries
import numpy as np
import pandas as pd
import re
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_e... |
# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
from ._neural_net_regressor import NN_Regressor
from ._rf_regressor import RF_Regressor
from ._rf_classifier import RF_Classifier |
import sys
import pathlib
from django.core.management import execute_from_command_line
from cobl import configure
if __name__ == "__main__":
ci, cfg_path = 0, None
for i, arg in enumerate(sys.argv):
if arg.endswith('.ini') and pathlib.Path(arg).exists():
ci = i
break
if c... |
# ------------------------------
# 560. Subarray Sum Equals K
#
# Description:
# Given an array of integers and an integer k, you need to find the total number of
# continuous subarrays whose sum equals to k.
#
# Example 1:
# Input:nums = [1,1,1], k = 2
# Output: 2
#
# Note:
# The length of the array is in range [1... |
# from . import StorageMetadataDTO
|
#!/usr/bin/env python
import re
import subprocess
import sys
from typing import Final
from .common_types import HtmlCode
## Depends on having Calibre's `ebook-convert` in your PATH.
## On MacOS, install Calibre then:
## export PATH="${PATH}:/Applications/calibre.app/Contents/MacOS"
## On Debian, `sudo apt install ... |
class Solution(object):
# @param A : tuple of integers
# @return an integer
def maxSubArray(self, A):
i=0
j=0
running_sum = 0
max_sum = float("-inf")
for i in range(1,len(A)):
running_sum += A[i]
if running_sum > max_sum:
max_su... |
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from plans.models import Order, Invoice, UserPlan, Plan
from plans.signals import order_completed, activate_user_plan
from accounts.models import User
@receiver(post_save, sender=Order)
def create_proforma_invoice(sender, ... |
# coding: utf-8
"""
Notation and containers for multi-dimensional MIDI style data
"""
from functools import total_ordering
from numpy import array, dot, exp, log
from .temperament import JI_5LIMIT, mod_comma, canonize, canonize2, JI_ISLAND, JI_7LIMIT, JI_11LIMIT, JI_3_7, canonize_3_7, canonize2_3_7, canonize_7_11, JI_7... |
from .file_lock import FileLock
import os
import json
from json import JSONDecodeError
import threading
import time
DEBUG_MODE = False
class ReadWrite:
""" An object that allows many simultaneous read lock but one exclusive write lock"""
def __init__(self, file_name):
self.target_file = os.path.join(... |
from .cityscapes import CitySegmentation
from .coco import COCOSegmentation
from .person import PersonSegmentation
datasets = {
'citys': CitySegmentation,
'coco': COCOSegmentation,
'person': PersonSegmentation,
}
def get_segmentation_dataset(name, **kwargs):
"""Segmentation Datasets"""
return dat... |
# Generated by Django 2.0.6 on 2018-06-05 05:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import sys
import time
from gpu_tests import gpu_integration_test
from gpu_tests import pixel_test_pages
from gpu_tests import skia... |
#!/usr/bin/env python
import os, runpy
this_dir = os.path.dirname(os.path.abspath(__file__))
runpy.run_path(f"{this_dir}/a.py")
from nspawn.build import *
name = "bionic"
version = "18.04"
image_url = f"file://localhost/tmp/nspawn/repo/ubuntu/base/{name}-{version}.tar.gz"
booter_url = f"https://cloud-images.ubuntu.c... |
import os, sys, time, argparse
from utils import get_info, error, warn, success, display_info_dict
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', help='Pass district name, it should match with what you have added in input.json, it is case sensitive.')
args = parser.p... |
import my_setting.utils as utils
import pandas as pd
import os
from enum import IntEnum
import csv
import abc
from abc import ABCMeta
import re
from multiprocessing import Pool
from functools import partial, reduce
import time
import chinese_converter as cc
from collections import Counter
class DatasetType(IntEnum):
... |
from picsellia.client import Client
from picsellia_yolov5.utils import to_yolo, find_matching_annotations, edit_model_yaml, generate_yaml, Opt, setup_hyp
from picsellia_yolov5.utils import send_run_to_picsellia
from picsellia_yolov5.yolov5.train import train
import argparse
import sys
import os
import subprocess
imp... |
#!/usr/bin/env python3
# Project Euler : Problem 3
# Largest prime factor
from math import sqrt
# Plus grand premier diviseur de n
def PGPD(n):
pMax = n
div = 2
while n != 1:
if n % div == 0:
pMax = div
while n % div == 0:
n /= div
div += 1
re... |
INITIAL_GUID = _GUID
class _GUID(INITIAL_GUID):
def __init__(self, Data1=None, Data2=None, Data3=None, Data4=None, name=None, strid=None):
data_tuple = (Data1, Data2, Data3, Data4)
self.name = name
self.strid = strid
if all(data is None for data in data_tuple):
return sup... |
expected_output = {
"local_as": 100,
"total_established_peers": 3,
"total_peers": 4,
"vrf": {
"default": {
"router_id": "10.1.1.1",
"vrf_peers": 4,
"vrf_established_peers": 3,
"local_as": 100,
"neighbor": {
"10.51.1.101": {
... |
from fastapi import APIRouter, Body, BackgroundTasks
import logging
import aiohttp
import asyncio
from typing import Dict, Any
from pydantic import BaseModel
import uuid
from src.api_composition_proxy.configurations import ServiceConfigurations
from src.api_composition_proxy import helpers
from src.jobs import store_d... |
from django.core.management.base import BaseCommand
from money.models import Post, Tarif
from django.contrib.auth.models import User
from logs.models import Logs
from userprofile.models import UserProfile
import requests
import lxml.html
from local_site.settings import TYPE_CHOICES, LOGSTATUSYES, LOGSTATUSNO
# pyth... |
"""Top-level package for django-clone."""
__author__ = """Tonye Jack"""
__email__ = "jtonye@ymail.com"
__version__ = "2.5.3"
from model_clone.admin import CloneModelAdmin, CloneModelAdminMixin
from model_clone.mixins.clone import CloneMixin
from model_clone.utils import create_copy_of_instance
__all__ = [
"Clone... |
import subprocess
import os
import platform
import pytest
def _run_test(testname):
dirname = os.path.split(__file__)[0]
exename = os.path.join(dirname, 'bin', 'Python.DomainReloadTests.exe')
args = [exename, testname]
if platform.system() != 'Windows':
args = ['mono'] + args
proc = subpr... |
# Generated by Django 2.0 on 2018-04-22 21:23
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import imagekit.models.fields
class Migration(migrations.Migration):
dependencies = [("events", "0027_add_category_topic_slug")]
operations = [
migra... |
import csv
from PatientEntry import PatientEntry
from Recipient import Recipient
from EmailHandler import EmailHandler
from FormattedBodyText import FormattedBodyText
def get_data(file: str) -> list:
"""extract our data from our source file
Args:
file (str): filename
Returns:
list: list ... |
import os
import time
from pathlib import Path
from urllib.parse import urlparse
import attr
import falcon.testing
import psycopg2
import pytest
from psycopg2.extras import execute_values
from brightsky.db import get_connection, migrate
@pytest.fixture(scope='session')
def data_dir():
return Path(os.path.dirnam... |
from django.core.management.base import NoArgsCommand, CommandError;
from ldap_login.ldapUtils import ldapManager;
from ldap_login.models import user,group,Role;
from datetime import datetime;
import traceback;
class Command(NoArgsCommand):
"""Import LDAP users from Active Directory.
Uses the ldapUtils back... |
def is_palindrome(n):
s = str(n)
tens = len(s) - 1
i = 0
while i <= tens / 2:
if not s[i] == s[tens - i]:
return False
i += 1
return True
total = 0
for n in range(1000000):
if is_palindrome(n):
base_2 = int(bin(n)[2:])
if is_palindrome(base_2):
... |
from bs4 import BeautifulSoup
import requests
import yaml
import os
# Channel RSS feed to scrape for video data
url = "https://www.youtube.com/feeds/videos.xml?channel_id=UC964lfWIMojN48cA6FK2Fhg"
html = requests.get(url)
soup = BeautifulSoup(html.text, "lxml")
vidlist = []
for entry in soup.find_all("entry"):
vi... |
arr = []
b = False
with open("input","r") as f:
for i in f.readlines():
arr = arr + [int(i.rstrip("\n"))]
length = len(arr)
for i in range(0,length):
for j in range(0,length):
for k in range(0,length):
if (arr[i]+arr[j]+arr[k] == 2020):
print("Result = ", arr... |
# Copyright (c) 2018 Marco Giusti
import os.path
from cffi import FFI
curdir = os.path.abspath(os.path.dirname(__file__))
c_source = r'''
#include "ace.h"
'''
ffibuilder = FFI()
ffibuilder.set_source(
'_ace',
c_source,
libraries=['ace'],
include_dirs=[curdir]
)
ffibuilder.cdef(open(os.path.join('sr... |
"""
Restore ckpt from meta file and JUST display the shape/name of all the layers
"""
import tensorflow as tf
import numpy as np
config = tf.ConfigProto(
log_device_placement=True,
allow_soft_placement=True
)
with tf.Session(config=config) as sess:
new_saver = tf.train.import_meta_graph(
'../save_model... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""base.py: Contains toml parser and basic data class."""
from mruns import __version__
from pathlib import Path
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import Optional, Callable, List, Dict, Tuple, Any, ClassVar, Iterator... |
#Um programa que lê a idade de um atleta e mostra sua classificação
idade = int(input('Quantos anos você tem? '))
if idade <= 9:
print('Sua classificação é: mirim')
elif idade <= 14:
print('Sua classificação é: infantil')
elif idade <= 19:
print('Sua classificação é: junior')
elif idade <= 20:
print('... |
import os
import sys
from secret import FLAG
from Crypto.Cipher import AES
def pad(text):
padding = 16 - (len(text) % 16)
return text + bytes([padding] * padding)
def encrypt(text):
cipher = AES.new(key, AES.MODE_OFB, iv)
return cipher.encrypt(pad(text))
def nonce():
randtext = list(os.urandom(le... |
from uuid import uuid4
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.db.models.expressions import F, Value
from tastypie.models import create_api_key
from django.forms.models import model_to_dict
# Create your models here.
class TimestampMixin... |
nose
mock
ipython
oauth2==1.9.0.post1
urllib3==1.25
httplib2==0.10.3
|
#!/bin/bash
import os
import shlex
import subprocess
import sys
from pathlib import Path
def start_setup():
python_version = None
pip_version = None
# get os
os_name = sys.platform
print("os is %s" % (os_name))
if os_name.startswith("win"):
raise Exception("Try on linux system")
el... |
"""Methods to perform regular database maintenance."""
from backend.lib.database.postgres import connect
from backend.lib.timer import timed
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def _execute_outside_of_transaction_block(query):
"""
Execute a SQL statement outside of a transaction block.... |
import base64
from django.conf import settings
from django.http import JsonResponse
from healthpoint.registry import get_health_checks
def _is_authenticated_request(request):
# Superusers and staff members are always correctly authenticated.
user = getattr(request, "user", None)
if user is not None and (... |
"""2018 - Day 4 Part 1: Repose Record.
You've sneaked into another supply closet - this time, it's across from the
prototype suit manufacturing lab. You need to sneak inside and fix the issues
with the suit, but there's a guard stationed outside the lab, so this is as
close as you can safely get.
As you search the cl... |
import itertools
from amplifier import Amplifier, one_amplifier_running
puzzle_input = []
with open('day-7/input.txt', 'r') as file:
puzzle_input = [int(i.strip()) for i in file.read().split(',')]
def part_1(puzzle_input):
permutations = list(itertools.permutations(range(0, 5), 5))
highest_output = 0
... |
from ...isa.inst import *
import numpy as np
class Fcvt_wu_s(Inst):
name = 'fcvt.wu.s'
def golden(self):
if 'val1' in self.keys():
if self['val1'] < 0 or np.isneginf(self['val1']):
return 0
if self['val1'] > ((1<<32)-1) or np.isposinf(self['val1']) or np.isnan(s... |
import socket
import json
from flask import Flask, request, render_template, Response
from camera import VideoCamera
from flask import jsonify
# from flask_cors import CORS, cross_origin
import car
import logging
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import os
from iot_co... |
import numpy as np
def donor_acceptor_direction_vector(molecule, feat_type, atom_indx, coords, conformer_idx):
"""
Compute the direction vector for an H bond donor or H bond acceptor feature
Parameters
----------
molecule : rdkit.Chem.rdchem.Mol
Molecule that conta... |
'''
TODO: checkpoint/restart
* for each .map() call:
* log initial psets
* record results to disk in chunks as they come in
* on restart, rerun missing or provide previous results
* handle multiple map() calls in a single user program
'''
import datetime
import os
import sys
import socket
logger_filename = N... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os, sys, shutil
import xml.dom.minidom
import json
import urllib
def decodeXML(xmlFiledata):
dom = xml.dom.minidom.parseString(xmlFiledata)
items = dom.getElementsByTagName("item")
result = []
for item in items:
dictstr, wordstr, explainstr = decodeIte... |
ngsi_data= \
{
'originator':u'',
'subscriptionId': '195bc4c6-882e-40ce-a98f-e9b72f87bdfd',
'contextResponses':
[
{
'contextElement': {'attributes':
[
{
... |
"""
Generated by CHARMM-GUI (http://www.charmm-gui.org)
omm_readinputs.py
This module is for reading inputs in OpenMM.
Correspondance: jul316@lehigh.edu or wonpil@lehigh.edu
Last update: March 29, 2017
"""
from simtk.unit import *
from simtk.openmm import *
from simtk.openmm.app import *
class _OpenMMReadInputs():... |
# run test with
# python -m tests\test_echomodel.py
import importlib
import unittest
import echo2rasa.tools.echomodel as echomodel
class TestEchoModel(unittest.TestCase):
def get_restaurant_intent(self, model):
intents = model.model["interactionModel"]["languageModel"]["intents"]
for... |
"""
用户常量
"""
class UserConst:
BLOGGER_ID: int = 1 # 博主id
SILENCE: int = 1 # 禁言状态
|
#!/usr/bin/env python3
import re
from typing import Any, Dict, Generator
import lxml.html
from venues.abstract_venue import AbstractVenue
class Yotalo(AbstractVenue):
def __init__(self):
super().__init__()
self.url = "https://yo-talo.fi/ohjelma/"
self.name = "Yo-talo"
self.city =... |
'''
For the masked peptides, see if we can find them in the MS data;
'''
import glob, sys, os, numpy, regex
from glbase3 import *
import matplotlib.pyplot as plot
sys.path.append('../../')
import shared
res = {}
all_matches = glload('../results_gene.glb')
pep_hit = []
for pep in all_matches:
if pep['insideTE... |
# Copyright 2012-2013 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V2beta2PodsMetricSourceDict generated type."""
from typing import TypedDict
from kubernetes_typed.client import V2beta2MetricIdentifierDict, V2beta2MetricTargetDict
V2beta2PodsMetricSourceDict = TypedDict(
"V2beta2PodsMetricSourceDict",
{
"metric": V... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponse
from django_distill import distill_url, distill_path, distill_re_path
def test_no_param_view(reqest):
return HttpResponse(b'test',
content_type='application/octet-stream')
def test_positiona... |
import sys, string, os
def separator():
printf("=========================================")
separator()
printf(" ==> RandomX Mining Presets Wizard <== ")
separator()
printf(" /===========\ /==\")
printf(" | [-----] | | |")
printf(" | | | | | | ... |
# coding=utf-8
import os
import json
global_config = {
"gpu_id": "0,1,4,7,9,15",
"async_loading": true,
"shuffle": true,
"data_aug": true,
"num_epochs": 3000,
"img_height": 320,
"img_width": 320,
"num_channels": 3,
"batch_size": 96,
"dataloader_workers": 1,
"learning_rate_g": 1e-4,
"learning_... |
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
cnt, ans = 1, [1]
dp = [0 for _ in range(len(primes))]
while cnt < n:
next_ugly , min_index = -1 , -1
for i in range(len(primes)):
if primes[i] * ans[dp[i]] == an... |
#!/usr/bin/python
import os, sys
from PIL import ImageFile
import Image
def thumb(infile, ext):
size = 250, 250
outfile = os.path.splitext(infile)[0] + "_thumb" + ext
types = {'.jpg' : 'JPEG', '.jpeg' : 'JPEG', '.png' : 'PNG', '.gif' : 'GIF'}
im = Image.open(infile)
im = im.convert('RGB')
im.thumbnail(size, Imag... |
#!/usr/bin/env python
import re
from setuptools import setup
READMEFILE = 'README.rst'
VERSIONFILE = 'pytest_wholenodeid.py'
VSRE = r"""^__version__ = ['"]([^'"]*)['"]"""
def get_version():
version_file = open(VERSIONFILE, 'rt').read()
return re.search(VSRE, version_file, re.M).group(1)
setup(
name='... |
# MIT License
# Copyright (c) 2020 Ali Ghadirzadeh
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
from .api import UserSerializer
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from django.contrib.auth import get_user_model
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
def app(request):
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.