id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
489653 | import torch
import numpy as np
from torchvision import transforms
from skimage import color
from skimage.io import imsave
from skimage.draw import line, set_color, circle
from model import Model
import time
import warnings
import argparse
import os
from ngdsac import NGDSAC
from loss import Loss
import cv2
pars... |
489665 | import os
import datetime
from dotenv import load_dotenv
load_dotenv()
# class for secrets management
class FlaskConfig:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.environ['SECRET_KEY']
REMEMBER_COOKIE_DURATION = datetime.timedelta(m... |
489678 | import sys
import os
# extend the path with the current file, allows the use of other CMS scripts
sys.path.insert(0, os.path.dirname(__file__))
import cms_scanner
import re
import json
import random
try:
from urlparse import urljoin, urlparse
except ImportError:
from urllib.parse import urljoin, urlparse
cla... |
489705 | import numpy as np
import math
def get_ore(amount_needed, chemical, reactions, spare_parts):
if chemical == "ORE":
return amount_needed
amount_produced = int(reactions[chemical][0])
amount_reactions_needed = math.ceil(amount_needed / amount_produced)
ueberschuss = amount_reactions_needed * am... |
489706 | import os
import json
import base64
import click
import requests
import htmlmin
from html_cluster.settings import (
HTML_CLUSTER_DATA_DIRECTORY, SPLASH_URL, USER_AGENT, SPLASH_TIMEOUT, ALLOW_STATUS_CODE
)
from html_cluster.utils.common import get_file_name
from html_cluster.utils.url import FileUrlsReader
from ht... |
489755 | import gc
import gzip
import operator as op
from functools import reduce
from pathlib import Path
import torch
from rtg import log
import inspect
import shutil
import os
from datetime import datetime
import atexit
from typing import Tuple
import resource
import sys
import numpy as np
import subprocess
from itertools im... |
489792 | from .organisation import EXTERNAL_LINKS, Organisation
from .organisation_link import OrganisationLink
from .organisation_location import OrganisationLocation
from .organisation_type import OrganisationType
from .orgid import Orgid, OrgidField
from .orgid_scheme import OrgidScheme
from .related_organisation import Rela... |
489825 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from rlpy.Representations import iFDD
from rlpy.... |
489876 | from inqry import barcode
def test_barcode_data_delayify():
assert barcode.delayify('foo') == '~dfoo'
def test_barcode_data_delayify_long():
assert barcode.delayify('foo', 2) == '~d~dfoo'
def test_barcode_data_textify():
assert barcode.textify('foo') == '~dfoo~d~t'
def test_barcode_data_listify():
... |
489948 | import os
import re
from urllib.parse import urlparse, unquote
from crawler.utils import special_chars, html_pattern
def trans_query_for_local_link(local_link, query_str):
'''
将url中query部分中的特殊字符替换掉, 防止在写入本地文件时文件名非法.
'''
for k, v in special_chars.items():
if k in query_str: query_str = query_st... |
489963 | vehicles = [
{
"Year": 2020,
"Make": "Audi",
"Model": "Q3",
"Category": "SUV"
},
{
"Year": 2020,
"Make": "Chevrolet",
"Model": "Malibu",
"Category": "Sedan"
},
{
"Year": 2020,
"Make": "Cadillac",
"Model": "Escalade ESV",
"Category": "SUV"
},
{
"Year": 20... |
489989 | import inspect
from abc import ABC, abstractmethod
from datetime import datetime
from time import sleep
import cfscrape
import requests
import blockapi
cfscrape.DEFAULT_CIPHERS += ':!SHA'
class Service(ABC):
"""General class for handling blockchain API services."""
active = True
base_url = None
r... |
490013 | server1 = 4
server2 = 4
server3 = 4
server4 = 4
server5 = 4
mode1 = 3
mode2 = 3
mode3 = 3
mode4 = 3
mode5 = 3
waittime = 240 |
490025 | from flask import Flask
from flask_restx import Api
from .utils import Config
app = Flask(__name__)
app.config.from_object(Config)
api = Api(
app,
version="1.0",
title="Leonidas",
description="An API for executing attacker actions within AWS",
)
|
490053 | from collections import OrderedDict as odict
def importCONFHD(fobj):
CONFHD = odict()
for i, v in enumerate(fobj):
vline = v.decode('utf-8')
if vline.strip() and vline[0:5].strip() != 'NUM' and 'XXXX' not in vline:
coduhe = vline[:5].strip()
nome = vline[5:20].strip()
... |
490087 | from anime_downloader.downloader.http_downloader import HTTPDownloader
from anime_downloader.downloader.external_downloader import ExternalDownloader
from anime_downloader.downloader.SmartDL import pySmartDL
def get_downloader(downloader):
"""get_downloader returns the proper downloader class
TODO: Lazy load... |
490099 | import logging
from pomp.core.base import BaseCrawler, BaseMiddleware
from pomp.core.engine import Pomp
from pomp.contrib.urllibtools import UrllibDownloader
from pomp.contrib.urllibtools import UrllibAdapterMiddleware
from mockserver import HttpServer, make_sitemap
from tools import DummyCrawler
from tools import Req... |
490134 | from setuptools import find_packages, setup
setup(
name='btcturk_client',
version='0.0.2',
packages=find_packages(),
url='https://github.com/emre/btcturk-client',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Btcturk.com api client',
install_requires=['request... |
490137 | import re
from city_scrapers_core.constants import ADVISORY_COMMITTEE, COMMITTEE
from city_scrapers_core.spiders import CityScrapersSpider
from city_scrapers.mixins import CuyaCountyMixin
class CuyaEmergencyServicesAdvisorySpider(CuyaCountyMixin, CityScrapersSpider):
name = "cuya_emergency_services_advisory"
... |
490181 | import string
import httplib, sys
import myparser
import re
import time
class search_google:
def __init__(self,word,limit,start,filetype):
self.word=word
self.results=""
self.totalresults=""
self.filetype=filetype
self.server="www.google.com"
self.hostname="www.google.com"
self.userAgent="(Mozilla/5.0 (... |
490230 | def instance_name_check(test, resource, key, value):
if test == "ISBAD":
if resource[key].startswith(value):
return True
else:
return False
else:
return False
|
490246 | import sys
import os
import re
import pprint
searchkey = sys.argv[1]
querygroups = sys.argv[2].split('&')
for group in querygroups:
tokens=group.split("=")
if(len(tokens) == 2 and tokens[0] == searchkey):
print(tokens[1])
|
490251 | GOOGLEAPIS_BUILD_FILE = """
filegroup(
name = "annotations_protos",
srcs = [
"google/api/annotations.proto",
"google/api/http.proto",
],
visibility = ["//visibility:public"]
)
"""
DEPS = {
"com_github_grpc_ecosystem_grpc_gateway": {
"rule": "go_repository",
"importpath": "github.co... |
490252 | from collections import ChainMap
class AsyncTransactionDict(dict):
async def __aenter__(self):
self.writes = dict()
return ChainMap(self.writes, self)
async def __aexit__(self, exc_type, exc_val, tb):
if exc_type is None:
self.update(self.writes)
self.writes = None
|
490255 | from IPython.core.display import display
from ipywidgets import Output, widgets
from pandas_profiling.report.presentation.core.sample import Sample
class WidgetSample(Sample):
def render(self) -> widgets.VBox:
out = Output()
with out:
display(self.content["sample"])
name = wi... |
490271 | list = [('abc.es','HTTP/1.1 200',0,0,0,0,0),
('abcnews.go.com','HTTP/1.1 200',2,0,0,0,'/'),
('about.me','HTTP/1.1 200',5,1,1,'Lax','/'),
('abril.com.br','HTTP/1.1 301',1,1,1,0,'/'),
('alibaba.com','HTTP/1.1 200',1,0,0,0,'/'),
('ap.org','HTTP/1.1 200',0,0,0,0,0),
('biblegateway.com','HTTP/1.1 200',0,0,0,0,0),
('b... |
490315 | from anime_downloader.sites import helpers
from anime_downloader.sites.anime import Anime, AnimeEpisode, SearchResult
import logging
logger = logging.getLogger(__name__)
class KissAnimeX(Anime, sitename='kissanimex'):
sitename = "kissanimex"
@classmethod
def search(cls, query):
url = 'https://ki... |
490326 | class PushException(Exception):
pass
class PushAuthException(PushException):
pass
class PushInvalidTokenException(PushException):
pass
class PushInvalidDataException(PushException):
pass
class PushServerException(PushException):
pass
|
490388 | from itertools import chain
import fbuild.builders
import fbuild.db
import fbuild.path
# ------------------------------------------------------------------------------
class SDLConfig(fbuild.db.PersistentObject):
def __init__(self, ctx, exe=None, *,
requires_version=None,
requires_at_leas... |
490443 | import pytest
from jsonpath_ng.ext.filter import Filter, Expression
from jsonpath_ng.ext import parse
from jsonpath_ng.jsonpath import *
@pytest.mark.parametrize('string, parsed', [
# The authors of all books in the store
("$.store.book[*].author",
Child(Child(Child(Child(Root(), Fields('store')), Field... |
490475 | from machine import UART
import utime
from machine import Pin
class M5310_A():
def send_cmd(self,cmd):
self.uart.write(cmd + '\r\n')
def cheak_ack(self,buf, ack):
if ack in buf:
return True
else:
return False
def __init__(self):
self.rst = Pin(18, Pin... |
490551 | import warnings
from django.contrib.auth import authenticate
from . import TestCase
from .factories import UserFactory
class BackendTest(TestCase):
def test_case_insensitive_username(self):
user = UserFactory.create(username='TeSt')
with warnings.catch_warnings(record=True) as w:
se... |
490552 | from tests.integration import int_test
example = """
from typing import Generator
x: Generator[str, str, None, None]
"""
expected = """
from collections.abc import Generator
x: Generator[str, str, None, None]
"""
def test_generator():
int_test(example, expected, futures=True)
|
490583 | import base64
import json
import os
import pathlib
import shutil
from unittest import mock
import pytest # noqa: F401
from simple_salesforce.exceptions import SalesforceMalformedRequest
from cumulusci.core.exceptions import CumulusCIException # noqa: F401
from cumulusci.tasks.salesforce.tests.util import create_tas... |
490607 | from flask import Flask, jsonify, request, url_for
from flask_admin import Admin
#from flask_admin.contrib.peewee import ModelView
from flask_admin import helpers as admin_helpers
from flask_admin.menu import MenuLink
from flask_security import Security, PeeweeUserDatastore, \
UserMixin, RoleMixin, login_required, ... |
490609 | from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, SubmitField, BooleanField, PasswordField, RadioField, TextAreaField
from wtforms.validators import Length, EqualTo, Email, DataRequired, ValidationError, Regexp
from flask_login import current_user
fr... |
490611 | import unittest
from bibliopixel.layout.geometry import matrix
class MatrixTest(unittest.TestCase):
def test_simple(self):
m = matrix.Matrix(list(range(12)), 3)
self.assertEqual(m.get(0, 0), 0)
self.assertEqual(m.get(1, 0), 1)
self.assertEqual(m.get(0, 1), 3)
self.assertEqu... |
490620 | from braintree.exceptions.braintree_error import BraintreeError
class TooManyRequestsError(BraintreeError):
"""
Raised when the rate limit request threshold is exceeded.
"""
pass
|
490634 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor,ExtraTreesRegressor
from sklearn.model_selection import ShuffleSplit,cross_val_score
from sklearn.linear_model import Lasso,Ridge
from opc_python import * # Import constants.
from opc_python.utils import prog,scoring,loading
d... |
490637 | from Tkinter import Toplevel, StringVar, Message, Tk, Button, N, S, E, W
from time import time, localtime, strftime
class ToolTip(Toplevel):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__(s... |
490658 | from __future__ import absolute_import
from . import ClientProc
class QueuesProc(ClientProc):
"""
A proc class for the `queues <http://queues.googlecode.com/>`_
library.
:param name: the name of the proc (required)
:param queues: list of queue names to check (required)
:type name: str
:t... |
490663 | from cupy.cuda.memory_hooks import debug_print # NOQA
from cupy.cuda.memory_hooks import line_profile # NOQA
# import class and function
from cupy.cuda.memory_hooks.debug_print import DebugPrintHook # NOQA
from cupy.cuda.memory_hooks.line_profile import LineProfileHook # NOQA
|
490668 | from typing import Optional
from yangify.translator import Translator, TranslatorData, unneeded
class VlanConfig(Translator):
class Yangify(TranslatorData):
path = "openconfig-network-instance:network-instances/network-instance/vlans/vlan/config"
vlan_id = unneeded
def name(self, value: Optiona... |
490713 | from qira_log import *
def do_function_analysis(dat):
next_instruction = None
fxn_stack = []
cancel_stack = []
cl_stack = []
fxn = []
for (address, data, clnum, flags) in dat:
if not flags & IS_START:
continue
if address in cancel_stack:
# reran this address, this isn't return
... |
490720 | from environmentbase.template import Template
from troposphere import Ref, Output, GetAtt, ec2
SSH_PORT = '22'
class Bastion(Template):
"""
Adds a bastion host within a given deployment based on environemntbase.
"""
def __init__(self, name='bastion', ingress_port='2222', access_cidr='0.0.0.0/0', ins... |
490744 | import subprocess
p = subprocess.Popen("cd ~/BEAR/scripts/",
shell=True, stdout=subprocess.PIPE)
p.wait()
data_dir = '/home/nasheran/rozovr/recycle_paper_data/'
for size in [400,1600]:#[100,200,400,800,1600]:
for mult in [2,4]:
# if size!=100: break
num_reads = 1250000 * (size/100)
pref = data_dir+'plasmids_s... |
490752 | import featuretools as ft
from . import dfd, normalize
from .classes import Dependencies
def find_dependencies(df, accuracy=0.98, index=None):
"""
Finds dependencies within dataframe df with the DFD search algorithm.
Returns the dependencies as a Dependencies object.
Arugments:
df (pd.Dataf... |
490757 | from datetime import date, datetime
from django import template
from django.template import defaultfilters
from django.utils.timezone import is_aware, utc
from django.utils.translation import pgettext, ugettext as _, ungettext
register = template.Library()
@register.filter
def naturaltime(value):
"""
For date... |
490758 | import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
import pyaf.Bench.TS_datasets as tsds
#get_ipython().magic('matplotlib inline')
def pickleModel(iModel):
import pickle
output = pickle.dumps(iModel)
lReloadedObject = pickle.loads(output)
output2 = pickle.dumps(lReloadedObject... |
490765 | from .annotation_project import AnnotationProject
from .band import Band
from .thumbnail import Thumbnail
from .footprint import Footprint
from .image import Image
from .scene import Scene
from .upload import Upload
|
490800 | import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
js_to_json,
)
class OnDemandKoreaIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ondemandkorea\.com/(?P<id>[^/]+)\.html'
_GEO_COUNTRIES = ['US', 'CA']
_TESTS = [{
'url': 'https://www.ondemandkorea.com/a... |
490803 | import pprint
from subprocess import call
import sys
def pp(o):
p = pprint.PrettyPrinter(indent=4)
p.pprint(o)
def run_spark_job(command_data, job_info, client_name):
conf_data = command_data["conf_data"]
spark_home = conf_data["spark_home"]
seldon_spark_home = conf_data["seldon_spark_home"]
s... |
490812 | from osgeo import ogr
from osgeo import osr
source = osr.SpatialReference()
source.ImportFromEPSG(4326)
target = osr.SpatialReference()
target.ImportFromEPSG(3857)
transform = osr.CoordinateTransformation(source, target)
geojson = """{ "type": "LineString", "coordinates": [ [ -75.313585, 43.069271 ], [ -75.269426, ... |
490815 | from moai.visualization.visdom.base import Base
from moai.monads.execution.cascade import _create_accessor
import torch
import typing
import logging
import numpy as np
import visdom
import functools
log = logging.getLogger(__name__)
__all__ = ["Vector"]
class Vector(Base):
def __init__(self,
vector: ... |
490816 | import os
import errno
import argparse
import numpy as np
import tensorflow as tf
# Data loader/manager
from data_manager import DataManager
# Models
from logistic_regression import LogisticRegression
from feed_forward_neural_network import FeedForwardNN
from lstm_network import LSTMNN
def parse_arguments():
""... |
490854 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
from collections import OrderedDict
if k == 0 or not nums:
return False
d = OrderedDict()
cnt, nums_ = k, nums[:]
while cnt and nums_:
tmp = nums_.pop()
if ... |
490868 | import os, sys
dirname = os.path.dirname(__file__)
lib_path = os.path.join(dirname, "python_speech_features")
sys.path.append(lib_path)
import features as speechfeatures
import numpy as np
def filter(samplerate, signal, winlen=0.02, winstep=0.01,
nfilt=40, nfft=512, lowfreq=100, highfreq=5000, preemph=0.9... |
490900 | from stix_shifter_modules.aws_athena.entry_point import EntryPoint
from unittest.mock import patch
import json
import unittest
from stix_shifter.stix_transmission import stix_transmission
from botocore.exceptions import ClientError
from botocore.exceptions import ParamValidationError
import datetime
from dateutil.tz im... |
490924 | from nose.tools import assert_equals, assert_almost_equals, assert_raises, assert_true
from ...similarities.basic_similarities import UserSimilarity
from ...metrics.pairwise import euclidean_distances, jaccard_coefficient
from ...models.classes import MatrixPreferenceDataModel, \
MatrixBooleanPrefDataModel
from ... |
490934 | import math
import numpy as np
from Constants import SubDir
from system_functions import make_directory
import matplotlib.pyplot as plt
def generate_pub_figures(sys, sim):
"""Generate summary figure for Cylindrical Roller Bearing Tribosystems"""
plot_axis_pol = np.linspace(-math.pi, math.pi - 2 * math.pi / ... |
490942 | import os
import numpy as np
import matplotlib.pyplot as plt
import logging
from pandas import DataFrame
from app_globals import *
from alad_support import *
from r_support import matrix, cbind
from alad_iforest import *
from data_plotter import *
from results_support import *
def get_queried_indexes(scores, label... |
491020 | import unittest
from unittest import mock
from docker.errors import ContainerError
from custom_image_cli.helper import logging
from custom_image_cli.validation_tool.validation_tests.check_local_job_run import CheckLocalJobRun
class TestCheckLocalSparkJob(unittest.TestCase):
def setUp(self) -> None:
self... |
491030 | from ..gif_gui import GifGui
import numpy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib
from typing import List, Optional
matplotlib.rc("animation", html="html5")
from ..gui_base import GuiBase
class MatplotlibGifGui(GifGui):
class Settings(GifGui.Settings):
... |
491035 | import math
def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=None, barnes_hut_theta=1.2):
"""
Iterate through the nodes or edges and apply the forces directly to the node objects.
"""
if not barnes_hut_optimize:
for i in range(0, len(nodes)):
for j in range(0... |
491110 | import pytest
from rgd.datastore import datastore
from rgd_3d import models
from rgd_3d.tasks.etl import read_point_cloud_file
from . import factories
@pytest.mark.parametrize(
'sample_file',
[
'topo.vtk',
],
)
@pytest.mark.django_db(transaction=True)
def test_point_cloud_etl(sample_file):
pc... |
491132 | from lib import transformationsLib
from lib._version import __version__
def test_init():
assert transformationsLib.__version__ == __version__
assert hasattr(transformationsLib, 'center_mean')
assert hasattr(transformationsLib, 'center_median')
assert hasattr(transformationsLib, 'centroid')
assert ... |
491150 | import logging
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional
from eth_utils import to_checksum_address
from rotkehlchen.accounting.structures.balance import Balance
from rotkehlchen.assets.asset import EthereumToken
from rotkehlchen.chain.ethereum.graph import Graph, format_query_indentation
fr... |
491151 | import os
from ptsr.data import common
from ptsr.data import srdata
import numpy as np
import torch
import torch.utils.data as data
import glob
class Benchmark(srdata.SRData):
def __init__(self, cfg, name='', train=True, benchmark=True):
super(Benchmark, self).__init__(
cfg, name=name, trai... |
491167 | import tensorflow as tf
import numpy as np
from ares.attack.base import BatchAttack
from ares.attack.utils import get_xs_ph, get_ys_ph
class DeepFool(BatchAttack):
''' DeepFool. A white-box iterative optimization method. It needs to calculate the Jacobian of the logits with
relate to input, so that it only a... |
491174 | import unittest
import zserio
from testutils import getZserioApi
class StructLongTemplateArgumentTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "templates.zs").struct_long_template_argument
def testReadWrite(self):
templ = self.api.TemplatedStr... |
491195 | from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from queue import Queue
from typing import Any, Dict, List, Tuple, Callable, Union
import numpy as np
import torch
import torch.distributed as dist
from torch.utils.data.dataset import IterableDataset
from transformers import BertToken... |
491217 | class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
i, len1 = 2, len(s)
if len1 == 1: return False
if s == s[0] * len1: return True
while i * i < len1:
if len1 % i == 0:
flag = 1
... |
491219 | import json
import os
import time
import sys
import requests
from roboflow.core.workspace import Workspace
from roboflow.core.project import Project
from roboflow.config import *
def check_key(api_key, model, notebook):
if type(api_key) is not str:
raise RuntimeError(
"API Key is of Incorrect... |
491221 | from datetime import datetime
from decimal import Decimal
from unittest import TestCase
from hummingbot.connector.exchange.ftx.ftx_in_flight_order import FtxInFlightOrder
from hummingbot.core.data_type.common import OrderType, TradeType
class FtxInFlightOrderTests(TestCase):
def setUp(self):
super().set... |
491256 | import math
import numpy as np
import dgl
import dgl.function as fn
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
from typing import Callable
class GCNLayer(nn.Module):
def __init__(self, g:dgl.DGLGraph, in_f... |
491268 | import argparse
import sys
from copy import copy
from os import makedirs
from os.path import basename, dirname, exists
from os.path import join as joinp
from typing import List, Sequence
import jinja2
from jinja2 import Environment, FileSystemLoader
from ros_translator.library import Message, PostProcessors, RosLibrar... |
491274 | import math
NUM_VERTS_X = 30
NUM_VERTS_Y = 30
totalVerts = NUM_VERTS_X * NUM_VERTS_Y
totalTriangles = 2 * (NUM_VERTS_X - 1) * (NUM_VERTS_Y - 1)
offset = -50.0
TRIANGLE_SIZE = 1.
waveheight = 0.1
gGroundVertices = [None] * totalVerts * 3
gGroundIndices = [None] * totalTriangles * 3
i = 0
for i in range(NUM_VERTS_X):
... |
491293 | import os
import sys
from os.path import dirname, abspath
path = dirname(dirname(abspath(__file__)))
sys.path.append(path)
os.chdir(path)
|
491315 | import os
import subprocess as sp
from dotmap import DotMap
from typing import Union, Tuple
from .startup_script_gcp import (
tmux_setup,
clone_gcp_bucket_dir,
install_venv,
install_additional_setup,
jax_gpu_build,
jax_tpu_build,
exec_python,
exec_bash,
sync_results_from_dir,
)
cor... |
491364 | import ROOT
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gInterpreter.LoadFile('BTagCalibrationStandalone.cpp')
from functools import partial
import numpy
from coffea.btag_tools import BTagScaleFactor
def stdvec(l):
out = ROOT.std.vector('string')()
for item in l:
out.... |
491373 | import py
import os
import glob
import tokenize
import token
import StringIO
from pypy.interpreter.pyparser.metaparser import ParserGenerator, PgenError
from pypy.interpreter.pyparser.pygram import PythonGrammar
from pypy.interpreter.pyparser import parser
class MyGrammar(parser.Grammar):
TOKENS = token.__dict__
... |
491389 | from django.contrib.auth import get_user_model
from django.test import TestCase
from apis.betterself.v1.users.serializers import UserDetailsSerializer
from betterself.users.models import UserPhoneNumberDetails
User = get_user_model()
class TestUserSerializer(TestCase):
@classmethod
def setUpClass(cls):
... |
491403 | import sublime
try:
str_cls = unicode
except (NameError):
str_cls = str
def preferences_filename():
"""
:return: The appropriate settings filename based on the version of Sublime Text
"""
if int(sublime.version()) >= 2174:
return 'Preferences.sublime-settings'
return 'Global.subl... |
491438 | import attr
import numpy as np
from multiprocessing import Pool
import cloudpickle
import tectosaur.util.gpu as gpu
from tectosaur.mesh.modify import concat
from tectosaur.ops.dense_integral_op import FarfieldTriMatrix
from tectosaur.util.timer import Timer
@attr.s
class Ball:
center = attr.ib()
R = attr.ib()... |
491464 | from flask_restful import Resource
from lyrebird.mock import context
from flask import request, jsonify, abort
from lyrebird import application
class Event(Resource):
def get(self):
return context.make_ok_response(
noticeList=application.notice.notice_list,
notRemindList=applicati... |
491470 | from skimage.transform import AffineTransform
from skimage import transform as tf
import re
CODE = 'trans'
REGEX = re.compile(r"^" + CODE + "_(?P<x_trans>[-0-9]+)_(?P<y_trans>[-0-9]+)")
class Translate:
def __init__(self, x_trans, y_trans):
self.code = CODE + str(x_trans) + '_' + str(y_trans)
self... |
491477 | import argparse
parser = argparse.ArgumentParser(description="Train_Test")
### Training Settings
# General Parameters
parser.add_argument('--lr', type=float, default=0.0001)
parser.add_argument('--weight_decay', type=float, default=0.0001)
parser.add_argument('--grad_clip_norm', type=float, default=0.1)
parser.add_ar... |
491485 | from random import choice, sample
import pytest
import six
from sqlalchemy import create_engine, inspect
from mysql_to_sqlite3 import MySQLtoSQLite
from mysql_to_sqlite3.cli import cli as mysql2sqlite
@pytest.mark.cli
@pytest.mark.usefixtures("mysql_instance")
class TestMySQLtoSQLite:
def test_no_arguments(self... |
491497 | from ..abstract import Processor
class Render(Processor):
"""Render images and labels.
# Arguments
renderer: Object that renders images and labels using a method
''render_sample()''.
"""
def __init__(self, renderer):
super(Render, self).__init__()
self.renderer = r... |
491517 | from . import mobilenet_v1, mobilenet_v2, mobilenet_v3_large, mobilenet_v3_small, \
efficientnet, resnext, inception_v4, inception_resnet_v1, inception_resnet_v2, \
se_resnet, squeezenet, densenet, shufflenet_v2, resnet, se_resnext
from .RegNet import regnet
model_list = [
mobilenet_v1.MobileNetV1(), mobil... |
491521 | from __future__ import absolute_import, division, print_function
import logging
logger = logging.getLogger('pytest_catchlog.test.perf')
def test_log_emit(benchmark):
benchmark(logger.info, 'Testing %s performance: %s',
'catchlog', 'emit a single log record')
|
491533 | import argparse
import os, sys
import json
from copy import deepcopy
import numpy as np
from scipy.spatial import cKDTree
from tqdm import tqdm
from ..utils.scannet_utils import get_global_part_labels_description, load_pickle, get_scannet
from ..utils.vox import load_sample
from ..utils.transforms import apply_transf... |
491549 | from PyQt5.QtCore import pyqtSlot
from PyQt5.Qt import QFileDialog
class FileDialog(QFileDialog):
def __init__(self, parent, caption = '', directory = ''):
super(FileDialog, self).__init__(parent, caption, directory)
# 设置对话框标题
@pyqtSlot(str)
def setCaption(self, caption):
self.setWindowTitle(caption)
# 设置对... |
491551 | def func2():
pass
def func1(n):
num = 0
while num < n:
yield func2
num += 1
for i in func1(100):
i()
|
491565 | import os,sys
#add library to the system path
lib_path = os.path.abspath(os.path.join('lib'))
sys.path.append(lib_path)
from fast_rcnn.config import cfg
from utils.transform import calib_to_P,computeCorners3D,projectToImage,lidar_to_camera
from utils.util_voxels import lidar_in_cam_to_voxel
import matplotlib.pyp... |
491571 | import logging
import os
from avi.migrationtools.scp_util import SCPUtil
LOG = logging.getLogger(__name__)
def get_files_from_f5(local_path, host, username, pw=None, key=None, port=22):
"""
:param local_path: relative path to file
:param host: hostname of instance
:param username: username for ins... |
491595 | import unittest
from stats_counters.stanzas.action import Action
class TestData(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testEmptyInput(self):
'explicit call with no args is invalid'
self.assertRaises(ValueError, lambda: Action())
def ... |
491638 | from selectors import *
f = open(0, "rb")
p = DefaultSelector()
print("DefaultSelector():", p)
print("register:", p.register(f, EVENT_READ, "userdata"))
for r in p.select():
print(r)
|
491674 | import json
import itertools
import os
import sys
import shutil
from enum import Enum
from pprint import pprint
from lark.tree import Tree
from core.afflic import AFFLICT_LIST
from core.acl import regenerate_acl
from conf import SKIP_VARIANT, get_conf_json_path, ELE_AFFLICT, list_advs, load_json, mono_elecoabs, wyrmp... |
491720 | import math
import torch.nn as nn
from mmcv.cnn import ConvModule,build_norm_layer
from mmcv.runner import BaseModule, auto_fp16
from mmcv.cnn import kaiming_init
from mmdet.models.builder import NECKS
from mmcv.ops import DeformConv2dPack
@NECKS.register_module()
class ShortcutNeck(BaseModule):
"""The neck used... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.