id
stringlengths
3
8
content
stringlengths
100
981k
9951429
from time import sleep from twisted.trial.unittest import TestCase from mdstudio.collection.cache_dict import CacheDict from mdstudio.util.exception import MDStudioException class TestCacheDict(TestCase): def setUp(self): self.d = CacheDict(1) def test_construct(self): self.assertEqual(self....
9951430
import polymath as pm from tests.util import linear, op_counts, logistic, svm, reco, dense, conv,\ two_layer_dense, lenet, tvm_lenet from pathlib import Path # import tvm import pytest import pprint import numpy as np import copy import pickle from onnx import numpy_helper, helper, defs # TODO: Fix this def test...
9951434
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class StatusReport(ModuleData): implements(IPlugin, IModuleData) name = "ChannelStatusReport" core = True def actions(self): return [ ("channelstatuses", 1, self.statuses) ] ...
9951442
from typing import List, Union finalize_disjunction = lambda x: "(" + x[:-4] + ") AND " finalize_conjunction = lambda x: x[:-5] def get_query_from_keywords(keywords: List[Union[str, List[str]]]) -> str: """Receives a list of keywords and returns the query for the arxiv API. Args: keywords (List[str,...
9951451
from config import config, device from preproc import preproc from absl import app import math import os import numpy as np import json import re from collections import Counter import string from tqdm import tqdm import random import torch import torch.nn.functional as F import torch.optim as optim import torch.cuda f...
9951458
import unittest from deeprank_gnn.GraphGenMP import GraphHDF5 class TestCreateGraph(unittest.TestCase): def setUp(self): self.pdb_path = './tests/data/pdb/1ATN/' self.pssm_path = './tests/data/pssm/1ATN/' self.ref = './tests/data/ref/1ATN/' def test_create_serial_with_bio(self): ...
9951460
import os import sys import subprocess import shlex import shutil import sys import time import datetime import pytest HERE = os.path.abspath(os.path.dirname(__file__)) skip_on_osx = pytest.mark.skipif( 'sys.platform == "darwin"', reason="not working on osx") skip_on_linux = pytest.mark.skipif( 'sys.platform ...
9951551
import builtins import inspect from .scope import Scope, LoopScope, FuncScope from .errors import NameError, StackCall, AttributeError, OperatorError, RuntimeError, make_stack from ..parser import ast from .stdlib.builtin_types.Integer import Integer, Float from .stdlib.builtin_types.String import String from .stdlib.b...
9951557
from datetime import date, datetime from django import template from django.templatetags.static import static from django.urls import reverse from django.utils import timezone from django.utils.formats import time_format from django.utils.timesince import timeuntil from django.utils.translation import gettext_lazy as ...
9951634
from abc import abstractmethod from .base import Recognizer class FlashtextRecognizer(Recognizer): """The base class for all FlashText based recognizers.""" BACKEND = "flashtext" @property @abstractmethod def keywords(self): """The list of keywords that the FlashText backend is searchin...
9951639
import unittest from openmdao.main.api import Component, Assembly, set_as_top from openmdao.main.datatypes.api import Float, Slot class OneBase(Component): x = Float(iotype='out') class C(Component): x = Float(iotype='in') y = Float(iotype='out') def execute(self): self.y = 2*self.x cla...
9951641
import networkx as nx import pandas as pd from dowhy.gcm.cms import InvertibleStructuralCausalModel from dowhy.gcm.graph import get_ordered_predecessors, is_root_node, validate_causal_dag from dowhy.gcm.util.general import convert_numpy_array_to_pandas_column def compute_noise_from_data(causal_model: InvertibleStruc...
9951643
from flybywire.dom import h def test_dom(): count = 0 node1 = h('div', str(count), style = { 'textAlign': 'center', 'lineHeight': str(100 + count) + 'px', 'border': '1px solid red', 'width': str(100 + count) + 'px', 'height': str(100 + count) +...
9951647
from dataclasses import dataclass from typing_extensions import Final # Constants ID: Final = "id" NAME: Final = "name" URL_BACKGROUND: Final = "urlbackground" CODE: Final = "code" TYPE: Final = "type" HAS_MEDALS: Final = "hasmedals" LEVEL: Final = "level" NAME_LEVEL: Final = "namelevel" PROGRESSION: Final = "progres...
9951670
from pycoin.networks.ParseAPI import ParseAPI from pycoin.networks.parseable_str import parseable_str, parse_b58 from .hash import groestlHash def b58_groestl(s): data = parse_b58(s) if data: data, the_hash = data[:-4], data[-4:] if groestlHash(data)[:4] == the_hash: return data ...
9951705
from .abstract_handler import AbstractHandler from .aws_alb import AwsAlb from .aws_api_gateway import AwsApiGateway from .aws_cf_lambda_at_edge import AwsCfLambdaAtEdge from .aws_http_gateway import AwsHttpGateway from .aws_ws_gateway import AwsWsGateway __all__ = [ "AbstractHandler", "AwsAlb", "AwsApiGat...
9951708
import numpy as np from sklearn.neighbors import KNeighborsClassifier import torch import random def calc_frac_idx(x1_mat,x2_mat): """ Returns fraction closer than true match for each sample (as an array) """ fracs = [] x = [] nsamp = x1_mat.shape[0] rank=0 for row_idx in range(nsamp): ...
9951730
from ecpy.utils import is_prime, modinv from .FiniteField import FiniteField from .Field import Field, FieldElement from .Zmod import Zmod, ZmodElement class ExtendedFiniteField(FiniteField): def __init__(s, p, poly="x^2+1"): Field.__init__(s, ExtendedFiniteFieldElement) s.p = s.n = p if poly == "x^2+1":...
9951777
from checks import NaptanCheck from report import reporting as rep # %% class StopRoadDistance(NaptanCheck): """[summary] StopPoint geocode is more than 100 metres from a road. Args: NaptanCheck ([type]): [description] """ check_name = 'stop road distance.' check_geographic_level = 'sto...
9951803
import pytest from typing import Iterator from tornado.httpclient import HTTPClient, HTTPRequest from tornado.simple_httpclient import HTTPTimeoutError from altair_viewer._event_provider import EventProvider @pytest.fixture def http_client() -> HTTPClient: return HTTPClient() @pytest.fixture(scope="module") d...
9951819
import torch.utils.data as data import torch import h5py, cv2 import numpy as np import random import torchvision from PIL import Image import os import kornia class DatasetFromHdf5(data.Dataset): def __init__(self, file_path, patch_size, aug=False): super(DatasetFromHdf5, self).__init__() self.pa...
9951823
from attrdict import AttrDict from annotator_store.models import BaseAnnotation, AnnotationQuerySet from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.urls import reverse from djiffy.models import Canvas from derrida.books.models import Language from derrida.common.models im...
9951848
import numpy as np import scipy.io as sio import scipy.sparse mat = sio.loadmat('wiki.mat')['H'] I, J, _ = scipy.sparse.find(mat) with open('wiki_topcat.txt', 'w') as f: for i, j in zip(I, J): f.write('%d %d\n' % (i, j))
9951867
from __future__ import print_function from keras.datasets import imdb from keras.preprocessing import sequence from attention import Position_Embedding, Attention max_features = 20000 maxlen = 80 batch_size = 32 print('Loading data...') (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features) p...
9951881
import torch import pn2_ext ''' try: from . import pn2_ext print("Import PointNet2 extension successfully") except ImportError: print('Please compile source files before using pointnet2 cuda extension.') ''' def gather_points(points, index): """Gather xyz of centroids according to indices Args: ...
9951905
import os from aws_cdk import ( aws_cloudformation as cfn, aws_lambda as lambda_, core, aws_logs as logs, ) class CustomResource(core.Construct): def __init__( self, scope: core.Construct, id: str, Description: str, Uuid: str, **kwargs ) -> None: super().__init__(scope, id) ...
9951927
import torch.nn as nn class Lambda(nn.Module): """Wrap a function as `nn.Module`.""" def __init__(self, fn): super(Lambda, self).__init__() self.lambda_func = fn def forward(self, *args): return self.lambda_func(*args)
9951952
import numpy as np from PuzzleLib.CPU.CPUArray import CPUArray from PuzzleLib.Intel.ThirdParty import libdnnl def mulMatrixOnMatrix(A, B, out=None, transpA=False, transpB=False, alpha=1.0, beta=0.0): assert not (transpA and transpB) assert A.ndim == 2 and B.ndim == 2 assert A.dtype == B.dtype and A.dtype == np.f...
9951965
print("Thank for your enrolling in ITC110.") print("Let's setup your BE 1130 username.") first_name = input("What is your first name? ") last_name = input("What is your last name? ") username = first_name[0] + last_name[:7] print ("Your username is {0}, and your password is: {1}".format( username.lower(), "<PASS...
9951973
import pytest from ..utils import data_dir, bert_files from tokenizers import BertWordPieceTokenizer class TestEncoding: @pytest.fixture(scope="class") def encodings(self, bert_files): tokenizer = BertWordPieceTokenizer.from_file(bert_files["vocab"]) single_encoding = tokenizer.encode("I love...
9952009
from __future__ import absolute_import from .solver import Solver from .alpha_vector import AlphaVector from scipy.optimize import linprog import numpy as np from itertools import product class ValueIteration(Solver): def __init__(self, agent): """ Initialize the POMDP exact value iteration solver...
9952012
if __name__ == '__main__': # take input as a number N = int(input()) # define two lists z=[] l=[] for i in range(N): # add some input to the end of list z z.append(input()) for x in z: y=x.split() if y[0]=='insert': # insert the secound argument at...
9952019
from xbox.nano.packet import control def session_create(**kwargs): return control.session_create(**kwargs) def session_create_response(**kwargs): return control.session_create_response(**kwargs) def session_destroy(**kwargs): return control.session_destroy(**kwargs) def video_statistics(**kwargs): ...
9952058
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode from armulator.armv6.shift import shift from armulator.armv6.bits_ops import sign_extend, signed_sat_q class Ssat(AbstractOpcode): def __init__(self, saturate_to, d, n, shift_t, shift_n): super(Ssat, self).__init__() self.saturate_...
9952072
import pytest from peewee_validates import DEFAULT_MESSAGES from peewee_validates import ModelValidator from peewee_validates import ValidationError from peewee_validates import ManyModelChoiceField from tests.models import BasicFields from tests.models import ComplexPerson from tests.models import Course from tests....
9952096
from argparse import ArgumentParser from ..predict import AutoLGBMPredict from . import BaseCommand def predict_autolgbm_command_factory(args): return PredictAutoLGBMCommand(args.model_path, args.test_filename, args.out_filename) class PredictAutoLGBMCommand(BaseCommand): @staticmethod def register_sub...
9952113
import json def make_item(name, bread, meat, cost, charge): return {'name': name, 'bread': bread, 'meat': meat, 'my_cost': cost, 'my_charge': charge } menu = [] menu.append(make_item('Roasted B', 'white', 'Roast Beef', 5.00, 7.00)) menu.append(make_ite...
9952126
from setuptools import setup from setuptools import find_packages version = '0.1' setup(name='keras-text', version=version, description='Text classification library for Keras', author='<NAME>', author_email='<EMAIL>', url='https://github.com/raghakot/keras-text', download_url='htt...
9952181
import json from aim.web.api.dashboard_apps.models import ExploreState def explore_state_response_serializer(es_object): if not isinstance(es_object, ExploreState): return None response_schema = { 'id': es_object.uuid, 'type': es_object.type, 'updated_at': es_object.updated_at...
9952199
import os import subprocess from sgfmill import sgf def get_response_move(filename): ''' shell out and call the gnugo program and give it an in sgf file and an out sgf file''' cmd = r'bin\gnugo-3.8\gnugo.exe --infile '+ filename + r' --quiet --outfile sgf_files\response.sgf' p = subprocess.Popen(cmd, std...
9952283
from .train_options import TrainOptions class HyperparameterSearchOptions(TrainOptions): """This class includes hyperparameter search options. It also includes shared options defined in TrainOptions. """ def initialize(self, parser): parser = TrainOptions.initialize(self, parser) par...
9952290
from typing import Any, Dict, Text import pytest import copy import re from pytest import Testdir from rasa.__main__ import create_argument_parser import rasa.cli.data import rasa.cli.scaffold import rasa.cli.train import rasa.cli.shell import rasa.shared.utils.io from rasa.utils.common import EXPECTED_WARNINGS @...
9952339
from tests.create_test_db import engine, session, Base from constants import (CHARACTER_EQUIPMENT_BOOTS_KEY, CHARACTER_EQUIPMENT_LEGGINGS_KEY, CHARACTER_EQUIPMENT_BELT_KEY, CHARACTER_EQUIPMENT_GLOVES_KEY, CHARACTER_EQUIPMENT_BRACER_KEY, CHARACTER_EQUI...
9952340
import sys import hashlib def main(): try: file = open(sys.argv[1], 'rb') md5 = hashlib.md5() buffer = file.read(2 ** 20) while buffer: md5.update(buffer) buffer = file.read(2 ** 20) file.close() print(md5.hexdigest()) except: impo...
9952362
import os import subprocess import json print os.getcwd() json_file = "/Dropbox/CyclopsVFX/CYC_envs.json" os.chdir("/Dropbox/CyclopsVFX/Apps/Arges/") print os.getcwd() new_dict = {} with open(json_file) as j: env = json.load(j) cyc_env = env.get("CYC_envs") for key, value in cyc_env.iteritems...
9952394
from typing import Iterator import numpy as np from torch.utils.data.sampler import BatchSampler, Sampler, SubsetRandomSampler from ..prelude import Array def sample_indices(n: int, k: int) -> Array: """Sample k numbers from [0, n) Based on https://github.com/chainer/chainerrl/blob/master/chainerrl/m...
9952429
from hdlConvertorAst.to.hdl_ast_visitor import HdlAstVisitor from hdlConvertorAst.translate.verilog_to_basic_hdl_sim_model.wrap_module_statements_to_processes import collect_hdl_ids from hdlConvertorAst.hdlAst import HdlIdDef def all_ids_constant(expr): all_ids = set() collect_hdl_ids(expr, all_ids) for hi...
9952462
from datasette_jq import prepare_connection import sqlite3 import pytest import json @pytest.mark.parametrize( "data,jq,expected", ( ({"foo": "bar"}, ".foo", '"bar"'), ({"foo": [1, 2, 3, 4, 5]}, ".foo[:2]", "[1, 2]"), ), ) def test_jq(data, jq, expected): conn = sqlite3.connect(":memor...
9952469
import pytest from runner import ProjectType from glotter import project_test, project_fixture from test.utilities import clean_list usage = "Usage: please provide a comma-separated list of integers" invalid_permutations = ( 'description,in_params,expected', [ ( 'no input', None, ...
9952518
from hubspot import HubSpot from hubspot.cms.blogs.tags import TagApi def test_is_discoverable(): apis = HubSpot().cms.blogs.tags assert isinstance(apis.tag_api, TagApi)
9952525
import logging import sys def Bed_File(fName, mode='r'): if mode == 'r': return Bed_Reader(fName) elif mode == 'w': return Bed_Writer(fName) else: raise ValueError(f"Invalid mode: {mode}") class Bed_Reader: def __init__(self, inFile): self.file = open(inFil...
9952542
import vtk class Line(object): def __init__( self, point_1, point_2, color=(0, 0, 0), width=1, renderer=None): self.line = vtk.vtkLineSource() mapper = vtk.vtkPolyDataMapper2D() mapper.SetInputConnection(self.line.GetOutputPort()) self.actor = vtk.vtkActor2D() ...
9952558
import os import pandas as pd from datetime import datetime import backtrader as bt class BuyAndHold(bt.Strategy): def __init__(self): # To keep track of pending orders and buy price/commission self.order = None def log(self, txt, dt=None): ''' Logging function fot this strategy''' ...
9952601
import os import re import urllib.request import pickle from docker import Client # TODO: Check if Docker daemon is running. Start it if it's not. class DockerNotInstalledError(Exception): pass class ContainerHandler: def __init__(self, cage_path, app_path): self.__path = cage_path self.__...
9952626
from __future__ import division import numpy as np from openmdao.api import ExplicitComponent gamma = 1.4 R = 287.058 class SpeedOfSoundComp(ExplicitComponent): ''' This component computes speed of sound from temperature. Adapted from: <NAME>, <NAME>, and <NAME>: Design and Trajectory Optimization...
9952629
from fence.resources import userdatamodel as udm from fence.errors import UserError, NotFound def get_group(current_session, groupname): return udm.get_group(current_session, groupname) def get_group_info(current_session, groupname): group = get_group(current_session, groupname) if not group: ra...
9952636
import gdb import sys import os current_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, current_path) sys.path.insert(1, current_path + "/../") import core_dump_lib import gdb_lib def show_pending_callback(): output = gdb.execute("p pos::gDumpSharedModulePtr", to_string=True) pending_ob...
9952644
Donor = ["[N;!H0;v3,v4&+1]", "[O,S;H1;+0]", "[n&H1&+0]"] Acceptor = ["[O,S;H1;v2;!$(*-*=[O,N,P,S])]", "[O;H0;v2]", "[O,S;v1;-]", "[N;v3;!$(N-*=[O,N,P,S])]", "[n&H0&+0]", "[o;+0;!$([o]:n);!$([o]:c:n)]"] Positive = ["[#7;+]", "[N;H2&+0][$([C,a]);!$([C,a](=O))]", "[N;H1&+0]([$([C,a]);!$([C,a...
9952650
import logging import time import random from typing import Union from typing import Any from typing import Dict from typing import Optional from typing import List from typing import Tuple from typing import Set from typing import Callable from pyspark.sql.types import StructType from pyspark.sql.types import StructFi...
9952665
from __future__ import absolute_import from __future__ import print_function from ..common.geometry import Point, Polygon, Envelope, SpatialReference from .._abstract.abstract import BaseGeoEnrichment from ..manageorg import Administration import json import csv import os import numpy as np ############################...
9952702
from hwtypes import BitVector, Bit import magma as m from magma.simulator.python_simulator import PythonSimulator from magma.simulator.coreir_simulator import CoreIRSimulator from magma.scope import Scope import fault.actions from fault.target import Target from .select_path import SelectPath from .wrapper import PortW...
9952710
from setuptools import find_packages, setup setup( name="pysen_ls", version="0.1.2", packages=find_packages(), description="A language server implementation for pysen", long_description=open("README.md").read(), long_description_content_type="text/markdown", author="<NAME>", author_emai...
9952814
from httpx import AsyncClient from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.main import app from app.models import User from app.tests.conftest import ( default_user_email, default_user_id, default_user_password_hash, ) async def test_read_current_user(client: Asy...
9952843
sign = lambda a: (a>0) - (a<0) def pairs_in_order(ranking, both_ways=True): assert len(ranking) > 1 for idx1, val1 in enumerate(ranking): for idx2, val2 in enumerate(ranking): if idx2 > idx1: yield val1, val2, sign(idx2-idx1) if both_ways: ...
9952926
import os import numpy as np import pandas as pd import argparse import colorsys import cv2 import PIL from PIL import Image import matplotlib.pyplot as plt import matplotlib.pylab as pylab def load(im_path): """ Given an image path, returns a PIL image """ pil_image = Image.open(im_path).convert("RGB...
9953009
class Solution: def earliestAcq(self, logs: List[List[int]], N: int) -> int: parent = [i for i in range(N)] def findParent(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x count = N for time, a, b i...
9953016
import os from datetime import datetime, timezone from unittest import TestCase from draft_kings.response.objects.contests import Contest, ContestAttributes, DraftGroup from draft_kings.response.schema.contests import ContestsSchema from tests.config import ROOT_DIRECTORY class TestUpcomingNFLContests(TestCase): ...
9953025
from admin_honeypot.models import LoginAttempt from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.test import RequestFactory, tag, TestCase from django.test.client import Client from django.urls import reverse from django_otp import DEVICE_ID_SESSION_KEY from django_otp.ad...
9953065
from setuptools import setup setup( name="small_fake_with_deps", version=0.1, install_requires=["small-fake-a==0.1", "small-fake-b==0.1"], )
9953076
import tensorflow as tf from tensorflow.python.framework import ops import gradient_reversal_op @ops.RegisterShape("Gradientreversal") def _gradient_reversal_shape(op): output_shape = op.inputs[0].get_shape() return [output_shape] @ops.RegisterGradient("Gradientreversal") def _gradient_reversal_grad(op, grad): ...
9953084
from setuptools import setup, find_packages from os.path import join with open('README.md') as readme_file: readme = readme_file.read() with open('requirements.txt') as requirements_file: requirements = requirements_file.read().splitlines() with open('CHANGELOG.md') as history_file: history = history_...
9953105
import json import requests from utils import LogHelper, NetworkHelper, StateMachineHelper class UserRequester(object): app = None def __init__(self): NetworkHelper.config_server({ 'endpoints': { '/webhook-lrs': self.webhook } }) def webhook(self, params): LogHelper.log('WEBHOOK RECEIVED ...') ...
9953116
import random import numpy as np __all__ = [ 'random_walk_based_mp', 'random_walk_based_seq', 'random_walk_spacey_mp', 'MetaGraphGenerator'] def random_walk_based_mp(g, metapath, num_walks, walk_length, outfilename): # MP based RW is only applicable for metapaths with same source and target nodes...
9953137
import contextlib import datetime import os import shutil import uuid __all__ = ['get_extname', 'is_file_exist', 'file_remove', 'open_tmp_path', 'get_relpath'] def get_extname(path, match_first=False): if match_first: path = os.path.split(path)[1] return path[path.find('.'):] else: re...
9953161
from typing import Any from typing import Dict def upgrade(baseline: Dict[str, Any]) -> None: for function in [ _add_new_default_filters, ]: function(baseline) def _add_new_default_filters(baseline: Dict[str, Any]) -> None: baseline['filters_used'].extend([ { 'path': ...
9953176
from twisted.internet.defer import Deferred, DeferredList class PendingDeferreds(object): def __init__(self, dfds=None): super().__init__() self._dfds = set() if dfds: for dfd in dfds: self.add(dfd) def add(self, dfd): if not isinstance(dfd, Deferre...
9953201
from os.path import dirname, realpath, sep from os import getenv from unittest import TestCase from buidl.tx import TxFetcher class OfflineTestCase(TestCase): cache_file = dirname(realpath(__file__)) + sep + "tx.cache" @classmethod def setUpClass(cls): # fill with cache so we don't have to be on...
9953203
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from rlkit.torch.core import PyTorchModule from rlkit.torch.networks import Mlp from rlkit.torch import pytorch_util as ptu from rlkit.torch.torch_meta_irl_algorithm import np_to_pytorch_batch fr...
9953213
import tensorflow as tf class Decoder(object): def __init__(self, cfg): self.cfg = cfg def __call__(self, input): with tf.varible_scope("decoder"): h1 = tf.contrib.layers.conv2d_transpose(input, num_outputs=64, kernel_size=4, str...
9953227
from pydantic.networks import EmailStr from sqlalchemy import Column, Integer, String, ForeignKey from dispatch.database.core import Base from dispatch.models import NameStr, PrimaryKey from dispatch.models import ResourceBase, ResourceMixin class Group(Base, ResourceMixin): id = Column(Integer, primary_key=True...
9953269
from pathlib import ( Path, ) BASE_PATH = Path(__file__).parent CONFIG_FILE_PATH = BASE_PATH / "test_config.yml" class FakeAsyncIterator: """For testing purposes.""" def __init__(self, seq): self.iter = iter(seq) def __aiter__(self): return self async def __anext__(self): ...
9953287
from enum import Enum import numpy as np R = 6373000.0 # approximate radius of earth in mts def vectors(points): """Provides a array of vectors on cartesian space (x, y). Each vector represents the path from a point in `points` to the next. `points` must by a (N, 2) array of [lat, lon] pairs in radians...
9953292
import os import sys import re import shutil def find_matching_dirs(dirname): for filename in os.listdir(dirname): filepath = os.path.join(dirname, filename) if os.path.isdir(filepath): if re.search('_(jpg|jp2)$', filename): yield filepath else: ...
9953323
from bs4 import BeautifulSoup import requests # Written by <NAME> (@R8T3D) # Under the MIT license # you need to change this to yours cart_id = 'YOUR CART ID' # this shouldn't change, only have it as a variable just in case. x_api_key = '<KEY>' class FootpatrolAPI(object): def __init__(self): self.s = requests....
9953375
from logging import getLogger from pgopttune.workload.sampled_workload import SampledWorkload from pgopttune.objective.objective import Objective from pgopttune.config.postgres_server_config import PostgresServerConfig from pgopttune.config.tune_config import TuneConfig from pgopttune.config.sampled_workload_config imp...
9953384
import io import logging from contextlib import redirect_stderr, redirect_stdout import numpy as np import open3d as o3d from PIL import Image, ImageChops # Value defined in Open3D # https://github.com/intel-isl/Open3D/blob/master/src/Open3D/Visualization/Visualizer/ViewControl.cpp ROTATION_RADIAN_PER_PIXEL = 0.003 ...
9953401
from io import TextIOWrapper from pathlib import Path from typing import List, Mapping, Optional import click import yaml from . import compile_namespace, rst_to_myst, to_docutils_ast from .utils import yaml_dump @click.group(context_settings={"help_option_names": ["-h", "--help"]}) @click.version_option() def main...
9953409
from baconian.envs.dmcontrol_env import have_mujoco_flag import unittest class TestEnv(unittest.TestCase): def test_dmcontrol_env(self): if have_mujoco_flag: from baconian.envs.dmcontrol_env import DMControlEnv a = DMControlEnv('cartpole', 'swingup') a.set_status('TRAIN...
9953422
import logging import queue from threading import Thread from Giveme5W1H.extractor.combined_scoring import distance_of_candidate from Giveme5W1H.extractor.extractors import action_extractor, environment_extractor, cause_extractor, method_extractor from Giveme5W1H.extractor.preprocessors.preprocessor_core_nlp import Pr...
9953444
import torch import torch.nn as nn import torch.nn.functional as F from lib.pspnet import PSPNet from lib.utils import sample_rotations_12, sample_rotations_24, sample_rotations_60 psp_models = { 'resnet18': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='resnet18'), 'resnet3...
9953447
class Animal: def eat(self, food): if self._is_meat(food): print('Om nom nom') def _is_meat(self, food): return food == 'meat' Animal().eat('meat')
9953448
import unittest import gevent from scales.constants import ChannelState from scales.loadbalancer import HeapBalancerSink from test.scales.loadbalancer.base_tests import LoadBalancerTestCase class HeapBalancerTestCase(LoadBalancerTestCase): SINK_CLS = HeapBalancerSink def testHeapOpensAllChannels(self): self...
9953462
import os import json from collections import OrderedDict class Config(object): def __init__(self, image_name, aws_profile, aws_region, python_version, sagify_module_dir, requirements_dir): self.image_name = image_name self.aws_profile = aws_profile self.aws_region = aws_region sel...
9953472
class Milestone: def __init__(self, projectName: str, milestoneId: int ): self._projectName = projectName self._milestoneId = milestoneId self._issues = [] @property def projectName(self): return self._projectName @property def milestoneId(self): return...
9953489
from ..errors.validation import Validation from ..constants import DOCUMENT, LIST_ITEM class ElementBase: def __init__(self, context, instruction, parent=None): self._context = context self._instruction = instruction self._parent = parent # TODO: Could be set optionally as well (needs hasa...
9953500
from mock import patch from scrapyrt.decorators import deprecated from scrapyrt.exceptions import ScrapyrtDeprecationWarning class TestDecorators(object): def test_deprecated(self): @deprecated def test_func(*args, **kwargs): return (args, kwargs) with patch('warnings.warn') ...
9953537
import FWCore.ParameterSet.Config as cms import RecoVertex.PrimaryVertexProducer.primaryVertexProducer_cfi as _mod offlinePrimaryVerticesFromCosmicTracks = _mod.primaryVertexProducer.clone( TrackLabel = "ctfWithMaterialTracksP5", beamSpotLabel = "offlineBeamSpot", ...
9953577
import random import torch import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc import torch.multiprocessing as mp import torch.optim as optim from torch.distributed.nn import RemoteModule from torch.distributed.optim import DistributedOptimizer from t...
9953586
from multiprocessing import Pool as ProcessPool from multiprocessing.dummy import Pool as ThreadPool from common import timed NUM_WORKERS = 8 # four cores def fib(n): """Calculate the n-th element of Fibonacci.""" a, b = 1, 1 while n > 1: a, b = b, a + b n -= 1 return a timed(fib, ...
9953604
import os from collections.abc import Mapping import yaml # The configuration can be overloaded by a local 'shenfun.yaml' file, or # in '~/.shenfun/shenfun.yaml'. A yaml file to work with can be created # using the `dumpconfig` function below config = { 'optimization': { 'mode': 'cython', 'ver...