id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3232237 | import numpy
for _ in range(int(input())):
n=int(input())
ar=[]
for i in range(n):
x=list(map(int,input().split()))
ar.append(x)
det = numpy.linalg.det(ar)
print(int(det)) |
3232239 | import warnings
from dataclasses import dataclass
from enum import Enum
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from duckdq import VerificationSuite
from duckdq.checks import CheckStatus, Check, CheckLevel
from duckdq.utils.exceptions import Da... |
3232279 | import argparse
import os
import unittest
from quarkchain.cluster.cluster_config import ClusterConfig
class TestClusterConfig(unittest.TestCase):
def test_cluster_dict_with_loadtest(self):
"""convert to dict and back to check if the content changed, requires `__eq__`
removing --loadtest will make... |
3232289 | import argparse
import gdb
import pwndbg.arch
import pwndbg.argv
import pwndbg.commands
import pwndbg.typeinfo
@pwndbg.commands.ArgparsedCommand("Prints out the number of arguments.")
@pwndbg.commands.OnlyWhenRunning
def argc():
print(pwndbg.argv.argc)
parser = argparse.ArgumentParser()
parser.description = "... |
3232293 | from .TftEndpoint import TftEndpoint
class MatchEndpoint(TftEndpoint):
def __init__(self, url: str, **kwargs):
nurl = "/match/v1/matches" + url
super().__init__(nurl, **kwargs)
class MatchApiUrls:
by_puuid = MatchEndpoint("/by-puuid/{puuid}/ids", count=int)
by_id = MatchEndpoint("/{match... |
3232294 | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
def downsample(x, x_len, sample_rate, sample_style):
batch_size, timestep, feature_dim = x.shape
x_len = x_len // sample_rate
if sample_style == 'drop':
# Drop the unselected timesteps
... |
3232310 | import keras
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Dropout, Input
batch_size = 128
num_classes = 10
epochs = 10
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_trai... |
3232324 | class OperateDevices(object):
def __init__(self):
self.deviceGroups = None
self.deviceType = None
self.model = None
self.manufacturerName = None
self.devices = None
def getDeviceGroups(self):
return self.deviceGroups
def setDeviceGroups(self, deviceGroups):... |
3232328 | from ..schema.nexusphp import NexusPHP
from ..schema.site_base import SignState, NetworkState, Work
from ..utils.net_utils import NetUtils
class MainClass(NexusPHP):
URL = 'https://pt.hd4fans.org/'
USER_CLASSES = {
'downloaded': [805306368000, 3298534883328],
'share_ratio': [3.05, 4.55],
... |
3232331 | from delorean import parse
import traceback
from poget import LOGGER
'''
This method is used to get hour
'''
def get_hour(value):
parsed_date = parse(value).datetime.hour
return parsed_date
def get_day(value):
parsed_date = parse(value).datetime.isoweekday()
return parsed_date
def get_categoric... |
3232347 | from time import sleep
from utils.thread import BackgroundRepeater
class RepeaterTest(BackgroundRepeater):
def __init__(self, iterations: int):
self.iterations = iterations
self.iteration_count = 0
super().__init__(sleep_interval=0.1)
def _do_run(self) -> bool:
self.iteratio... |
3232365 | import pandas as pd
from matplotlib import pyplot as plt
from geneviz.tracks import plot_tracks
from geneviz.tracks.feature import FeatureTrack
import seaborn as sns
sns.set_style('white')
# Setup features.
features = pd.DataFrame.from_records([
('1', 10, 25, 1, 'a', 'a'),
('1', 30, 40, None, 'a', 'b... |
3232372 | class Delegator:
# The cache is only used to be able to change delegates!
def __init__(self, delegate=None):
self.delegate = delegate
self.__cache = set()
def __getattr__(self, name):
attr = getattr(self.delegate, name) # May raise AttributeError
setattr(self, name, attr)
... |
3232410 | import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
class ClassificationDataset(Dataset):
def __init__(self, file_paths, targets, augmentations = None):
self.files = file_paths
self.targets = targets
self.augmentations = augmentations
def _... |
3232429 | import csv
import glob
import gensim
import nltk
import numpy as np
from typing import Dict, List, TextIO
from sklearn.preprocessing import OrdinalEncoder
from sklearn.utils import shuffle
from collections import Counter
import json
# nltk.download('punkt')
# When calling the function the user must decide if he/she w... |
3232441 | import logging
import os
from logging import handlers
def get_logger(LOG_ROOT, level=logging.DEBUG, back_count=0,cmd_stream=False):
"""
:brief 日志记录
:param log_filename:
:param level:
:param back_count:
:return: logger
"""
logger = logging.getLogger("logger.log")
logger.setLevel(le... |
3232472 | from SublimeLinter.lint import ComposerLinter
class Phpcs(ComposerLinter):
cmd = ('phpcs', '--report=emacs', '${args}', '-')
regex = r'^.*:(?P<line>[0-9]+):(?P<col>[0-9]+): (?:(?P<error>error)|(?P<warning>warning)) - (?P<message>(.(?!\(\S+\)$))+)( \((?P<code>\S+)\)$)?' # noqa: E501
defaults = {
'... |
3232481 | import pickle
import unittest
from betfairlightweight import exceptions
class ExceptionsTest(unittest.TestCase):
def test_betfair_error(self):
with self.assertRaises(exceptions.BetfairError):
raise exceptions.BetfairError("test")
# pickle
error = exceptions.PasswordError("test... |
3232510 | import numpy as np
import pylas
def test_mmap(mmapped_file_path):
with pylas.mmap(mmapped_file_path) as las:
las.classification[:] = 25
assert np.all(las.classification == 25)
las = pylas.read(mmapped_file_path)
assert np.all(las.classification == 25)
|
3232520 | from __future__ import absolute_import
from .validator import *
class Field(object):
def __init__(self, source=None, required=False, many=False, default=None, allow_null=True):
self._source = source
self._data = None
self.data = None
self._many = many
self._errors = []
... |
3232578 | from floem import *
pkt_size = 1024 #1024
class Request(Element):
def configure(self):
self.inp = Input(SizeT, "void*", "void*")
self.out = Output(SizeT, "void*", "void*")
def impl(self):
self.run_c(r'''
(size_t size, void* pkt, void* buff) = inp();
udp_message* m = (udp_message*) pkt... |
3232588 | from django.urls import path
from paypal.express_checkout import views
from paypal.express_checkout.gateway import buyer_pays_on_paypal
base_patterns = [
# Views for normal flow that starts on the basket page
path('redirect/', views.PaypalRedirectView.as_view(), name='express-checkout-redirect'),
path('ca... |
3232598 | import re
import pandas as pd
def parse_region_string(region: str):
feat_list = re.split("-|:", region)
feature_df = pd.DataFrame(columns=["Chromosome", "Start", "End"])
feature_df.loc[0] = feat_list
feature_df = feature_df.astype({"Start": int, "End": int})
return feature_df
|
3232606 | from ptstrategy import PTStrategy
import pandas as pd
import numpy as np
import datetime as dt
import backtrader as bt
class DistStrategy(PTStrategy):
def __init__(self):
super().__init__()
self.resid_mean = None
self.resid_std = None
def log_status(self):
stat... |
3232619 | import torch
# import sys
# sys.path.insert(0, '/n/scratch2/xz204/Dr37/lib/python3.7/site-packages')
from deeprobust.graph.targeted_attack import Nettack
from deeprobust.graph.utils import *
from deeprobust.graph.data import Dataset
import argparse
from deeprobust.graph.defense import * # GCN, GAT, GIN, JK, GCN_attack,... |
3232623 | import json
import unittest
import time
import cryptomarket.args as args
from test_helpers import *
from cryptomarket.client import Client
from cryptomarket.exceptions import ArgumentFormatException
from cryptomarket.exceptions import CryptomarketSDKException
with open('/home/ismael/cryptomarket/apis/keys.json') ... |
3232641 | import requests
import json
import os
import time
from tqdm import tqdm
from bs4 import BeautifulSoup
from typing import List, Dict
class Scraper:
"""
Scrape data from PCPartPicker from given product `endpoints`.
Note that requests may hang for a while depending on how many endpoints
there are, and h... |
3232658 | import glob
import os
import pathlib
import re
from collections import defaultdict
from typing import Dict, Union
REGEX_ENTITY = re.compile(r'^(T\d+)\t([^\s]+)([^\t]+)\t(.*)$')
REGEX_NOTE = re.compile(r'^(#\d+)\tAnnotatorNotes ([^\t]+)\t(.*)$')
REGEX_STATUS = re.compile(r'^(#\d+)\tStatus ([^\t]+)\t(.*)$')
REGEX_RELATI... |
3232669 | import pytest
from ombpdf import paragraphs
from . import bbox
def test_annotate_paragraphs_works(m_16_19_doc):
p = paragraphs.annotate_paragraphs(m_16_19_doc)
assert str(p[1][0]).startswith('In 2010, the Office')
assert str(p[2][0]).startswith('In December 2014, the')
# The first sentence on page... |
3232781 | import tempfile
from syne_tune.backend import PythonBackend
from syne_tune.backend.trial_status import Status
from syne_tune.config_space import randint
from tst.util_test import wait_until_all_trials_completed
def f(x):
import logging
from syne_tune import Reporter
root = logging.getLogger()
root.se... |
3232822 | import json
from pathlib import Path
from rlbot.matchconfig.loadout_config import LoadoutConfig, LoadoutPaintConfig
from rlbot.matchconfig.match_config import MatchConfig, ExtensionConfig, MutatorConfig, PlayerConfig, ScriptConfig
from rlbot.parsing.agent_config_parser import PARTICIPANT_CONFIGURATION_HEADER, PARTICIP... |
3232838 | import pluggable
class TestPluginPluggableExpected(pluggable.TestPluggable):
def expected_function(self):
raise NotImplementedError()
|
3232895 | import warnings
import numpy as np
from scipy.special import factorial
from .pyramid import SteerablePyramidBase
from .c.wrapper import pointOp
from ..tools.utils import rcosFn
class SteerablePyramidFreq(SteerablePyramidBase):
"""Steerable frequency pyramid.
Construct a steerable pyramid on matrix IM, in the... |
3232926 | import Levenshtein
import sys
stdout = sys.stdout
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdout = stdout
encoding="utf-8"
def cer(r, h):
# Extra space would be errors for this competition
#r = ' '.join(r.split())
#h = ' '.join(h.split())
# I think the extra conditions should be able ... |
3233006 | import enum
from sqlalchemy import Integer, Column, Enum, String, DateTime, Boolean, Float
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Image(Base):
__tablename__ = "image"
# Managed by D... |
3233053 | from pymatsolver.solvers import Base
try:
from pydiso.mkl_solver import MKLPardisoSolver
from pydiso.mkl_solver import set_mkl_pardiso_threads, get_mkl_pardiso_max_threads
class Pardiso(Base):
"""
Pardiso Solver
https://github.com/simpeg/pydiso
documentation::
... |
3233058 | import unittest
import pytest
import torch
from torch import nn
from pfrl.nn import RecurrentBranched, RecurrentSequential
from pfrl.testing import torch_assert_allclose
from pfrl.utils.recurrent import (
concatenate_recurrent_states,
get_recurrent_state_at,
mask_recurrent_state_at,
one_step_forward,
... |
3233059 | import math
from collections import OrderedDict
from flask import escape
from flask.ext.babel import gettext as _
from .node import Node
class Route():
def __init__(self, graph, points, settings, avoided_ctypes=()):
self.graph = graph
self.points = points
self.settings = settings.copy()
... |
3233080 | from wtpy import BaseCtaStrategy
from wtpy import CtaContext
import numpy as np
class StraDualThrust(BaseCtaStrategy):
def __init__(self, name:str, code:str, barCnt:int, period:str, days:int, k1:float, k2:float, isForStk:bool = False):
BaseCtaStrategy.__init__(self, name)
self.__days... |
3233111 | import requests
from dashboard.Image import draw_black, draw_red, get_enhanced_icon, h_red_image, small_font, medium_font
from dashboard.Config import open_weather_map_api_key, lat, lon, units, unit_letter
def print_weather():
weather = get_weather()
icon = get_enhanced_icon(weather['icon_path'], 45, False)
h_red... |
3233119 | from sys import argv
from src.common.config import users
from src.helpers.general import secondOrNone
from src.helpers.mines import fetchOpenLoots
from src.models.User import User
# VARS
userNumber = int(secondOrNone(argv) or 1)
# TEST FUNCTIONS
def test() -> None:
openLoots = fetchOpenLoots(User.find(userNumber)... |
3233122 | from construct import Struct, Int32ul
from .piostring import PioString
Key = Struct(
"id" / Int32ul,
"id2" / Int32ul, # a duplicate of id
"name" / PioString
)
|
3233134 | import os
import torch
import torchvision
import torch.nn as nn
import numpy as np
import math
import sys
import urllib
import pickle
import tarfile
class PurchaseClassifier(nn.Module):
def __init__(self,num_classes=100):
super(PurchaseClassifier, self).__init__()
self.features = nn.Sequential(
... |
3233187 | import theano
import theano.tensor as T
import numpy
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.sandbox.cuda.dnn import dnn_conv
from generic_utils import *
srng = RandomStreams(seed=3732)
T.nnet.relu = lambda x: T.switch(x > floatX(0.), x, floatX(0.00001)*x) #this helps avoid Na... |
3233195 | from django.utils.lru_cache import lru_cache
from manabi.apps.flashcards.models import (
CardHistory,
)
from manabi.apps.flashcards.models.constants import (
DEFAULT_TIME_ZONE,
NEW_CARDS_PER_DAY_LIMIT,
)
class NewCardsLimit:
'''
How many more new cards can the user learn today?
'''
def _... |
3233224 | from db.redis import RedisDB
from tortoise.models import Model
from tortoise.transactions import in_transaction
from tortoise import fields
from util.env import Env
import asyncio
import datetime
import logging
class Stats(Model):
user = fields.ForeignKeyField('db.User', related_name='stats', unique=True, index=T... |
3233262 | import collections
from types import SimpleNamespace
RawResult = collections.namedtuple("RawResult", ["start_logits", "end_logits"])
from model_utils.tokenization import (BasicTokenizer, BertTokenizer, whitespace_tokenize)
import math
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenize... |
3233288 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import sys, glob
sys.path.insert(0, glob.glob('/home/yba/Documents/clarity/fbthrift/thrift/lib/py/build/lib*')[0]) # This needs to be more generic.
from lucidatypes.ttypes import *
from lucidaservice imp... |
3233311 | from flask_restx import reqparse
from flask_restx.reqparse import RequestParser
def create_put_question_parser() -> RequestParser:
"""
We use this parser in the vote endpoint - we want to
ensure, that only a possible type of vote is putted.
"""
parser = reqparse.RequestParser()
parser.add_arg... |
3233327 | from scope_event import ScopeStart, ScopeEnd
_registered_events = [ ScopeStart, ScopeEnd ]
_events = []
__all__ = [
"on",
"dispatch",
"register_event"
]
def on(event_name, *args, **kwargs):
for event in _registered_events:
if event.name == event_name:
_events.append(event(*args, *... |
3233363 | import os
import pyroms
def test_remap_weights(field_choice, interp_file, output_file):
'''
test addresses and weights computed in a setup phase
'''
# write test namelist file
f = open('test_remap_weights_in','w')
f.write('&remap_inputs' + '\n')
f.write(' field_choice = ' + str(field... |
3233376 | import json
import numpy as np
import os
import pandas as pd
from argparse import ArgumentParser
from pathlib import Path
pd.set_option("max.rows", 10)
pd.set_option("max.columns", 20)
pd.set_option("display.width", 200)
def parse_args():
parser = ArgumentParser(allow_abbrev=False)
# Run configuration
p... |
3233388 | import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'app: {} - version: {}'.format(os.environ.get("TSURU_APPNAME"), os.environ.get("TSURU_APPVERSION"))
if __name__ == '__main__':
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8888)))
|
3233392 | import cv2
import numpy as np
import Queue
class Digit(object):
'''
Extracts the digit from a cell.
Implements the classic `Largest connected component` algorithm.
'''
def __init__(self, image):
self.graph = image.copy()
self.W, self.H = self.graph.shape
self.visited = [[F... |
3233497 | from bs4 import BeautifulSoup
import re
import time
import requests
headers0 = {'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"}
def getWishList(doubanid):
firstpage='https://movie.douban.com/people/'+doubanid+'/wish?start=0&sort=time&rating=... |
3233507 | def request(flow):
flow.request.headers["x-requests-proxy"] = "http"
def response(flow):
flow.response.headers[b"x-requests-proxied"] = "http"
|
3233526 | import megengine as mge
import megengine.optimizer as optim
from model.IFNet import IFNet
from model.IFNet_m import IFNet_m
import megengine.distributed as dist
import megengine.autodiff as ad
from model.loss import *
from model.laplacian import *
from model.refine import *
class Model:
def __init__(self, local_r... |
3233540 | import pytest
import pathlib
import re
docs_dir = pathlib.Path(__file__).parent.parent / "docs"
widgets_md = (docs_dir / "widgets.md").read_text()
widget_templates_dir = (
pathlib.Path(__file__).parent.parent
/ "django_sql_dashboard"
/ "templates"
/ "django_sql_dashboard"
/ "widgets"
)
header_re = ... |
3233577 | def output_layer(task, last_activation, y_train, y_val):
import numpy as np
# output layer
if task == 'binary':
activation = last_activation
last_neuron = 1
elif task == 'multi_class':
activation = last_activation
last_neuron = len(np.unique(np.hstack((y_train, y_val))... |
3233590 | import os
import scp
import time
from shakedown.dcos.helpers import *
import shakedown
def copy_file(
host,
file_path,
remote_path='.',
username=None,
key_path=None,
action='put'
):
""" Copy a file via SCP, proxied through the mesos master
:param host: ho... |
3233611 | import numpy as np
import os
import scipy.interpolate as interp
import scipy.optimize as sciopt
import yaml
import importlib
from eval_engines.ngspice.TwoStageComplete import TwoStageMeasManager
class NoGainBoostMeasManager(TwoStageMeasManager):
def _get_specs(self, results_dict):
ugbw_cur = results_dict... |
3233660 | import os, sys, time, itertools, resource, gc, argparse, re, logging
from util import psutil_process, print_datetime
import numpy as np
import torch
from Model import Model
def parse_arguments():
parser = argparse.ArgumentParser()
# dataset
parser.add_argument(
'--path2dataset', type=str,
help='name of the ... |
3233676 | def convert_to_number(value):
try:
value = int(value)
return value
except Exception:
return 0
def main():
print("Find the largest number")
number_string = input("Enter a list of numbers, separated by a space: ")
# Expected input = "4 6 23 99 32 1 0 -4 44 76"
numbers = ... |
3233697 | import numpy as np
import torch
import random
def find_index(y_traj, y_rand):
for idx, label in enumerate(y_rand[0]):
if label == y_traj[0]:
return idx
def sample_balanced_data(cactus_partition):
for idx, cluster in enumerate(list(cactus_partition.values())):
# Sample fixed elemen... |
3233730 | from sp_api.base.helpers import sp_endpoint, fill_query_params
from sp_api.base import Client, ApiResponse
class ProductFees(Client):
"""
:link: https://github.com/amzn/selling-partner-api-docs/tree/main/references/product-fees-api
"""
@sp_endpoint('/products/fees/v0/listings/{}/feesEstimate', method... |
3233732 | from oem_framework.core.helpers import convert_keys_to_string
from oem_framework.models.core.base.mapping import BaseMapping
from oem_framework.models.core.base.model import Model
from oem_framework.models.core.mixins.names import NamesMixin
from bencode import bencode
import collections
import hashlib
import inspect
... |
3233800 | from toolz import curry
@curry
def subtract(x, y):
"""Subtracts its second argument from its first argument"""
return x - y
|
3233808 | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from itertools import chain
from pyspark.sql.functions import create_map, lit
from awsglue.dynamicframe import DynamicFram... |
3233829 | import pytest
import os
import shutil
import tempfile
@pytest.fixture()
def workspace(request):
"""Returns a path to a temporary directory for writing data."""
test_workspace = tempfile.mkdtemp()
def fin():
if os.path.exists(test_workspace):
shutil.rmtree(test_workspace)
request... |
3233876 | import numpy, svg3d, pyrr, math
def get_octahedron_faces():
f = math.sqrt(2.0) / 2.0
verts = numpy.float32(
[(0, -1, 0), (-f, 0, f), (f, 0, f), (f, 0, -f), (-f, 0, -f), (0, 1, 0)]
)
triangles = numpy.int32(
[
(0, 2, 1),
(0, 3, 2),
(0, 4, 3),
... |
3233928 | from moha import *
mol,orbs = IOSystem.from_file('h2o.xyz','sto-3g.nwchem')
ham = RestrictedChemicalHamiltonian.build(mol,orbs)
wfn = HFWaveFunction(10,7,{'alpha':5,'beta':5})
hf_results = DIISSCFSolver(ham,wfn).kernel()
print(hf_results['orbital_energies'])
|
3233944 | import zengl
from PIL import Image
from window import Window
window = Window(1280, 640)
ctx = zengl.context()
image = ctx.image(window.size, 'rgba8unorm-srgb', samples=16)
depth = ctx.image(window.size, 'depth24plus', samples=16)
image.clear_value = (0.0, 0.0, 0.0, 0.0)
ctx.includes['perspective'] = '''
mat4 pe... |
3233952 | import logging
from barry.datasets.dataset_power_spectrum import PowerSpectrum_DESIMockChallenge0_Z01
from barry.models import PowerBeutler2017
from barry.models.model import Correction
import pandas as pd
import numpy as np
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format="[%(levelname)7... |
3233973 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from distutils.extension import Extension
import numpy as np
# Read contents of README markdown ... |
3233996 | import json
import boto3
import cfnresponse
from botocore.exceptions import ClientError
import time
s3 = boto3.resource('s3')
ddb_client = boto3.client('dynamodb')
def create(properties, physical_id):
print("Create Event and Properties: {}".format(json.dumps(properties)))
bucket = properties['Bucket']
... |
3234018 | import warnings
from functools import reduce as _reduce
from .iter import Iter, generator
from .lib_basic import uncons
from .._toolz import accumulate as _accumulate, topk as _topk, reduceby
from ..functions import fn, to_callable
from ..typing import Func, Seq, Pred, TYPE_CHECKING, NOT_GIVEN
if TYPE_CHECKING:
f... |
3234031 | from django.contrib import admin
from django.conf.urls import url
from django.contrib import messages
from . import models
from .forms import UploadQuarterlyFileForm, UploadAnnualFileForm
from django_q.tasks import async_task
@admin.register(models.FinancialYear)
class FinancialYearAdmin(admin.ModelAdmin):
list_... |
3234034 | from django.conf import settings
from django.contrib.auth import logout as auth_logout
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect, render
from .forms import UserImpersonationForm
def logout(request):
auth_logout(request)
return redirect(settings.LOGOUT_REDIRECT_URL)
... |
3234048 | import ntpath
import os
import sys
import xml.etree.ElementTree as ElementTree
import autosar
dvg_xml = """<?xml version="1.0" encoding="utf-8"?>
<DVG>
<Version>1.0</Version>
<Contents>
</Contents>
</DVG>"""
class XMLWriterSimple:
def __init__(self):
self.indentChar='\t'
def mak... |
3234087 | from __future__ import print_function
import sys
import pandas as pd
import types as t
import helper as h
class Database:
def __init__(self, db, conn):
self.db = db
self.connection = conn
def __getitem__(self, item):
for x in self.tables():
if x.name() == item:
... |
3234254 | import datetime
from django.test import TestCase, SimpleTestCase
from corehq.apps.userreports.data_source_providers import DynamicDataSourceProvider, MockDataSourceProvider
from corehq.apps.userreports.tests.utils import (
get_sample_data_source,
)
class DataSourceProviderTest(TestCase):
def test_dynamic_mo... |
3234267 | from ..ir import IR
def printf(visitor, expr):
assert expr.args
tpl = visitor.visit_expression(expr.args[0])
assert isinstance(tpl, IR.LiteralString),\
"printf called with non-constant string"
args = string_format(visitor, tpl.val, expr.args[1:])
visitor.emit(IR.Print(tuple(map(visitor.... |
3234276 | from django.db import models
from paypalrestsdk import payments as paypal_models
from .. import enums
from ..fields import CurrencyAmountField, JSONField
from .base import PaypalObject
class Payment(PaypalObject):
intent = models.CharField(max_length=9, choices=enums.PaymentIntent.choices)
cart = models.CharField(... |
3234305 | import os
from datetime import date
import psycopg2
import psycopg2.extras
from flask import Flask, jsonify, Response
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {"citibike": generate_password_... |
3234351 | import logging
from ...relocation import Relocation
l=logging.getLogger(name=__name__)
# Reference: https://msdn.microsoft.com/en-us/library/ms809762.aspx
class PEReloc(Relocation):
AUTO_HANDLE_NONE = True
def __init__(self, owner, symbol, addr, resolvewith=None): # pylint: disable=unused-argument
... |
3234355 | import os, logging
import operator
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from run_commands import run_command
class RemovedHit(object):
def __init__(self, left_flank, right_flank):
# reason for removal
self.reason = ''
# coordinates of left and ri... |
3234416 | from django.contrib import admin
from .models import Instance
class InstanceAdmin(admin.ModelAdmin):
list_display = ('name', 'ami', 'ip_address', 'start', 'end', 'state')
admin.site.register(Instance, InstanceAdmin)
|
3234426 | from .core import ArxivDatabase
from .elasticsearch import \
ArxivElasticTextSearch,\
ArxivElasticSeachDatabaseClient,\
DateAggregation,\
TermsAggregation,\
KeywordsTextSearch,\
CategoryFilterItem,\
TextSearchFilter,\
SearchResults,\
FIELD_MAPPING,\
DATE_FIELD_NAME
SUPPORTED_DBS... |
3234428 | import collections
import functools
import numpy as np
import operator
IMAGEOutput = collections.namedtuple(
"IMAGEOutput", ("data", "years", "header", "unit", "label")
)
def load_image_data_file(fp):
raw = list(open(fp))
# Remove empty strings at end of file
if not raw[-1]:
raw = raw[:-1]
... |
3234429 | from __future__ import annotations
import re
from slackbot.bot import listen_to
from slackbot.dispatcher import Message
from slacker import Error
# リアクション対象のキーワードと絵文字
REACTION = {
("肉", "meat"): "meat_on_bone",
"カレーメシ": ["curry", "boom"],
("ピザ", "pizza"): "pizza",
("sushi", "寿司", "おすし"): "sushi",
... |
3234430 | import os,sys,shutil
import protac_lib as pl
import rosetta as rs
import utils
import glob
import pymol_utils
sys.path.append(utils.SCRIPTS_FOL)
import cluster as cl
def main(name, argv):
if not len(argv) == 1:
print_usage(name)
return
log = open('log.txt', 'w', bufferi... |
3234452 | import pytest
from typing import List, Tuple
from robot_server.robot.calibration import util
@pytest.fixture
def machine(loop):
states = {
"imaginingTable",
"millingLumber",
"sawingToDimensions",
"assemblingTable" "gluingUp" "rethinkingDesign",
"sandingDown",
"apply... |
3234474 | from pollbot.models import Option, Poll, Vote
import pytest
from sqlalchemy.exc import IntegrityError
from sqlalchemy import exists
class TestVote:
def test_unique_ordering(self, session, user, poll):
option = Option(poll, "option 0")
session.add(option)
vote = Vote(user, option)
v... |
3234481 | import pytest
from eth._utils.padding import (
pad32,
pad32r
)
padding_byte = b"\x00"
@pytest.mark.parametrize(
"value, expected",
(
(b"", padding_byte * 32),
(b"\x01", (padding_byte * 31) + b"\x01")
)
)
def test_pad_32(value, expected):
assert pad32(value) == expected
@pyt... |
3234530 | import setuptools
setuptools.setup(
name='zed',
install_requires=[
'durationpy',
'python-dateutil',
'requests',
],
py_modules=['zed'],
python_requires='>=3.3',
)
|
3234533 | import requests
import argparse
import os
from bs4 import BeautifulSoup
import youtube_dl
from termcolor import colored
from banner import banner
def downloader(courseTitle, dl, qualityCode="18"):
if not os.path.exists(courseTitle):
os.mkdir(courseTitle)
for mod, lecs in dl.items():
mod = cours... |
3234557 | from activityio.pwx._reading import read_and_format as read
from activityio.pwx._reading import gen_records
|
3234574 | from dispatch import *
import logging, sys
logging.basicConfig(level=logging.INFO)
exe = read_executable(sys.argv[1])
exe.analyze()
exe.analyzer.cfg()
print "passed"
|
3234602 | from distutils.core import setup
import py2exe
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
console = [{'script': "InstallAPK.py"}],
zipfile = None,
) |
3234617 | from .chain_collection import Chain, ChainCollection
import numpy as np
from .chain import calculate_charge
from abpytools.utils import DataLoader
from .helper_functions import germline_identity_pd, to_numbering_table
class Fab:
def __init__(self, heavy_chain=None, light_chain=None, load=True, name=None):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.