id
stringlengths
3
8
content
stringlengths
100
981k
183547
import time from ..ExcelDataUtil.xlsxDataGetter import XlsxDataGetter from ..ExcelDataUtil.xlsxDataWriter import XlsxDataWriter from ..Util.dateUtil import timestamp2datetime from ..Variables.Status import Status class RealNotes(object): def __init__(self, code, strategy, **kwargs): self.file_name = code ...
183550
import csv import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np import scipy.signal import matplotlib plt.style.use('dark_background') # with open('csv/run_PPO_summary-tag-Info_cumulative_reward.csv', newline='') as csvfile: with open('csv/run_PPO_summary-tag-Info_episode_...
183551
from rapidfuzz import process, fuzz from .load_dicts import FORMULA_URI_DICT, SMILES_URI_DICT, NAME_URI_DICT, \ FORMULA_KEYS, NAME_KEYS, SMILES_KEYS, ATTRIBUTE_URI_DICT, \ ATTRIBUTE_KEYS, CLASS_URI_DICT, CLASS_KEYS, process_species, process_species_reversed def find_nearest_match(entity_value, entity_type): ...
183562
from parameterized import parameterized from integration.helpers.base_test import BaseTest class TestIntrinsicFunctionsSupport(BaseTest): # test code definition uri object and serverless function properties support @parameterized.expand( [ "combination/intrinsics_code_definition_uri", ...
183580
import os import config import basehandler import models import accounts import urllib import admin from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db class AdjustScore(basehandler.BaseHandler): def ge...
183651
import pandas as pd from report import reporting as rep from checks import NaptanCheck # %% class MultiRoadName(NaptanCheck): """[summary] A collection of methods to check that the roads names contain the correct types and collection of words. Args: NaptanCheck ([type]): [description] Retu...
183657
import asyncio import json from threading import Timer import httpx import pytest from ariadne.asgi import GQL_CONNECTION_INIT, GQL_START from websockets import connect my_storage = {} @pytest.fixture def storage(): return my_storage @pytest.mark.asyncio async def test_create_user(host, credentials, storage):...
183662
def stockmax(p): ind_max = p.index(max(p)) #find the max price inv = sum(p[:ind_max]) #split the array before and after max price pf = len(p[:ind_max])*p[ind_max] - inv #buy all stocks before max price if len(p[ind_max+1:]) > 0: pf += stockmax(p[ind_max+1:]) #then sell them at max price ret...
183688
import csv import numpy as np import cv2 def resize_and_crop(image, img_size): """ Resize an image to the given img_size by first rescaling it and then applying a central crop to fit the given dimension. """ source_size = np.array(image.shape[:2], dtype=float) target_size = np.array(img_size, dtyp...
183741
import warnings import os.path as osp import tensorflow as tf import numpy as np import time from tflearn import is_training from in_out import create_dir from general_utils import iterate_in_chunks from latent_3d_points.neural_net import Neural_Net, MODEL_SAVER_ID try: from latent_3d_points.structural_loss...
183789
class BaseContest(object): '''BaseContest is an abstract class for contest-specific modifications to Marathoner. ''' def __init__(self, project): self.project = project self.maximize = project.maximize def extract_score(self, visualizer_stdout, solution_stderr): '''Extract r...
183838
from mstrio.connection import get_connection from mstrio.server.job_monitor import (Job, JobStatus, JobType, kill_all_jobs, kill_jobs, list_jobs, ObjectType, PUName) from mstrio.server.project import Project from mstrio.users_and_groups.user import User # connect to environment ...
183847
import os import parser import unittest class TestParser(unittest.TestCase): # Tests for parsers for the months from July 2019 to November 2020 def test_active_members_jan_2020(self): self.maxDiff = None expected = { "reg": "3725", "name": "<NAME>", "role"...
183849
from .module import PytorchModel, TrainingInterface from .scheduler import ConstantScheduler, TeacherForcingScheduler, \ OptimizerScheduler, ParameterScheduler from .manager import LogPathManager, DataLoaders, SummaryWriters from .example import MinExponentialLR
183881
from BlindMIUtil import * from dataLoader import * import tensorflow as tf from tensorflow.keras.models import load_model from sklearn import svm import sys os.environ['CUDA_VISIBLE_DEVICES'] = '1' tf.config.experimental.set_memory_growth(tf.config.experimental.list_physical_devices('GPU')[0], True) DATA_NAME...
183883
from math import * import random import timeit import matplotlib.pyplot as plt n, omega, N = 12, 2400, 1024 result = '' result22 = '' def show_graphic(num: int, signal: list, title: str): plt.plot(list(range(0, num)), signal) plt.grid(True) plt.title(title) plt.show() def random_signal(): all_...
183884
import csv import json import sys from pathlib import Path from typing import Dict, List from simcore_service_webserver.projects.projects_db import _convert_to_schema_names SEPARATOR = "," current_file = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve() current_dir = current_file.parent def load_...
183891
def flatten(myList): newList = [] for item in myList: if type(item) == list: newList.extend(flatten(item)) else: newList.append(item) return newList def main(): myList1 = [1,2,3,[1,2],5,[3,4,5,6,7]] print(flatten(myList1)) myList2 = [1,[2,[3,[4,[5,[6,[7,[...
183928
import conx as cx import numpy as np from keras.datasets import mnist from keras.utils import (to_categorical, get_file) description = """ Original source: http://yann.lecun.com/exdb/mnist/ The MNIST dataset contains 70,000 images of handwritten digits (zero to nine) that have been size-normalized and centered in a s...
183942
import hashlib import json import random import re import time import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36", "Referer": "http://fanyi.youdao.com/" } def test01(): """36kr.com的内容是存放在script标签中...
183971
import bspump.unittest import bspump.common class TestNullSink(bspump.unittest.ProcessorTestCase): def test_null(self): events = [ (None, "Don't let this out!"), ] self.set_up_processor(bspump.common.NullSink) output = self.execute( events ) self.assertEqual( [event for context, event in out...
184003
from pupa.scrape import Scraper from pupa.scrape import Event import datetime as dt import lxml.html import re CAL_PAGE = ("http://www.cityoftemecula.org/Temecula/Visitors/Calendar.htm") class TemeculaEventScraper(Scraper): def lxmlize(self, url): entry = self.urlopen(url) page = lxml.html.fro...
184035
import datetime from django.utils import timezone from django.test import TestCase from hknweb.events.tests.models.utils import ModelFactory class EventModelTests(TestCase): def setUp(self): user = ModelFactory.create_user() event_type = ModelFactory.create_event_type() event_name = "cu...
184062
from __future__ import print_function from orphics import maps,io,cosmology,symcoupling as sc,stats,lensing from enlib import enmap,bench import numpy as np import os,sys cache = True hdv = False deg = 5 px = 1.5 shape,wcs = maps.rect_geometry(width_deg = deg,px_res_arcmin=px) mc = sc.LensingModeCoupling(shape,wcs) ...
184089
from ._line import Line from ._colorbar import ColorBar from plotly.graph_objs.histogram.marker import colorbar
184095
from typing import Callable, Any, List import numpy as np import math import autograd from .dataset import Dataset class DataLoader(object): """ Dataloader class """ def __init__(self, dataset: Dataset, batch_size: int = 1, shuffle: bool = True, collate_fn: Callable[[List], Any] = ...
184116
from quest.admin import admin_site from .models import Goal, Task, TaskStatus admin_site.register(Goal) admin_site.register(Task) admin_site.register(TaskStatus)
184196
from __future__ import division import numpy as np import torch import torch.nn as nn from mmcv.cnn import normal_init from mmdet.core import (PointGenerator, multi_apply, multiclass_nms_kp, point_target_kp) from mmdet.ops import DeformConv from ..builder import build_loss from ..registry impo...
184256
import wandb import numpy as np import pandas as pd api = wandb.Api() wandb_entity = os.environ['WANDB_ENTITY'] # Project is specified by <entity/project-name> runs = api.runs(f"{wandb_entity}/invalid_action_masking") analysis = True summary_list = [] config_list = [] name_list = [] for run in runs: # run.sum...
184271
from .base import * DEBUG = True if DEBUG is True: from .dev import * else: from .production import * # 站点名称 SITE_NAME = 'manage' # 后台首页 SITE_PAGE = '/%s/service/article/' % SITE_NAME
184278
from CoreFoundation import ( CFPreferencesCopyValue, kCFPreferencesAnyHost, kCFPreferencesAnyUser, ) factoid = "updates_app_autoupdate" def fact(): """Returns the status of automatic updates to MAS apps""" status = "disabled" pref = CFPreferencesCopyValue( "AutoUpdate", "/Libr...
184310
from homeassistant.const import ( ENERGY_KILO_WATT_HOUR, ENERGY_WATT_HOUR, DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, POWER_WATT, ) from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, ) from homeassistant.components.integration.sen...
184353
from __future__ import print_function from fenics import * from mshr import * import numpy as np from scipy import integrate set_log_level(LogLevel.INFO) T = 500.0 # final time num_steps = 1000 # number of time steps dt = T / num_steps # time step size mu = 16 # dynamic viscosity rho = 1 ...
184363
import re as RE import operator from logging import info, getLogger getLogger().setLevel(1) def conv(input,output): info("reading input file "+input) fd=open(input) line=reduce(operator.add,fd.readlines()) fd.close() info("pruning trailing comments, labels, declarations and indentation") ...
184365
import numba import numpy as np NP_COMPLEX = np.complex128 NUMBA_COMPLEX = numba.complex128 NP_FLOAT = np.float64 NUMBA_FLOAT = numba.float64
184370
from .algorithms import OnlineNNClassifier, OnlineNNRuLSIF from .rulsif import RuLSIF from .dataset import generate_dataset from .viz import display __all__ = [ 'OnlineNNClassifier', 'OnlineNNRuLSIF', 'RuLSIF', 'generate_dataset', 'display' ]
184401
from fastai.callbacks.mixup import * from fastai.tabular import * class TabMixUpCallback(LearnerCallback): "Callback that creates the mixed-up input and target." def __init__(self, learn:Learner, alpha:float=0.3, stack_x:bool=False, stack_y:bool=True): super().__init__(learn) self.alpha,self.st...
184442
import numpy as np import matplotlib.pyplot as plt import torch from collections import namedtuple Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward', 'done')) class DeepRLTrainer: NB_EPISODES = 3000 SAVE_EVERY = 500 INFO_EVERY = 50 SOFT_MAX = False DEVICE = 'cpu'...
184495
DATABASE_ENGINE = 'sqlite3' SECRET_KEY = 'abcd123' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': './example.db', } } INSTALLED_APPS = ( 'django_bouncy', ) BOUNCY_TOPIC_ARN = ['arn:aws:sns:us-east-1:250214102493:Demo_App_Unsubscribes'] TEST_RUNNER = 'django_n...
184503
from robox import Options, Robox with Robox() as robox: page = robox.open("https://httpbin.org/forms/post") form = page.get_form() form.fill_in("custname", value="foo") form.check("topping", values=["Onion"]) form.choose("size", option="Medium") form.fill_in("comments", value="all good in the h...
184540
import os import asyncio import json from pyppeteer import launch network = [] javascript = [] async def intercept_network_response(response): network.append(str(response.status) + response.url) async def intercept_console(response): javascript.append(response.text) async def collect_msgs_and_screenshot(...
184606
import asyncio import json import time import unittest import requests import websockets from BaseTest import BaseTest, BASE_URL, BASE_WS_URL_CUSTOM, BASE_WS_URL_JSONRPC, BaseAsyncTest class IntentionsHttpTestCase(BaseTest): @classmethod def setUpClass(cls): BaseTest.setUpClass() def setUp(self)...
184615
from functools import partial import numpy as np import torch from torch import nn from counterfactualms.arch.layers import Conv2d, ConvTranspose2d class HierarchicalEncoder(nn.Module): def __init__(self, num_convolutions=3, filters=(16,32,64,128,256), latent_dim=100, input_size=(1,128,128), us...
184638
import lief def lief_from_raw(bytes): """Create a lief binary object from raw bytes""" b_list = list(bytes) lief_binary = lief.parse(raw=b_list) return lief_binary
184687
graphite_url = 'http://graphite.intra.douban.com' graphite_index_url = graphite_url + '/metrics/index.json' metrics_file = 'metrics.json' diamond_cache = 'diamond.cache' debug = False listen_host = '0.0.0.0' listen_port = 8808 try: from local_config import * except: pass
184688
import torch import torch.nn as nn # model class net_le(nn.Module): def __init__(self): super().__init__() def forward(self, inputs): return torch.le(inputs[0], inputs[1]) _model_ = net_le() # dummy input for onnx generation _dummy_ = [torch.randn(1, 2, 3, 3), torch.randn(1, 2, 3, 3)]
184705
from pepnet.encoder import Encoder from nose.tools import eq_ import numpy as np def test_encoder_index_lists(): encoder = Encoder() S_idx = encoder.index_dict["S"] A_idx = encoder.index_dict["A"] index_lists = encoder.encode_index_lists(["SSS", "AAA", "SAS"]) eq_(index_lists, [ [S_idx, S_i...
184724
def multiplication_table(row, col): return [range(a, a * col + 1, a) for a in xrange(1, row + 1)]
184728
from _tutorial import * explorerhat = None name = '' horse = ''' >>\. /_ )`. / _)`^)`. _.---. _ (_,' \ `^-)"" `.\\ | | \\ \ / | / \ /.___.'\ (\ (_ < ,"|| \ |`. \`-' \\\\ () )| )/ hjw |_>|> /_] // /_] ...
184752
from unittest import TestCase from irlib.progress import Progress class TestProgress(TestCase): def setUp(self): self.p = Progress(n=1002, percent=10) def test_progress_counter(self): total = 0 for i in range(0,1002): total += self.p.show(message='Testing progress:', sile...
184795
import os from PIL import Image class SlideCrack(object): def __init__(self, gap_img, bg): self.gap_img = gap_img self.bg = bg @staticmethod def pixel_is_equal(image1, image2, x, y): """ 判断两张图片的像素是否相等,不想等即为缺口位置 :param image1: :param image2: ...
184810
import logging import os import csv import codecs from decimal import Decimal as D import nose from . import pygrowup from six.moves import zip class WHOResult(object): def __init__(self, indicator, values): self.indicator = indicator columns = 'id,region,GENDER,agemons,WEIGHT,_HEIGHT,measure,oe...
184862
from ocdskit.cli.__main__ import main from tests import assert_streaming def test_command(capsys, monkeypatch): assert_streaming(capsys, monkeypatch, main, ['split-record-packages', '1'], ['realdata/record-package_package.json'], ['realdata/record-package_split.json'])
184863
import math import sys import time import numpy as np from fj_refactored import fisher_jenks, fj_generate_sample def testfull(): """ Tests the fully enumerated Fisher-Jenks implementation """ cores = [1,2,4,16,32] classes = [5,6,7] data_sizes = [500, 1000, 2500, 5000, 7500, 10000, 12500, 15000...
184877
import numpy as np from imread import ijrois from . import file_path def test_rois_smoke(): rois = ijrois.read_roi_zip(file_path('rois.zip')) assert len(rois) == 4 r = ijrois.read_roi(open(file_path('0186-0099.roi'), 'rb')) assert any([np.array_equal(ri, r) for ri in rois])
184881
import pandas as pd import sqlalchemy from constants import DB_FOLDER, SYMBOL import matplotlib.pyplot as plt def create_engine(symbol): engine = sqlalchemy.create_engine(f"sqlite:///{DB_FOLDER}/{symbol}-stream.db") return engine def fetch_dataframe(symbol, engine): try: return pd.read_sql(symbo...
184909
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils as nn_utils import torch.backends.cudnn as cudnn from torch.nn import SyncBatchNorm import torch.optim.lr_scheduler as lr_scheduler from torch.nn.parallel import DistributedDataParallel import uti...
184922
import numpy as np import torch.nn as nn from networks.ResidualBlocks import ResidualBlock1dTransposeConv def make_res_block_decoder_feature_generator(channels_in, channels_out, a_val=2.0, b_val=0.3): upsample = None; if channels_in != channels_out: upsample = nn.Sequential(nn.ConvTranspose1d(channe...
184930
import os from typing import NamedTuple from unittest.mock import Mock, sentinel import pytest import requests import requests_mock import vcr from apiclient import APIClient from apiclient.request_formatters import BaseRequestFormatter from apiclient.response_handlers import BaseResponseHandler BASE_DIR = os.path.a...
184952
from __future__ import print_function, division # import sys,os quspin_path = os.path.join(os.getcwd(),"../../") sys.path.insert(0,quspin_path) # from quspin.operators import hamiltonian, exp_op # Hamiltonians, operators and exp_op from quspin.basis import spin_basis_1d # Hilbert space spin basis import numpy as np # g...
185013
import re import string DEFAULT_TOKENIZER_DELIMITER = ' ' def remove_all_whitespace(str): """ Strips all whitespace from a given string. :return: new string without whitespaces, will return the original string if it is empty or None """ if str: return re.sub(r'\s+', '', str) el...
185045
import unittest import sympy from means.approximation.mea.eq_central_moments import eq_central_moments from means.core import Moment from means.util.sympyhelpers import to_sympy_matrix, assert_sympy_expressions_equal class CentralMomentsTestCase(unittest.TestCase): def test_centralmoments_using_p53model(self): ...
185059
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import tensorflow as tf from ccgnet import experiment as exp from ccgnet.finetune import * from ccgnet import layers from ccgnet.layers import * import numpy as np import time import random from sklearn.metrics import bal...
185064
import pytest import sqlalchemy as sa from postgresql_audit import ( add_column, alter_column, change_column_name, remove_column, rename_table ) from .utils import last_activity @pytest.mark.usefixtures('activity_cls', 'table_creator') class TestRenameTable(object): def test_only_updates_giv...
185137
from office365.sharepoint.changes.change import Change class ChangeWeb(Change): @property def web_id(self): return self.properties.get("WebId", None)
185169
from pathlib import Path path = Path().absolute() SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = "sqlite:///" + str(path) + "/Database/database.db" SECRET_KEY = "e9515dfe457bfe64c1c30d73e161de0f76f6b03f"
185242
from .decorator import log_on_start, log_on_error, log_on_end, log_exception __all__ = ["log_on_start", "log_on_error", "log_on_end", "log_exception"]
185259
import os from substance.logs import * from substance import (Command, Box, EngineProfile) from substance.exceptions import (InvalidOptionError) class Create(Command): def getUsage(self): return "substance engine init [options] [ENGINE NAME]" def getHelpTitle(self): return "Create a new engi...
185280
from examples.paper.initialize import * # user settings settings = { # # audit settings 'data_name': 'credit', 'method_name': 'logreg', 'normalize_data': True, 'force_rational_actions': False, # # script flags 'audit_recourse': True, 'plot_audits': True, 'print_flag': True, ...
185293
import unittest import urllib.parse from ingenico.connect.sdk.defaultimpl.authorization_type import AuthorizationType from ingenico.connect.sdk.defaultimpl.default_authenticator import DefaultAuthenticator from ingenico.connect.sdk.request_header import RequestHeader class DefaultAuthenticatorTest(unittest.TestCase)...
185294
import numpy as np from scipy.fft import dct, idct import math def idct_basis_2d(len_basis, num_basis): ''' Generate basic 2D DCT basis for dictionary learning Inputs: len_basis: length of the flattened atom, e.g. 36 for 6x6 basis num_basis: number of the atoms. usually it is o...
185325
from typing import List class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: left, right = 0, len(letters) - 1 while left <= right: middle = left + (right - left) // 2 if letters[middle] <= target: left = middle + 1 else: right =...
185344
import torch EPSILON = 1E-10 def xyxy_to_xywh(boxes_xyxy): assert torch.all(boxes_xyxy[..., 0] < boxes_xyxy[..., 2]) assert torch.all(boxes_xyxy[..., 1] < boxes_xyxy[..., 3]) return torch.cat([ (boxes_xyxy[..., [0]] + boxes_xyxy[..., [2]]) / 2., (boxes_xyxy[..., [1]] + boxes_xyxy[..., [3]...
185386
l = [[True] * 4 for _ in range(4)] def s(r, c): if r == 3 and c == 3: return 1 elif max(r, c) > 3 or min(r, c) < 0: return 0 elif not l[r][c]: return 0 else: l[r][c] = False cnt = s(r + 1, c) + s(r - 1, c) + s(r, c + 1) + s(r, c - 1) l[r][c] = True ...
185414
from datetime import datetime from unittest.mock import Mock import pytest from toucan_connectors.google_sheets_2.google_sheets_2_connector import GoogleSheets2Connector from toucan_connectors.http_api.http_api_connector import HttpAPIConnector from toucan_connectors.json_wrapper import JsonWrapper from toucan_connec...
185416
import logging from typing import Optional class LazyLogger: log_level: int = logging.WARNING log_format: str = "%(name)s: %(levelname)-8s %(message)s" logger_name: str = "dynamoquery" _lazy_logger: Optional[logging.Logger] @property def _logger(self) -> logging.Logger: if self._lazy_...
185431
from django.db import models import datetime #---------------- Drive Profile Logic Function ------------------------# class Category(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=300) ...
185438
from __future__ import print_function import numpy as np import pickle as pkl import networkx as nx import scipy.io as sio import scipy.sparse as sp import scipy.sparse.linalg as slinalg import scipy.linalg as linalg from scipy.sparse.linalg.eigen.arpack import eigsh from sklearn.feature_extraction.text import TfidfTr...
185452
import logging from django.core.management.base import BaseCommand import stats.models import openkamer.dossier import openkamer.parliament import openkamer.kamervraag logger = logging.getLogger(__name__) class Command(BaseCommand): MAX_TRIES = 3 def add_arguments(self, parser): # Named (optional...
185471
import os import numpy as np from PIL import Image from fnmatch import fnmatch def remove_low_resolution_images(path, min_resolution=20): """ A function that removes all the single pixel images Parameters ------------------------- path: str Path to the folder that we would like to clear o...
185501
import os import unittest from tempfile import mkstemp from clips import Environment, Symbol, InstanceName from clips import CLIPSError, ClassDefaultMode, LoggingRouter DEFCLASSES = [ """ (defclass AbstractClass (is-a USER) (role abstract)) """, """(defclass InheritClass (is-a AbstractClass))""...
185511
def test_home_retorna_status_code_200(client): response = client.get("/") assert response.status_code == 200 def test_home_retorna_texto_ola(client): response = client.get("/") assert response.text == "ola" def test_echo_retorna_status_code_200(client): response = client.get("/echo") assert ...
185512
import numpy as np import torch from pytorchrl.distributions.base import Distribution from pytorchrl.misc.tensor_utils import constant class DiagonalGaussian(Distribution): """ Instead of a distribution, rather a collection of distribution. """ def __init__(self, means, log_stds): """ ...
185535
from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense def create_model(): model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(150, 150, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size...
185539
from xgboost_ray.tests.utils import create_parquet def main(): create_parquet( "example.parquet", num_rows=1_000_000, num_partitions=100, num_features=8, num_classes=2) if __name__ == "__main__": main()
185569
from motionAE.src.models import lstmCVAE2 from torch.distributions.kl import kl_divergence from torch.distributions.normal import Normal import torch from motionAE.src.motionCVAETrainer import motionCVAETrainer import numpy as np class motionCVAE2Trainer(motionCVAETrainer): def load_param(self, arg_parser, **kw...
185578
import ui def hide_action(sender): s = sender.superview s['view1'].hidden = True s2 = s['view2'] def a(): s2.transform=ui.Transform.scale(1.0, 1.33).concat(ui.Transform.translation(0,-100)) ui.animate(a, 1.0) def reveal_action(sender): s = sender.superview s2 = s['view2'] ...
185593
import torch import torch.nn as nn class contrastive_loss(nn.Module): def __init__(self, tau=1, normalize=False): super(contrastive_loss, self).__init__() self.tau = tau self.normalize = normalize def forward(self, xi, xj): x = torch.cat((xi, xj), dim=0) is_cuda = x....
185645
from inspect import getmembers from fastapi import FastAPI from tortoise.contrib.starlette import register_tortoise from app.config import tortoise_config from app.utils.api.router import TypedAPIRouter def init(app: FastAPI): """ Init routers and etc. :return: """ init_routers(app) init_db(...
185657
from EventEngine.DyEvent import * class DyStockStrategyState: running = 'sRunning' monitoring = 'sMonitoring' backTesting = 'sBackTesting' def __init__(self, *states): self._state = None self.add(*states) @property def state(self): if self._state is None: ...
185658
import os import sys import random import datetime import time import shutil import numpy as np import pandas as pd import scipy.io import scipy.signal import math from skimage.measure import compare_ssim as sk_ssim import torch from torch import nn class ProgressMeter(object): def __init__(sel...
185691
import argparse import pyBigWig def extract_regions(bwfile, bedfile, chsizefile, bwoutfile): bw = pyBigWig.open(bwfile) bed_el = [] intervals = [] for line in open(bedfile): cols = line.strip().split() intervals.append(bw.intervals(cols[0], int(cols[1]), int(cols[2]))) bed_el....
185695
from common import * import datetime import argparse import time here = os.path.abspath(os.path.dirname(__file__)) app_dir = os.path.join(here, '../dgl/multi_gpu') """ if log_dir is not None, it will only parse logs """ def motivation_test(log_folder=None): tic = time.time() if log_folder: mock...
185696
from .translated_object import TranslatedObject from .base_translator import BaseTranslator BASE_HEADERS: dict = { "User-Agent": "GoogleTranslate/6.6.1.RC09.302039986 (Linux; U; Android 9; Redmi Note 8)", }
185698
import io import pathlib import pytest from mopidy.m3u import translator from mopidy.m3u.translator import path_to_uri from mopidy.models import Playlist, Ref, Track def loads(s, basedir): return translator.load_items(io.StringIO(s), basedir) def dumps(items): fp = io.StringIO() translator.dump_items(...
185734
import random import unittest from podman import PodmanClient from podman.errors import NotFound from podman.tests.integration import base class VolumesIntegrationTest(base.IntegrationTest): def setUp(self): super().setUp() self.client = PodmanClient(base_url=self.socket_uri) self.addCle...
185747
import unittest from test.robotTestUtil import RobotTestUtil class MyTestCase(unittest.TestCase): def test_pose(self): robot = RobotTestUtil.make_fake_dash() packet = {} packet['2002'] = { 'x' : 1.2, 'y' : 3.4, 'degree': 5.6, } ...
185753
from PIL import Image import numpy as np import cv2 PAPER_EXT = {".gloria_chx": "gloria_chx_open_image"} def gloria_chx_open_image(img): def _resize_img(img, scale): """ Args: img - image as numpy array (cv2) scale - desired output image-size as scale x scale Retur...
185760
import copy from dataclasses import dataclass, field import functools from typing import Optional, Tuple from pycparser import c_ast as ca from .compiler import Compiler from .randomizer import Randomizer from .scorer import Scorer from .perm.perm import EvalState from .perm.ast import apply_ast_perms from .helpers i...
185763
import pickle import re from unidecode import unidecode from collections import defaultdict from math import log from opentapioca.readers.dumpreader import WikidataDumpReader separator_re = re.compile(r'[,\-_/:;!?)]? [,\-_/:;!?(]?') def tokenize(phrase): """ Split a text into lists of words """ words...