id
stringlengths
3
8
content
stringlengths
100
981k
1764334
from sklearn.preprocessing import StandardScaler from abc import ABC, abstractmethod import numpy as np class DistanceMetric(ABC): """Computes distances and defines the optimization model for both exploration and penalty. Parameters ---------- - Attributes ---------- - """ ...
1764335
import math a = int(input("Enter a ")) b = int(input("Enter b ")) c = int(input("Enter c ")) d = (b**2) - (4*a*c) root1 = (-b-math.sqrt(d))/(2*a) root2 = (-b+math.sqrt(d))/(2*a) print('The solution are {} and {}'.format(root1,root2)) x = int(input("Enter x ")) y = int(input("Enter y ")) result=(((2*x*y)-(9*...
1764343
import os import os.path as osp from pathlib import Path import logging import pandas as pd from gluonts.dataset.repository.datasets import get_dataset from gluonts.dataset.multivariate_grouper import MultivariateGrouper from gluonts.dataset.common import TrainDatasets logger = logging.getLogger(__name__) os.enviro...
1764371
import os import math import asyncio from concurrent.futures.process import ProcessPoolExecutor from grpclib.utils import graceful_exit from grpclib.server import Stream, Server from google.protobuf.wrappers_pb2 import BoolValue # generated by protoc from .primes_pb2 import Request, Reply from .primes_grpc import Pr...
1764414
from sections import Section, Section2D from sections import CoRenderedSection, SketchSection from manager import SectionManager, AutoManager, GeoprobeManager from manager import ExampleSections, NankaiSections from horizons import HorizonSet from wells import WellSet, Well, WellDatabase from maps import Map __all__ =...
1764460
from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ("mp", "0008_auto_20151018_2208"), ] operations = [ migrations.AlterField( model_name="payment", name="notification", field=models.One...
1764516
import os import re from oelint_parser.cls_item import Variable from oelint_adv.cls_rule import Rule class VarDependsOrdered(Rule): def __init__(self): super().__init__(id="oelint.vars.dependsordered", severity="warning", message="'{VAR}' entries should b...
1764538
import torch import torch.nn as nn from ...ops.pointnet2.pointnet2_batch import pointnet2_modules from ...ops.roipoint_pool3d import roipoint_pool3d_utils from ...utils import common_utils from ...ops.iou3d_nms import iou3d_nms_utils from .roi_head_template import RoIHeadTemplate class PointRCNNIoUHead(RoIHeadTemplat...
1764550
from __future__ import print_function, division import os import shutil import tempfile import numpy as np from numpy.testing import assert_array_almost_equal_nulp import pytest import six from .. import Model from ..sed import SED from ...util.functions import random_id from .test_helpers import get_test_dust cl...
1764563
import functools import logging import os import sys @functools.lru_cache() # so that calling setup_logger multiple times won't add many handlers def setup_logger(output_dir, distributed_rank=0, name="monoflex", file_name="log.txt"): ''' Args: output_dir (str): a directory saves output log files ...
1764568
import torch from torch import nn, optim, multiprocessing from torch.utils.data import DataLoader import numpy as np from tensorboardX import SummaryWriter from time import time from utils.train_utils import CheckpointManager, make_grid_triplet, make_k_grid from utils.run_utils import get_logger class ModelTrainer...
1764599
class LogmeError(Exception): """Used as a general error for the logme module""" class MisMatchScope(Exception): """Used when scope and passed callable is mismatched""" class InvalidOption(Exception): """Used when the an option is invalid""" class InvalidLoggerConfig(Exception): """Used when invali...
1764674
from uvicorn.workers import UvicornWorker from .settings import settings class RunboatUvicornWorker(UvicornWorker): # type: ignore if settings.log_config: UvicornWorker.CONFIG_KWARGS["log_config"] = settings.log_config
1764675
import os import sys from typing import Tuple import inquirer from cli.platform.error import CliError from winnow.pipeline.pipeline_context import PipelineContext from winnow.remote.connect import RepoConnector def ask_password( message, literal_pass: Tuple[str, str] = (None, None), file_pass: Tuple[str, str] =...
1764718
from aetherling.modules.hydrate import Hydrate, Dehydrate from aetherling.modules.map_fully_parallel_sequential import MapParallel from magma.simulator.coreir_simulator import CoreIRSimulator import coreir from magma.scope import Scope from aetherling.helpers.image_RAM import * from aetherling.modules.upsample import U...
1764719
from immobilus import immobilus import time def test_gmtime(): with immobilus('2015-11-16 21:35:16'): time_struct = time.gmtime() assert time_struct.tm_year == 2015 assert time_struct.tm_mon == 11 assert time_struct.tm_mday == 16 assert time_struct.tm_hour == 21 as...
1764727
import torch.nn as nn from .base_rnn import BaseRNN class Encoder(BaseRNN): """Encoder RNN module""" def __init__(self, vocab_size, max_len, word_vec_dim, hidden_size, n_layers, input_dropout_p=0., dropout_p=0., bidirectional=False, rnn_cell='lstm', variable_lengths=False, w...
1764758
from datetime import datetime import pandas as pd from IPython.display import display, Markdown display(Markdown( 'Loaded variable-table.py at {}' .format(str(datetime.now())) )) input_types_1 = { '1st': 'toggle', '3rd': 'number', '4th': 'dropdown', '5th': 'dropdown', '6th': 'readonly' }...
1764759
from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.test import TestCase, override_settings from flags.conditions.validators import ( validate_boolean, validate_date, validate_parameter, validate_path_re, validate_user, ) class ValidatePar...
1764788
num1=float(input('Enter the first number:')) num2=float(input('Enter the second number:')) print(num1+num2)
1764890
import numpy as np import warnings warnings.filterwarnings("ignore") import tensorflow as tf from tensorflow import keras tf.compat.v1.enable_eager_execution() import matplotlib.pyplot as plt from model_utils import save_model # construct TensorFlow model model = keras.Sequential() model.add(keras.layers.InputLayer(in...
1764914
from django.urls import path from .views import LocationList, LocationDetail, add_or_change_location, delete_location urlpatterns = [ path("", LocationList.as_view(), name="location_list"), path("add/", add_or_change_location, name="add_location"), path("<uuid:pk>/", LocationDetail.as_view(), name="locati...
1764923
import ctypes import epics.dbr as dbr def _build_args(dbr_type, c_data): args = dbr.event_handler_args() args.type = dbr_type args.count = len(c_data) args.raw_dbr = ctypes.cast(c_data, ctypes.c_void_p) args.status = dbr.ECA_NORMAL return args def test_cast_args(): # cast_args casts a si...
1765029
assert 100000000000 ** 10 == 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 a = 1000000000000 assert str(a) == "1000000000000" assert str(a * a) == "1000000000000000000000000" print("ok")
1765070
import torch from torch import nn from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence from ..utils.generic_utils import to_cuda class EmbeddingConstructionBase(nn.Module): """ Base class for (initial) graph embedding construction. ... Attributes ---------- feat : dict ...
1765107
from __future__ import print_function #This is to train the network by running: python single1_train.py <experiment_name> <obj_id> #e.g.: python single1_train.py subdiv_29_softmax_edge 29 #Prerequisite before training: #cfg file: <experiment_name>.cfg under the path: path_workspace/cfg/<experiment_name>.cfg #Rendered ...
1765114
from django.contrib import admin from django.conf import settings from django.contrib.admin import SimpleListFilter from freeradmin.models import Raduser, Radcheck, Radreply, Radgroup, Vlan, Mac # CUSTOM ADMIN FILTERs class UsersByVlanListFilter(SimpleListFilter): # Human-readable title which will be displayed in...
1765138
import unittest from datetime import datetime from datetime import timedelta from programy.services.library.base import PythonAPIService from programy.services.library.base import PythonAPIServiceException from programy.services.config import ServiceConfiguration class PythonAPIServiceExceptionTests(unittest.TestCase...
1765200
from setuptools import setup with open("../README.md") as f: readme = f.read() version = "v1.4_wip" setup( name="ruffini", version=version, description="Monomials, Polynomials and lot more!", long_description=readme, long_description_content_type="text/markdown", author="<NAME>", auth...
1765218
import gen_layer import math label_source = "/ssd/ijcai18/data/agnews" #training and testing label generated by 'gen_data.py' data_source = "/ssd/ijcai18/data/agnews" #training and testing data generated by 'gen_data.py' local_dict_source = "/ssd/ijcai18/data/agnews/local_dict.txt" #local dict generated by 'gen_data.p...
1765236
import os import sys import pandas as pd from datetime import datetime sys.path.append('src') from Broker import Robinhood # noqa autopep8 import Constants as C # noqa autopep8 rh = Robinhood() if not C.CI: rh.writer.store.bucket_name = os.environ['S3_DEV_BUCKET'] rh.reader.store.bucket_name = os....
1765260
from starkeffect import * from ext.las_str.SimplexModMPF import Simplex from mpmath import * import sys class Stark_calcSS: def __init__(self,_n1, _n2, _m, point_ground_state): mp.prec = 10000 self.n1 = _n1 self.n2 = _n2 self.m = abs(_m) ...
1765272
from csv import reader import sys import os import time import subprocess import sys from subprocess import DEVNULL if len(sys.argv) < 2: print('usage: python3 {} <out dir>'.format(sys.argv[0])) sys.exit(-1) fin = sys.stdin outdir = sys.argv[1] def version(prog): try: subprocess.check_call(['p4tes...
1765292
class Test(object): @classmethod def setUpClass(cls): cls.setup = 1 @classmethod def tearDownClass(cls): del cls.setup def setUp(self): self.test_setup = 1 def tearDown(self): del self.test_setup def test(self): assert self.test_setup asser...
1765331
import os import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import torchmetrics from model.seq2seq import JointNLU from util.conf_util import read_conf from util.dataset_util import DatasetUtil device = "cuda" if torch.cuda.is_available() else "cpu" print(f"device...
1765350
from setuptools import setup, find_packages setup(name='code_transformer', version='0.1', description='Code Transformer', author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>,<EMAIL>', packages=find_packages(), install_requires=['jsonlines==1.2.0', 'rouge==1.0.0', ...
1765353
from django.core.management.base import BaseCommand from hc.api.models import Flip from hc.lib.date import month_boundaries class Command(BaseCommand): help = "Prune old Flip objects." def handle(self, *args, **options): threshold = min(month_boundaries(months=3)) q = Flip.objects.filter(cr...
1765363
import copy import numpy as np from mmhuman3d.data.datasets import HumanImageDataset from mmhuman3d.data.datasets.pipelines import ( LoadImageFromFile, MeshAffine, RandomHorizontalFlip, ) def test_human_image_dataset(): # test auto padding for bbox_xywh train_dataset = HumanImageDataset( ...
1765384
from conans import ConanFile class libembeddedhal_conan(ConanFile): name = "libembeddedhal" version = "0.0.1" license = "Apache License Version 2.0" author = "<NAME>" url = "https://github.com/SJSU-Dev2/libembeddedhal" description = "A collection of interfaces and abstractions for embedded per...
1765395
import os.path import click import tensorflow as tf import numpy import pkg_resources import sklearn.model_selection from xtreme_vision.Detection.keras_resnet import metrics as m from xtreme_vision.Detection.keras_resnet import models _benchmarks = { "CIFAR-10": tf.keras.datasets.cifar10, "CIFAR-100": tf.ker...
1765411
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(zip(s, t))) == len(set(s)) == len(set(t))
1765444
import os, sys import configparser import serial import logging from LogReader import LogReader from EncoderReader import EncoderReader import math import tkinter import collections import pandas from matplotlib import pyplot import numpy as np import scipy.signal logging.basicConfig(level=os.environ.get("LOGLEVEL", "...
1765455
import argparse import sys from vcstool.streams import set_streams from .command import Command from .command import simple_main class StatusCommand(Command): command = 'status' help = 'Show the working tree status' def __init__(self, args): super(StatusCommand, self).__init__(args) se...
1765465
def extractJiamintranslationCom(item): ''' Parser for 'jiamintranslation.com' ''' if 'Calligraphy' in item['tags']: return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('HAWRR', 'Quic...
1765496
from autograd.tracer import primitive, getval from autograd.extend import defvjp from autograd.test_util import check_grads from nose.tools import assert_raises_regexp def test_check_vjp_1st_order_fail(): @primitive def foo(x): return x * 2.0 defvjp(foo, lambda ans, x : lambda g: g * 2.001) as...
1765504
from datetime import datetime, timedelta from vnpy.trader.gateway.oandaGateway import OandaGateway from vnpy.trader.vtEngine import EventEngine from vnpy.trader.app.ctaStrategy.histbar._base import BarReader, freq_minutes from vnpy.trader.app.ctaStrategy.histbar._test import test class OandaBarReader(BarReader): ...
1765522
import os from typing import Dict, NamedTuple, Optional import numpy as np try: import wandb wandb.ensure_configured() if wandb.api.api_key is None: _has_wandb = False wandb.termwarn("W&B installed but not logged in. Run `wandb login` or set the WANDB_API_KEY env variable.") else: ...
1765540
import tkinter as tk import tk_tools if __name__ == '__main__': root = tk.Tk() tk.Label(root, text="The variable value: ").grid(row=0, column=0) value_label = tk.Label(root, text="") value_label.grid(row=0, column=1) def callback(value): value_label.config(text=str(value)) # specify...
1765563
import gzip import os import shutil from pathlib import Path from tempfile import NamedTemporaryFile import pytest import skhep_testdata import pylhe TEST_FILE = skhep_testdata.data_path("pylhe-testfile-pr29.lhe") @pytest.fixture(scope="session") def testdata_gzip_file(): test_data = skhep_testdata.data_path("...
1765564
import pytest from django.contrib.auth.models import Group from django.urls import reverse from guardian.shortcuts import get_group_perms, get_objects_for_group class TestGroupView: def test_group_list_permission_required(self, django_app, volunteer): response = django_app.get(reverse("core:group_list"), ...
1765585
import os from deepblast.dataset.utils import state_f, revstate_f import pandas as pd import numpy as np from collections import Counter def read_mali(root, tool='manual', report_ids=False): """ Reads in all alignments. Parameters ---------- root : path Path to root directory tool : str ...
1765598
from boa3.builtin.interop.contract.contractmanifest import ContractManifest from boa3.builtin.type import UInt160 class Contract: """ Represents a contract that can be invoked. :ivar id: the serial number of the contract :vartype id: int :ivar update_counter: the number of times the contract was ...
1765603
from __future__ import division # LIBTBX_SET_DISPATCHER_NAME qr.fragmentation import sys import time import os.path import libtbx import iotbx.pdb from qrefine.fragment import fragments from qrefine.fragment import fragment_extracts from qrefine.fragment import get_qm_file_name_and_pdb_hierarchy from qrefine.fragment i...
1765609
from typing import Any, Dict, Tuple, Union import torch from torchsparse.utils import make_ntuple __all__ = ['SparseTensor', 'PointTensor'] class SparseTensor: def __init__(self, feats: torch.Tensor, coords: torch.Tensor, stride: Union[int, Tuple[int, ...]] =...
1765625
import unittest import crestdsl.model as crest from crestdsl.simulation.z3calculator import uses_dt_variable class uses_dt_variableTest(unittest.TestCase): def test_finds_used_dt(self): @crest.update(state="some_state", target="some_port") def myUpdate(self, dt): a = 133 ...
1765644
from __future__ import print_function import flydra_analysis.a2.core_analysis as core_analysis import numpy as np import flydra_analysis.a2.utils as utils class EquivalentObjectFinder: def __init__(self, src_h5, dst_h5): self.ca = core_analysis.get_global_CachingAnalyzer() self.src_h5 = src_h5 ...
1765654
from django.conf import settings from rest_framework import serializers from musics.models import Music class MusicSerializer(serializers.ModelSerializer): # If your <field_name> is declared on your serializer with the parameter required=False # then this validation step will not take place if the field is n...
1765738
import random import string import subprocess import os import tempfile import re import sys from datetime import timedelta from subprocess import DEVNULL, STDOUT, PIPE class Transcode: """ Transcode is a wrapper around the ffmpeg binary used to transcode audio from media files. """ def __init__(...
1765755
import mock import ckan.tests.factories as factories import ckan.model as model import ckan.plugins.toolkit as tk import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base from ckanext.hdx_org_group.helpers.static_lists import ORGANIZATION_TYPE_LIST config = tk.config NotAuthorized = tk.NotAuthorized class Te...
1765789
import unittest import unittest.mock import programytest.storage.engines as Engines from programy.storage.stores.sql.config import SQLStorageConfiguration from programy.storage.stores.sql.engine import SQLStorageEngine from programy.storage.stores.sql.store.sqlstore import SQLStore class SQLStoreTests(unittest.TestCa...
1765814
from . import tools from . import formula from . import linear from . import testing from .formula import ( Factor, Term, Formula, Real, Categ, Demean, Binned, Custom, I, R, C, D, B, robust_eval, factor, design_matrices ) from .linear import ols from .testing import dataset try: from .general import ( ...
1765869
import glob import os import shutil from universal_build import build_utils HERE = os.path.abspath(os.path.dirname(__file__)) REACT_WEBAPP_COMPONENT = "react-webapp" DOCS_COMPONENT = "docs" PYTHON_LIB_COMPONENT = "python-lib" DOCKER_COMPONENT = "docker" def main(args: dict) -> None: """Execute all component bu...
1765906
from setuptools import setup import sys classifiers = """\ Intended Audience :: Developers License :: OSI Approved :: Apache Software License Development Status :: 4 - Beta Natural Language :: English Programming Language :: Python :: 2.7 Operating System :: MacOS :: MacOS X Operating System :: Unix Programming Langua...
1765955
import json from datetime import datetime, timedelta import pytz from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from helium.auth.tasks import expire_auth_tokens from helium.auth.tests.helpers import userhe...
1765957
import click import tabulate # describes how to align the individual table columns colalign = ( "left", # date "left", # description "left", # ticker "left", # action "right", # qty "right", # price "right", # commission "right", # currency ) def capgains_show(transaction...
1765978
import tensorflow as tf import selfsup import os from .base import Method from autocolorize.tensorflow.sparse_extractor import sparse_extractor from autocolorize.extraction import calc_rgb_from_hue_chroma import functools from collections import OrderedDict import numpy as np def kl_divergence(labels, logits): #re...
1765987
class CompactSet: def __init__(self, numbers = None, bits = None): self.bits = bits or 0 if numbers: for n in numbers: self.add(n) def add(self, n): self.bits |= 1 << n def remove(self, n): self.bits &= ~(1 << n) def clear(self): ...
1766000
def xgcd( x, y ): old_r, r = (x, y) old_s, s = (1, 0) old_t, t = (0, 1) while r != 0: quotient = old_r // r old_r, r = (r, old_r - quotient * r) old_s, s = (s, old_s - quotient * s) old_t, t = (t, old_t - quotient * t) return old_s, old_t, old_r # a, b, g class Fie...
1766007
import json import boto3 import cfnresponse from botocore.exceptions import ClientError import time rds_data = boto3.client('rds-data') rds_client = boto3.client('rds') s3 = boto3.resource('s3') def create(properties, physical_id): print("Create Event and Properties: {}".format(json.dumps(properties))) cluster =...
1766014
import argparse import os from dataset import * from models.cnn_block_frame_flow import CNNBlockFrameFlow from train_helper import * if __name__ == "__main__": parser = argparse.ArgumentParser(description="Block Frame&Flow ConvNet") parser.add_argument("--dataset_dir", type=str, default="data", ...
1766017
import argparse import json import numpy as np import os import shutil import sqlite3 import sys import types import torch from utils import translate_descriptors, build_hybrid_database, match_features, geometric_verification, reconstruct, blob_to_array, compute_extra_stats sys.path.append(os.getcwd()) from l...
1766114
import tensorflow.keras as keras # call this to stop training class myStopCallback(keras.callbacks.Callback): def __init__(self): self.stop_me = False def on_epoch_begin(self, epoch, logs={}): if self.stop_me: self.model.stop_training = True def on_epoch_end(self, epoch, logs...
1766155
import constants as con def main_menu(): # Display a welcome message print("Welcome to {}".format(con.GAME_NAME)) print("Here are your choices: {}".format(con.MAIN_MENU_CHOICES)) user_input = input("> ").lower().strip() while not user_input in con.MAIN_MENU_CHOICES: print("Sorry, I didn’t r...
1766186
from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from user import models from user import forms class UserAdmin(DefaultUserAdmin): """ The class for enabling the django admin interface to interact with the c...
1766195
from ...managers import get_python_manager from . import _get_opposite_operator class MetaField: def __init__(self, name, index=None, meta_condition=None, meNode=None, t=None, reMetaNode=None): if (meta_condition is not None) and (meNode is not None): raise ValueError("you cannot mix condition...
1766203
class SlavesBaseException(Exception): pass class SlaveIsLocked(SlavesBaseException): pass class InvalidSign(SlavesBaseException): pass class UnknownError(SlavesBaseException): pass
1766210
import dataclasses import pytest from dddpy.domain.book import Isbn class TestIsbn: @pytest.mark.parametrize( "value", [ ("978-0321125217"), ("978-4-949999-12-0"), ], ) def test_constructor_should_create_instance(self, value): isbn = Isbn(value) ...
1766229
import os import sys import json import logging import argparse import uuid import time from shutil import copyfile import shure import offline import tornado_server APPNAME = 'micboard' CONFIG_FILE_NAME = 'config.json' FORMAT = '%(asctime)s %(levelname)s:%(message)s' config_tree = {} gif_dir = '' group_update_l...
1766260
from enum import Enum, unique __all__ = ['ParserEnum', 'CommonEnum'] @unique class ParserEnum(Enum): MENHIR = 'menhir' DYPGEN = 'dypgen' PWZ_NARY = 'pwz_nary' PWZ_NARY_LIST = 'pwz_nary_list' PWZ_NARY_LOOK = 'pwz_nary_look' PWZ_BINARY = 'pwz_binary' PWD_BINARY = 'pwd_binary' PWD_BINAR...
1766276
from __future__ import print_function import time import tensorflow as tf from six.moves import xrange def model(x, nlogits, train=False): b = tf.shape(x)[0] if args.infer_legacy: window = tf.contrib.signal.hann_window(1024) windows = [] for i in xrange(0, 16384, 128): x_window = x[:, i:i+102...
1766331
from .decoders import WienerFilterDecoder, WienerCascadeDecoder, KalmanFilterDecoder,\ DenseNNDecoder, SimpleRNNDecoder, GRUDecoder, LSTMDecoder, XGBoostDecoder, SVRDecoder, NaiveBayesDecoder from .metrics import get_R2, get_rho from .preprocessing_funcs import bin_output, bin_spikes, get_spikes_with_histor...
1766347
import warnings from torch.optim.lr_scheduler import ReduceLROnPlateau from .base import BaseHook from .registry import HOOKS @HOOKS.register_module class LRSchedulerHook(BaseHook): def __init__(self, monitor_metric="loss", by_epoch=True): self.monitor_metric = monitor_metric self.by_epoch = by_...
1766352
import torch import torch.nn.functional as F from medical_seg.networks.nets.swin_transformer.model_2 import StageModule ## 官方代码为model.py 这个改起来比较困难,model_2 是非官方实现 model_patch_conv 是在model_2的基础上把unfold操作换成了卷积 # # # 测试unfold函数。 # x = torch.randn(1, 2, 64, 64, 64) # x = x.squeeze(dim=0) # kc, kh, kw = 16, 16, 16 # ker...
1766356
import random from copy import deepcopy import numpy as np from sklearn.datasets import make_classification from sklearn.metrics import roc_auc_score as roc_auc from core.composer.chain import Chain from core.composer.composer import DummyComposer, DummyChainTypeEnum, ComposerRequirements from core.models.da...
1766369
import argparse import os from pprint import pprint import yaml from autogluon.vision import ImagePredictor def get_input_path(path): file = os.listdir(path)[0] if len(os.listdir(path)) > 1: print(f'WARN: more than one file is found in {path} directory') print(f'Using {file}') filename = f'{p...
1766398
from . import packet class Packet32(packet.Packet): def __init__(self, player): super(Packet32, self).__init__(0x32) self.add_data(player.playerID) for i in range(0, 22): self.add_data(0)
1766452
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('error', '0005_auto_20180621_2110'), ] def update_should_be_retried(apps, schema_editor): # Go through all of the Error models and update which ones should ...
1766453
import unittest from jsom import JsomParser, SINGLE_QUOTED_STRING, UNQUOTED_STRING, \ EMPTY_OBJECT_VALUE, TRAILING_COMMA_IN_OBJECT, TRAILING_COMMA_IN_ARRAY, \ ALL_WARNINGS class TestWarnings(unittest.TestCase): def setUp(self): self.parser = JsomParser() def test_single_quoted_string_warning...
1766455
import re import re import os import sys import pprint import platform import subprocess from setuptools.command.install import install from setuptools.command.build_ext import build_ext from setuptools import setup, Extension, find_packages WITH_MPI = False opt_flags = { 'Release': { 'unix': ['-O3', '-DN...
1766472
import copy import pytest from datasette.app import Datasette @pytest.mark.asyncio async def test_dashboard_views(datasette): dashboards = datasette._metadata["plugins"]["datasette-dashboards"] for slug, dashboard in dashboards.items(): response = await datasette.client.get(f"/-/dashboards/{slug}") ...
1766494
import numpy as np from datetime import datetime from .routine import get_fix_string, get_fix_list from .routine import get_equal_strings, get_equal_lists from .models.base_model import MODEL_NAME_LENGTH UP_END = "┌" DOWN_END = "└" MIDDLE = "├" LAST = "┤" EMPTY = "│" START_END = "┐" SPACE = " " USELESS_SUBKEYS = { ...
1766506
from __future__ import absolute_import from sentry.testutils import TestCase class StaticMediaTest(TestCase): def test_basic(self): url = '/_static/sentry/app/index.js' response = self.client.get(url) assert response.status_code == 200, response assert 'Cache-Control' not in respo...
1766548
import yaml from transible.plugins.os_ansible.const import DEFAULTS from transible.plugins.os_ansible.config import VARS_PATH class ExtraDumper(yaml.Dumper): """Custom dumper for YAML """ def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def ya...
1766583
import numpy as np import pandas as pd from keras.utils import to_categorical from scipy.signal import butter, lfilter # @sp - remove unused imports from imblearn.over_sampling import SMOTE def conv_arrays_to_df(train_x, train_y, params): n_steps = train_x.shape[2] # number of samples per 30 seconds train_y...
1766604
import json import argparse from tornado import web, ioloop, queues, gen, process from server import ApiHandler, TranslatorWorker, initialize_workers, settings class ElgApiHandler(ApiHandler): def post(self, src_lang, target_lang): self.prepare_args() lang_pair = "{}-{}".format(src_lang, tar...
1766618
from __future__ import division, unicode_literals from django.test import override_settings from django.contrib.auth import get_user_model from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException from selenium.webdriver.support.wait import WebDriverWait from .testcase import ...
1766657
import csv rows = [] with open("output.csv", "rb") as csvFile: reader = csv.reader(csvFile) for row in reader: rows.append(row) rows.sort(key=lambda x: x[2]) for row in rows: print row f = open("pic.dot", "w") f.write("digraph {\n\nrankdir = TB\n\n") #print rows[0][4] + ' ** ' + rows[0][5] ...
1766670
import math import torch import random import unittest import itertools import contextlib from copy import deepcopy from itertools import repeat, product from functools import wraps import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel as dp import torch.nn.utils.rnn as rnn_utils from torch.nn...
1766680
import scipy.io as sio import numpy as np from PIL import Image from pathlib import Path import sys sys.path.append('.') from util import data from dataloader import SSLDataset class SVHNSSL(SSLDataset): def read_x(self, idx): return Image.fromarray(self.x[idx].copy()) @staticmethod def split_da...
1766695
from multiprocessing import freeze_support from rdkit import Chem from mordred import Chi, ABCIndex, RingCount, Calculator, is_missing, descriptors if __name__ == "__main__": freeze_support() benzene = Chem.MolFromSmiles("c1ccccc1") # Create empty Calculator instance calc1 = Calculator() # Reg...