id
stringlengths
3
8
content
stringlengths
100
981k
9986333
from common.params import Params import time CACHE = {} class CachedParams: def __init__(self): self.params = Params() def get_float(self, key, ms): return float(self.get(key, ms)) def get_bool(self, key, ms): return self.get(key, ms) == "1" def get(self, key, ms): current_ms = round(time.t...
9986356
from .lib.symengine_wrapper import Symbol, Basic from itertools import combinations, permutations, product, product as cartes import re as _re import string import sys _range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])') def symbols(names, **args): """ Transform strings into instances of :class:`Symbo...
9986404
from .. import db class UseOfForce(db.Model): id = db.Column(db.Integer, primary_key=True) incident_id = db.Column(db.Integer, db.ForeignKey("incident.id")) item = db.Column(db.Text())
9986434
import pytest from rotkehlchen.accounting.ledger_actions import LedgerAction, LedgerActionType from rotkehlchen.accounting.mixins.event import AccountingEventType from rotkehlchen.accounting.pnl import PNL, PnlTotals from rotkehlchen.constants import ONE, ZERO from rotkehlchen.constants.assets import A_ETH, A_EUR, A_K...
9986446
from runner import Runner import logging import time from postprocessing import PostProcessing from event import Event import config from context import Context from prepare import Prepare from write import Writer import utils import sys import argparse from simulationfiles import checkargs def _create_parser(): ...
9986460
from creme import utils from . import base __all__ = ['SGD'] class SGD(base.Optimizer): """Plain stochastic gradient descent. Parameters: lr Example: >>> from creme import datasets >>> from creme import evaluate >>> from creme import linear_model >>> from crem...
9986476
import pytest from django.urls import reverse from django.utils import timezone from rest_framework.status import ( HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_405_METHOD_NOT_ALLOWED) from ..utils import ALL_METHODS, check_method_status_codes list_url = reverse('monitoring:v1:valid_parking-list') def detail...
9986531
import os import torch import argparse import numpy as np from model import LSTM_Net from cm_fig import save_cm_fig from sklearn.metrics import confusion_matrix def get_args(): parser = argparse.ArgumentParser(description='Argument Parser for downstream evaluation') ### mode ### parser.add_argument('--task...
9986562
SECRET_KEY = 'this is a not very secret key' # all test databases need to have different name or they will not be picked up by django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'daiquiri_app', 'USER': 'daiquiri_app', 'PASSWORD': '<PASSWORD>', ...
9986612
import numpy as np class Delay(object): """Multi-channel delay line. Parameters: nchannels (int): number of channels to process delay (int): number of samples to delay by """ def __init__(self, nchannels, delay): assert delay >= 0 self.delaymem = np.zeros((delay, ncha...
9986623
from .fixtures import BING_MAPS_KEY, parametrize from bingmaps.apiservices import ElevationsApi DATA = [ {'method': 'List', 'points': [15.5467, 34.5676], 'key': BING_MAPS_KEY }, {'method': 'Polyline', 'points': [35.89431, -110.72522, 35.89393, -110.72578], 'samples': 10, 'key': BI...
9986659
from django.db import models from django.conf import settings from django.contrib.auth.models import User class Language(models.Model): user = models.ForeignKey(User) language = models.CharField(max_length=10, choices=settings.LANGUAGES)
9986660
import ldnlib import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description="""For a provided web resource, discover an ldp:inbox and POST the provided RDF to the receiver, if one exists""") parser.add_argument("target", help="The IRI of the target web resource") ...
9986663
from marshmallow import fields, Schema class PetSchema(Schema): id = fields.Integer(required=False) name = fields.Str(required=True) tag = fields.Str(required=False)
9986667
import pytest import numpy as np import torch import torch.nn as nn from collections import OrderedDict from torchmeta.modules import MetaModule from torchmeta.modules.conv import MetaConv1d, MetaConv2d, MetaConv3d @pytest.mark.parametrize('bias', [True, False]) @pytest.mark.parametrize('padding_mode', [None, 'zero...
9986672
import tensorflow as tf sess = tf.InteractiveSession() x = tf.constant([[1., 2.]]) neg_op = tf.negative(x) result = neg_op.eval() print(result) sess.close()
9986689
import itertools from collections import Collection, Mapping, OrderedDict, Sequence from .specs import DynamicAnnotation, DynamicPrefetch, DynamicSelect, DynamicSpec from django.core.exceptions import FieldDoesNotExist def tagged_chain(*iterables, tag_names=None): """ An itertools.chain modification, tha...
9986712
import pytest from leapp.libraries.actor.cupsfiltersmigrate import NEW_MACROS, update_config def _gen_append_str(list_out=None): """ Just helper function to generate string expected to be added for an input (see testdata) for testing. :param list list_out: None, [0], [1], [0,1] - no more expected vals, ...
9986718
import configparser def default_material_library(path): config = configparser.ConfigParser() config['STEEL'] = { 'Name': 'steel', 'Identifier': 1, 'Color': '[170,170,170]', #Light Gray 'Density': 7...
9986750
import pytest from sqlfmt.api import format_string from sqlfmt.mode import Mode from tests.util import check_formatting, read_test_data @pytest.mark.parametrize( "p", [ "preformatted/001_select_1.sql", "preformatted/002_select_from_where.sql", "preformatted/003_literals.sql", ...
9986767
from typing import * import logging import numpy as np try: from rpy2.robjects.packages import importr import rpy2.robjects as ro from rpy2.robjects import numpy2ri def convert_r_obj(v: Any, obj_to_obj: bool=True, verbose: bool=True) -> Any: """Function with manually specified conversion from ...
9986814
import os import tempfile # SERVER CONFIGURATION SERVER_HOST = "127.0.0.1" SERVER_PORT = 5000 # SSL config: path to certificate and private key files CERTIFICATE = None PRIVATE_KEY = None # Max number of processes to fork when handling requests MAX_PROCESSES = 10 # Enable debugging DEBUG = False # The secret key ...
9986882
from boa3.builtin import public @public def range_example(start: int, stop: int) -> range: return range(start, stop)
9986884
import tensorflow as tf import numpy as np l_num = 0 ########################################################### #define weight and bias initialization def weight(shape,dtype=None): return tf.get_variable('weight',shape,initializer=tf.contrib.layers.xavier_initializer(),dtype=dtype) def bias(shape,value=0.1,dtyp...
9986895
import os import json class HostContext: instances_json_path = None context_json_path = None @classmethod def get_context_title(cls): project_name = os.environ.get("AVALON_PROJECT") if not project_name: return "TestHost" asset_name = os.environ.get("AVALON_ASSET")...
9986898
import abc from .response import Response class BaseClient(abc.ABC): @abc.abstractmethod def get(self, url: str, **kwargs) -> Response: pass @abc.abstractmethod def post(self, url: str, **kwargs) -> Response: pass @abc.abstractmethod def patch(self, url: str, **kwargs) -> Re...
9986919
from datetime import datetime from bson.objectid import ObjectId from pymongo import MongoClient from .utils import log from osu_map_gen.util import definitions client = MongoClient(definitions.MONGO_URL) db = client.Osu # job statuses STATUS_PENDING = 0 STATUS_FAILED = 1 STATUS_GENERATED = 2 def beatmap_data(bea...
9986924
import textile import siptracklib.errors from siptrackweb.views import helpers from siptrackweb.forms import * def parse_attributes(obj): attr_list = {'standard': [], 'important': [], 'wikitext': [], 'large': []} for attr in obj.attributes: if attr.attributes.get('wikitext'): value = attr...
9986927
class BasicModel(dict): def filter_keys(self, *keys): rest = {} for k, v in self.items(): if k not in keys: rest[k] = v return rest def __setattr__(self, key, value): self[key] = value def __getattr__(self, item): if item == '...
9986953
r""" An introduction to crystals =========================== Informally, a crystal `\mathcal{B}` is an oriented graph with edges colored in some set `I` such that, for each `i\in I`, each node `x` has: - at most one `i`-successor, denoted `f_i x`; - at most one `i`-predecessor, denoted `e_i x`. By convention, one w...
9987027
from django.urls import path from . import views urlpatterns = [ path('', views.home), path('url', views.url), path('detail', views.detail), path('lists', views.lists), path('group', views.group), path('related', views.related), path('sub', views.sub), ]
9987029
from collections import defaultdict import maya.cmds as m from maya.mel import eval as meval def doDuplicateExtract(): selection = m.ls(sl=True, l=True) if not selection: raise RuntimeError('Bad selection. Select some polygons.') components = defaultdict(list) for s in selection: spl...
9987065
from gql import gql from typing import Dict, List, Optional from specklepy.logging import metrics from specklepy.api.models import Stream from specklepy.api.resource import ResourceBase NAME = "stream" METHODS = [ "list", "create", "get", "update", "delete", "search", ] class Resource(Resour...
9987086
from event_log.utils import log_creations, INSTANCE from ..models import FeedbackMessage log_creations( FeedbackMessage, feedback_message=INSTANCE, created_by=lambda feedback_message: feedback_message.author, context=lambda feedback_message: feedback_message.context, )
9987101
from test_utils import run_query def test_isvalid(): result = run_query( """ SELECT @@RS_PREFIX@@placekey.ISVALID(NULL) UNION ALL SELECT @@RS_PREFIX@@placekey.ISVALID('@abc') UNION ALL SELECT @@RS_PREFIX@@placekey.ISVALID('abc-xyz') UNION ALL SELECT...
9987125
r""" ====================== Single recurrence plot ====================== A recurrence plot is an image obtained from a time series, representing the pairwise Euclidean distances for each value (and more generally for each trajectory) in the time series. The image can be binarized using a threshold. It is implemented ...
9987150
from darshan.report import * import datetime import copy def merge(self, other, reduce_first=False): """ Merge two darshan reports and return a new combined report. Args: mods: Name(s) of modules to preserve (reduced) name_records: Id(s)/Name(s) of name_records to preserve (r...
9987192
from xmlrpc import client from xmlrpc.client import ServerProxy from xmlrpc.client import Fault import logging as log WIKI_URL = None WIKI_USER = None WIKI_PASSWORD = <PASSWORD> WIKI_SPACE = None WIKI_ALL_PAGE = None class ConfluenceError(Exception): pass class ConfluencePoster(object): def __init__(self, base_...
9987208
import numpy as np import galsim import batoid from test_helpers import timer, init_gpu @timer def test_zernikeGQ(): if __name__ == '__main__': nx=1024 rings=10 tol=1e-4 else: nx=128 rings=5 tol=1e-3 telescope = batoid.Optic.fromYaml("LSST_r.yaml") teles...
9987221
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adverts', '0003_universitas_ad_channels'), ] operations = [ migrations.AddField( model_name='advert', name='extra_classes', field=models.CharField(max_le...
9987278
import logging import fmcapi import time def test__slamonitor(fmc): logging.info("Test SLAMonitor. Post, get, put, delete SLAMonitor Objects.") starttime = str(int(time.time())) namer = f"_fmcapi_test_{starttime}" sz1 = fmcapi.SecurityZones(fmc=fmc) sz1.name = "SZ-OUTSIDE1" sz1.interfaceMod...
9987279
import unittest from chainer import testing import numpy as np from chainerrl.explorers.additive_ou import AdditiveOU @testing.parameterize(*testing.product({ 'action_size': [1, 3], 'sigma_type': ['scalar', 'ndarray'], })) class TestAdditiveOU(unittest.TestCase): def test(self): def greedy_act...
9987354
import sys import os SCRIPT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(SCRIPT_DIR)) from preflibtools.instances.preflibinstance import PreflibInstance from preflibtools.instances.drawing import drawInstance def writeTestTocFile(filePath): file = open(filePath, ...
9987362
from tests.factories.page import * # noqa: F401,F403 from tests.factories.site import * # noqa: F401,F403
9987436
from rwp.sspade import * from rwp.vis import * logging.basicConfig(level=logging.DEBUG) env = Troposphere(flat=True) env.z_max = 200 h = 20 w = 1000 x1 = 3000 env.terrain = Terrain(lambda x: h/2*(1 + fm.sin(fm.pi * (x - x1) / (2*w))) if -w <= (x-x1) <= 3*w else 0) max_range = 10000 ant_mm = GaussAntenna(freq_hz=300...
9987451
n = int(input()) arr = [int(x) for x in input().split()] if sum(arr) % n == 0: print (n) else: print (n-1)
9987456
from django.contrib import admin # Register your models here. from article.models import Article, Category @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('id', 'name') list_per_page = 20 @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ('id...
9987468
import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def sigmoid_compute_cls_scores(input_matches, valid_idxs): """ Computes proper scoring rule for multilabel classification results provided by retinanet. Args: input_matches (dict): dictionary containing input matc...
9987508
from subprocess import Popen from meiga import Error, Result, isSuccess from lume.src.application.use_cases.messages import get_colored_command_message from lume.src.domain.services.killer_service import KillerService from lume.src.domain.services.logger import COMMAND, Logger class PopenKillerService(KillerService...
9987514
class FieldDomainPointsByUV(FieldDomainPoints,IDisposable): """ Represents a set of two-dimensional point coordinates (defined usually on surface) FieldDomainPointsByUV(points: IList[UV],uCoordinates: ICollection[float],vCoordinates: ICollection[float]) FieldDomainPointsByUV(points: IList[UV]) """ ...
9987526
import logging from functools import cached_property from typing import Any class MixinLoggingSettings: @classmethod def validate_log_level(cls, value: Any) -> str: try: getattr(logging, value.upper()) except AttributeError as err: raise ValueError(f"{value.upper()} is ...
9987591
import argparse import json import os import subprocess from os import makedirs, remove from os.path import abspath, join, exists, dirname from jinja2 import Template CMDS = ["list", "add", "del", "gen"] VHOSTM_CONFIG = ".vhostm.conf" DEFAULT_NGINX_TEMPLATE = """ upstream {{domain}} { server {{address}}:{{port}...
9987607
import k2 s1 = ''' 0 1 0 0.1 0 1 1 0.2 1 1 2 0.3 1 2 -1 0.4 2 ''' s2 = ''' 0 1 1 1 0 1 2 2 1 2 -1 3 2 ''' a_fsa = k2.Fsa.from_str(s1) b_fsa = k2.Fsa.from_str(s2) c_fsa = k2.intersect(a_fsa, b_fsa) a_fsa.draw('a_fsa_intersect.svg', title='a_fsa') b_fsa.draw('b_fsa_intersect.svg', title='b_fsa') c_fsa.draw('c_fsa_inte...
9987649
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os.path as osp import joblib MAIN_PATH = '/scratch/gobi2/kamyar/oorl_rlkit/output' WHAT_TO_PLOT = 'faster_all_eval_stats.pkl' # WHAT_TO_PLOT = 'faster_all_eval_stats.pkl' # WHAT_TO_PLOT = 'faster_all_eval_stats.pkl' dat...
9987700
from django.db import models class User(models.Model): account = models.ForeignKey('accounts.Account', blank=True, null=True, related_name='users') active_record = models.ForeignKey('records.Record', blank=True, null=True)
9987717
import pytest import click.testing from openfecli.cli import OpenFECLI, main from openfecli.plugins import OFECommandPlugin class TestCLI: def setup(self): self.cli = OpenFECLI() def test_invoke(self): runner = click.testing.CliRunner() with runner.isolated_filesystem(): ...
9987754
import time from pathlib import Path import torchvision from omegaconf import OmegaConf from ganslate.utils import communication, io from ganslate.utils.trackers.tensorboard import TensorboardTracker from ganslate.utils.trackers.wandb import WandbTracker class BaseTracker: """"Base for training and inference tr...
9987810
import ccxtpro from pprint import pprint from asyncio import run print('CCXT Pro Version:', ccxtpro.__version__) async def main(): exchange = ccxtpro.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) markets = await exchange.load_markets() # exchange.verbose = True #...
9987851
import math import pandas as pd import plotly.express as px import plotly.graph_objects as go sizeref = 2000 # Dictionary with dataframes for each continent continent_names = ['DLA', 'Resnet', 'MobileNet', 'ShuffleNet', 'HigherResolution', 'HardNet'] continent_data = {} continent_data['DLA-34'] = {'map':[62.3], 'sp...
9987873
import copy import tqdm import shutil from PIL import Image import logging import argparse import os import torch import torch.distributed as dist import torch.utils.data as data_utils import torchvision.transforms as tv_trans from torchvision.utils import save_image from tl2.launch.launch_utils import update_parser_...
9987942
import json import unittest.mock from unittest import mock import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "configfinder/"))) import configfinder import helpers.utils sys.modules[ 'configfinder.builder'] = unittest.mock.Mock() # Mocking builder like so:https://stackoverflow.com/...
9987951
from flask import Flask from werkzeug.exceptions import HTTPException from app.misc.log import log def register_extensions(flask_app: Flask): from app import extensions extensions.cors.init_app(flask_app) def register_views(flask_app: Flask): from app.views import route route(flask_app) def reg...
9987970
import torch from torch.multiprocessing import Pipe from torch.distributions.categorical import Categorical import gym import numpy as np import os from envs import AtariEnvironment from arguments import get_args from model import CnnActorCriticNetwork def get_action(model, device, state): state = torch.Tensor(s...
9988006
from util import * from forecast import * # Read historical games from CSV games = Util.read_games("data/nfl_games.csv") # Forecast every game Forecast.forecast(games) # Evaluate our forecasts against Elo Util.evaluate_forecasts(games)
9988007
import gym import time import sys import MultiNEAT as NEAT import MultiNEAT.viz as viz import random as rnd import pickle import numpy as np import cv2 substrate = NEAT.Substrate([(-1, -1), (-1, 0), (-1, 1)], [(0, -1), (0, 0), (0, 1)], [(1, 0)]) substrate.m_allo...
9988011
from prometheus_client.core import GaugeMetricFamily from pandas import DataFrame from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.compute import ComputeManagementClient _BASE_COLUMNS = ['subscription', 'location', 'resource_group', 'vm_size'] _COUNT_COLUMN = ['total'] _ALL_COLUMNS =...
9988021
from linkedevents.settings import * # noqa INSTALLED_APPS += ['extension_course'] # noqag AUTO_ENABLED_EXTENSIONS += ['course'] # noqa
9988044
from django.conf.urls import url from django.views.decorators.cache import cache_page from . import views app_name = 'app' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), # (?P<article_id>\d+)为一个组, 其中?P<article_di>中的article_id代表了该组的组名 # url(r'^article/(?P<article_id>\d+)$', cache_page(...
9988071
from nose.tools import assert_equal from pydeeplator.deepL import DeepLTranslator, TranslateModeType, TranslateLanguageEnum TEST_ZH_SENTENCES: str = """ 今天天气很好,我和小明一起去爬山。我们在山上遇到了小红,一起快乐地写起了代码。 """ def test_translate_word(): result = DeepLTranslator( translate_str="水印", target_lang=TranslateLangua...
9988146
from typing import List, Tuple from warnings import warn import pandas as pd import numpy as np from sklearn.utils import indices_to_mask from sklearn.linear_model import Lasso, LogisticRegression from sklearn.linear_model._coordinate_descent import _alpha_grid from sklearn.model_selection import cross_val_score from...
9988158
import re # Regex for validating the email as per the RFC2822 EMAIL_REGEX = "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # noqa # Regex for Password based on the following conditions: # 1. Password must be between 8 and ...
9988161
from baldrick.config import Config, load, loads GLOBAL_TOML = """ [tool.baldrick] [tool.baldrick.plugin1] setting1 = 'a' setting2 = 'b' [tool.baldrick.plugin2] setting3 = 1 """ REPO_TOML = """ [tool.testbot] [tool.testbot.plugin1] setting2 = 'c' [tool.testbot.plugin2] setting3 = 4 setting4 = 1.5 [tool.testbot.pl...
9988170
from nonebot import on_command, CommandSession, get_bot from .utils import get_dragon @on_command('dragon', aliases=('龙图', '龙'), only_to_me=False) async def dragonimg(session: CommandSession): dragon = await get_dragon() await session.send(dragon) @dragonimg.args_parser async def _(session: CommandSession):...
9988187
import insightconnect_plugin_runtime from .schema import StringToFloatInput, StringToFloatOutput, Input, Output, Component # Custom imports below from insightconnect_plugin_runtime.exceptions import PluginException class StringToFloat(insightconnect_plugin_runtime.Action): def __init__(self): super(self....
9988196
import pytest from rest_framework import status from rest_framework.test import APITestCase from human_lambdas.user_handler.models import Organization from human_lambdas.workflow_handler.models import Task from human_lambdas.workflow_handler.region import Region from human_lambdas.workflow_handler.tests.constants impo...
9988202
import onnx import torch import torch.nn as nn from torch.onnx import TrainingMode class CNN(nn.Module): def __init__(self): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 32, 3, 1, 1), nn.ReLU(), nn.Conv2d(32, 32, 3, 1, 1), nn.ReLU(),...
9988214
import FWCore.ParameterSet.Config as cms ##____________________________________________________________________________|| from RecoMET.Configuration.RecoMET_cff import * from RecoMET.Configuration.RecoMET_BeamHaloId_cff import * hcalnoise.fillTracks = False CSCHaloData.CosmicMuonLabel = "muons" ##__________________...
9988224
import os from pgopttune.config.config import Config class SampledWorkloadConfig(Config): def __init__(self, conf_path, section='sampled-workload'): super().__init__(conf_path) self.conf_path = conf_path self.config_dict = dict(self.config.items(section)) self._check_is_exist_sampl...
9988237
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch from torchtext import data from torchtext.datasets import SequenceTaggingDataset, CoNLL2000Chunking from torchtext.vocab import Vectors, GloVe, CharNGram import numpy as np import random import lo...
9988295
import os from getpass import getpass from netmiko import ConnectHandler, file_transfer, progress_bar # Code so automated tests will run properly password = os.getenv("NETMIKO_PASSWORD") if os.getenv("NETMIKO_PASSWORD") else getpass() # Need a privilege15 account (no enable call) cisco3 = { "device_type": "cisco_...
9988309
from unittest.mock import call, sentinel import pytest from via.exceptions import ConfigurationError from via.services import create_google_api, load_injected_json class TestLoadInjectedJSON: def test_it(self, settings, tmpdir): json_file = tmpdir / "data.json" json_file.write('{"a": 1}') ...
9988310
from sys import stdin def gcd(a, b): while a % b: a, b = b, a % b return b for i, ln in enumerate(stdin): if i: if i % 2 == 1: n = int(ln) else: print n if reduce(gcd, map(int, ln.split())) == 1 else -1
9988371
import argparse parser = argparse.ArgumentParser(description='FIDTM') parser.add_argument('--dataset', type=str, default='ShanghaiA', help='choice train dataset') parser.add_argument('--save_path', type=str, default='save_file/A_baseline', help='save checkpoint directory') p...
9988387
import os import numpy as np import cv2 import torch class Logger(): def __init__(self, base_directory): self.base_directory = base_directory # Create directory to save data self.info_directory = os.path.join(self.base_directory, 'info') self.color_images_directory = os.path.jo...
9988403
from ..mapper import PropertyMapper, ApiInterfaceBase from ..mapper.types import Timestamp, AnyType from .user import User __all__ = ['UserCard', 'UserCardInterface'] class UserCardInterface(ApiInterfaceBase): user: User algorithm: str social_context: str caption: AnyType icon: AnyType media...
9988419
from zipfile import ZIP_DEFLATED as DEFLATED from xpisign.compat import BytesIO, ZipFile from xpisign.context import * from helper import * def test_StreamPositionRestore(): """StreamPositionRestore actually restores streams.""" with BytesIO() as bi: assert bi.tell() == 0 with StreamPosition...
9988425
import optuna import time import subprocess def objective(trial): x = trial.suggest_uniform('ratio1', -3.0, -0.0) y = trial.suggest_uniform('ratio2', -1.0, 2.0) cmd = "./a " cmd += str(pow(10, x)) cmd += " " cmd += str(pow(10, y)) d = subprocess.check_output(cmd.split()) return -float(d) start = tim...
9988432
from abc import ABC, abstractmethod from pattern.pattern import IPattern class Conjunctable(IPattern): @abstractmethod def is_conjuctable(self) -> bool: return True @abstractmethod def as_conjuctable(self): return self
9988528
import warnings from asyncio import Queue from typing import Any, Awaitable, Callable, Dict, Optional, Union from django.apps import apps def defer( func: Union[Callable[[Any], Awaitable], Callable], arguments: Optional[Dict] = None, *, options: Optional[Dict] = None ): """ Adds a function or cor...
9988547
import numpy as np from numpy.linalg import norm from .Line import Line class Plane: """Class to represent planes in a three dimensional space. Documentation obtained from: http://commons.apache.org/proper/commons-math /apidocs/org/apache/commons/math4/geometry/euclidean/threed/Plane.html Attributes ...
9988589
from colossalai.context.parallel_mode import ParallelMode import torch import torch.nn as nn import inspect from .layers import Embedding, BertLayer, BertDualHead, PreProcessor, VocabEmbedding from .layers.init_method import init_normal, output_init_normal from colossalai.core import global_context as gpc from colossal...
9988592
import abc import pandas as pd import warnings from copy import deepcopy from dockstream.core.ligand.ligand import Ligand from dockstream.utils.dockstream_exceptions import ResultParsingFailed from dockstream.loggers.docking_logger import DockingLogger from dockstream.utils.enums.logging_enums import LoggingConfigEnu...
9988604
from pymantic.rdf import Resource, register_class SKOS_NS = "http://www.w3.org/2004/02/skos/core#" NS_DICT = dict(skos = SKOS_NS) class SKOSResource(Resource): namespaces = NS_DICT scaler = ['skos:prefLabel'] @register_class("skos:Concept") class Concept(SKOSResource): pass @register_class("skos:Co...
9988681
from scivision.io import load_dataset, load_pretrained_model, wrapper, _parse_url, _parse_config, _get_model_configs import intake import pytest import fsspec import yaml def test_parse_url(): """Test that GitHub urls are correctly converted to raw.""" path = 'https://github.com/alan-turing-institute/scivisio...
9988687
import os from docutils import nodes try: from sphinx.util.compat import Directive except ImportError: from docutils.parsers.rst import Directive needs_sphinx = '1.6' author = 'MongoDB, Inc' # -- Options for HTML output ---------------------------------------------- smart_quotes = False html_show_sourcelink ...
9988691
from django.db import models # Create your models here. class Auto(models.Model): mark = models.CharField(max_length=50) model = models.CharField(max_length=50) colour = models.CharField(max_length=50) gov_number = models.IntegerField() class Owner(models.Model): first_name = models.CharField(max...
9988706
import powerlaw from matplotlib.pyplot import figure from matplotlib import rc import pylab from numpy import genfromtxt from matplotlib.font_manager import FontProperties pylab.rcParams['xtick.major.pad'] = '8' pylab.rcParams['ytick.major.pad'] = '8' # pylab.rcParams['font.sans-serif']='Arial' rc('font', ...
9988734
import torch def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor: """ Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch element, this function returns a ``(batch_size, max_length)`` mask variable. For example, i...
9988742
import geosoft.gxpy.gx as gx import geosoft.gxpy.utility as gxu gxc = gx.GXpy() url = 'https://github.com/GeosoftInc/gxpy/raw/9.3/examples/tutorial/Geosoft%20Databases/' gxu.url_retrieve(url + 'mag_data.csv')
9988743
import numpy as np class PredictionAnalysis(): def __init__(self, y_true, y_pred, dataset, reversed_original_mapping, reversed_virtual_mapping): self.y_true, self.y_pred = np.array(y_true), np.array(y_pred) self.dataset = dataset self.original_mapping, self.virtual_mapping = reversed_origin...