id
stringlengths
3
8
content
stringlengths
100
981k
9845039
import json import pickle import numpy as np from sklearn import preprocessing from datasets import DATASET def check_matchings(src_files, bug_reports): """Checking the matching tokens between bug reports and source files""" scores = [] for report in bug_reports.values(): matched_count = [] ...
9845070
import json as json_handler from balebot.models.base_models.response_body import ResponseBody from balebot.models.constants.errors import Error class GetLastSeqResponse(ResponseBody): def __init__(self, json): if isinstance(json, dict): json_dict = json elif isinstance(json, str): ...
9845083
from __future__ import print_function import math import torch import numpy as np # NOTE: assumes that the epoch starts with 1 def adjust_learning_rate(epoch, opt, optimizer): if hasattr(opt, 'cos') and opt.cos: # NOTE: since epoch starts with 1, we have to subtract 1 new_lr = opt.learning_rate *...
9845086
from django import template from socialregistration.templatetags import button register = template.Library() register.tag('tumblr_button', button('socialregistration/tumblr/tumblr_button.html'))
9845097
from os import getcwd from os.path import realpath import logging import click from . import __version__ from .merger import Merger @click.command() @click.version_option(version=__version__) @click.argument('path', type=click.Path(exists=True)) @click.option('--debug', default=False, is_flag=True, ...
9845109
import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('PublisherWeb') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import threading import web import json import random import Publisher webDataSource = None webTemplate = None class index(o...
9845114
import os import getpass from pathlib import Path from argparse import ArgumentParser from pyonepassword import OP, OPServerItem class ServerWithSSHKeys: SSH_KEYS_SECTION = "SSH Keys" PRIV_PERMS = 0o600 PUB_PERMS = 0o644 DIR_PERMS = 0o755 def __init__(self, server_item: OPServerItem): sel...
9845135
import logging # Global logger initialization PRINT = logging.getLogger("output") DEBUG = logging.getLogger("debug") def printDict(di, format="%-25s %s", log=None, loglvl=logging.DEBUG): for (key, val) in list(di.items()): if log: log.log(loglvl, format % (str(key) + ":", val)) else: ...
9845151
import numpy as np import random import re import torch import pdb import logging def clean_name(name): name = re.sub(r"\(.*\)", "", name) name = re.sub(r"_", " ", name) name = re.sub(r" ", " ", name) return name def sanity_check_target_after_processing(target): assert(len(targe...
9845203
from collections import Counter from django.db import models from corehq.apps.app_manager.exceptions import ResourceOverrideError from corehq.apps.app_manager.suite_xml.contributors import PostProcessor from corehq.apps.app_manager.suite_xml.sections.resources import FormResourceContributor from corehq.apps.app_manage...
9845210
import torch.nn as nn import torch import torch.nn.functional as F from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModel import numpy as np def init_weights(m): if isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) nn.init.uniform_(m.bias) class SpanE...
9845215
import numpy as np import torchcrepe ############################################################################### # Test core.py ############################################################################### def test_embed_tiny(audio): """Tests that the embedding is the expected size""" embedding = torc...
9845219
from crosscat.LocalEngine import LocalEngine import crosscat.utils.data_utils as data_utils data_filename = 'T.csv' inference_seed = 0 num_full_transitions = 10 # read the data table into internal json representation data_table, row_metadata, column_metadata, header = \ data_utils.read_data_objects(data_file...
9845317
import pytest from task_processing.interfaces.task_executor import TaskExecutor def test_abstract_interface(): with pytest.raises(TypeError): class TestExecutor(TaskExecutor): pass TestExecutor()
9845333
from __future__ import absolute_import import sys import unittest from testutils import ADMIN_CLIENT, suppress_urllib3_warning from testutils import harbor_server from testutils import TEARDOWN import library.repository import library.docker_api import library.containerd from library.base import _assert_status_code f...
9845363
import argparse import numpy as np import sys def generate(): parser = argparse.ArgumentParser() parser.add_argument('--vocab_file', default='vocab.txt', type=str) parser.add_argument('--vectors_file', default='vectors.txt', type=str) args = parser.parse_args() with open(args.vocab_file, 'r') as f...
9845377
import math def primeFactors(n): pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def numberOfDi...
9845379
import numpy as np import theano import theano.tensor as T from lasagne import nonlinearities from lasagne import init from lasagne.utils import unroll_scan import lasagne.layers as LL import lasagne.updates as LU from lasagne.layers.base import MergeLayer, Layer from lasagne.layers.input import InputLayer from lasagn...
9845413
import multiprocessing def thing(): print "yay!" multiprocessing.Process(target=thing).start()
9845458
import sys import re import db_data as datadb def clean_text(text): text = re.sub(r'(\r|\n)', '', text, flags=re.MULTILINE) text = re.sub(r'((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*', '', text, flags=re.MULTILINE) return text def clean_englishandchar(text): text =...
9845473
from github import Github # your github account credentials username = "username" password = "password" # initialize github object g = Github(username, password) # searching for my repository repo = g.search_repositories("pythoncode tutorials")[0] # create a file and commit n push repo.create_file("test.txt", "commi...
9845475
from django.db import models from django.contrib.auth.models import User class Password(models.Model): """ Represents a username and password together with several other fields """ created_by = models.ForeignKey(User, related_name='+', editable=False) title = models.CharField(max_length=200) u...
9845476
from datasets.PpiAimedDatasetPreprocessed import PpiAimedDatasetPreprocessed from datasets.custom_dataset_factory_base import CustomDatasetFactoryBase from metrics.result_scorer_f1_binary_factory import ResultScorerF1BinaryFactory class PpiAimedDatasetPreprocessedFactory(CustomDatasetFactoryBase): def get_metric...
9845527
from __future__ import print_function from __future__ import division from scitbx.array_family import flex class Optional: def target_gradient(self): """Return a tuple of (target, gradient)""" frac_large = 0.01 return self.finite_difference_gradient(frac_large) def target_gradient_hessian(self): "...
9845543
import pytest from lexsubgen.metrics.candidate_ranking_metrics import gap_score @pytest.fixture def gold_substitutes(): return ["intelligent", "clever", "i-am-mwe", "oov"] @pytest.fixture def gold_weights(): return [3, 2, 1, 1] # @pytest.fixture # def model_prediction(): # return [0.0581, 0.0872, 0.1...
9845585
import os import shutil import sys import tempfile import six import tests base_module_contents = """ import socket import urllib print("base {0} {1}".format(socket, urllib)) """ patching_module_contents = """ from eventlet.green import socket from eventlet.green import urllib from eventlet import patcher print('pa...
9845587
import setuptools requires = [ # asyncio was added to the stdlib in Python v3.4 'asyncio; python_version < "3.4"', 'aiohttp', 'aiodns', 'pandas', 'tqdm', 'requests', ] with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="cmc", version="2.0.3....
9845629
from __future__ import print_function, division, absolute_import import copy import numpy as np import scipy.spatial.distance import six.moves as sm from .. import imgaug as ia from .utils import normalize_shape, project_coords def compute_geometric_median(X, eps=1e-5): """ Estimate the geometric median of...
9845635
from .compat import is_py3, text class Symbol: """Abstract class""" def __init__(self, ticker, name, exchange): self.ticker = ticker self.name = name # <--- may be "None" self.exchange = exchange # <--- may be "None" too for some reason def getType(self): return "Undefined"...
9845642
import pathlib import sys from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool sys.path.append(str(pathlib.Path(__file__).resolve().parents[3])) from app.core.config import DATABASE_URL # isort:skip config = context.config fileConfig(config.config_file_...
9845643
import os from typing import ContextManager, TextIO, cast from ..utils import DummyContext from .base import PipeInput from .vt100 import Vt100Input __all__ = [ "PosixPipeInput", ] class PosixPipeInput(Vt100Input, PipeInput): """ Input that is send through a pipe. This is useful if we want to send t...
9845652
from td.session import TdAmeritradeSession from td.utils.orders import Order class SavedOrders(): """ ## Overview ---- Allows the user to create, delete, and update saved orders associated with their account. """ def __init__(self, session: TdAmeritradeSession) -> None: """Initia...
9845659
import FWCore.ParameterSet.Config as cms from RecoBTag.Skimming.btagMC_QCD_20_50_cfi import * btagMC_QCD_20_50Path = cms.Path(btagMC_QCD_20_50)
9845711
import logging import subprocess def check_name(): logging.info("Check if number of Ready nodes is greater than 5\n") def check(): node_count = subprocess.check_output("oc get nodes | grep Ready | wc -l", shell=True, universal_newlines=True) return True if int(node_count) > 5 else False def main(): ...
9845735
import itertools def get_tables(dynamodb): it = dynamodb.get_paginator("list_tables").paginate() tables = [response["TableNames"] for response in it] tables = itertools.chain(*tables) return tables
9845788
import motmetrics as mm import numpy as np import os import sys def get_gt_pred_pairs(gt_dir, pred_dir, gt_prefix='gt_', pred_prefix='pred_', iou_thresh=0.5): gt_files = os.listdir(gt_dir) pred_files = os.listdir(pred_dir) gt_name_dict = {x[len(gt_prefix):]: x for x in gt_files if x.startswith(gt_prefix)...
9845844
from django.conf.urls import patterns, url from . import api as api urlpatterns = patterns('', url( regex=r'api/bladers/(?P<pk>[0-9]+)/$', view=api.BladerDetailView.as_view(), name='api_bladers_blader_detail', ), url( regex=r'api/bladers/me/$', view=api.BladerCurr...
9845852
DYNACONF_MERGE = True FILES = ["settings.local.py"] PERSON = {"country": "Brasil"} PY_MERGE_LIST = [2] PY_MERGE_DICT = {"b": 2}
9845874
import chainer from chainer import backend from chainer import function_node from chainer.functions.activation import sigmoid from chainer import utils from chainer.utils import type_check class SigmoidCrossEntropy(function_node.FunctionNode): """Sigmoid activation followed by a sigmoid cross entropy loss.""" ...
9845915
import inspect from xv_leak_tools.import_helpers import import_all_from_package, itersubclasses from xv_leak_tools.test_framework.test_case import TestCase from xv_leak_tools.test_documentation.docstring_helpers import trim_docstring class TestDocstringRead: # pylint: disable=too-few-public-methods def __in...
9845945
from guillotina import configure from guillotina.api.service import Service from guillotina.component import get_multi_adapter from guillotina.component import get_utilities_for from guillotina.component import query_utility from guillotina.interfaces import IContainer from guillotina.interfaces import IFactorySerializ...
9845971
import MeCab class Morpheme: def __init__(self, word, poss, base, yomi): """ :param word: 元の単語 :param poss: :param base: 単語の原型 :param yomi: 単語の読み """ self.word = word self.poss = poss self.base = base self.yomi = yomi if se...
9845976
from dataclasses import dataclass import json import warnings import os from transformers import AutoConfig from vila.dataset import preprocessors @dataclass class VILAPreprocessorConfig: agg_level: str = "row" #"block", "sentence" label_all_tokens: bool = False group_bbox_agg: str = "first" added_s...
9846014
import numpy as np from scipy.sparse import diags from scipy.sparse import kron from scipy.sparse import eye from .particle_system import ParticleSystem from ..util.constants import * from abc import abstractmethod class TwoParticles(ParticleSystem): def __init__(self, m = m_e, spin = None): """ ...
9846025
from kubernetes import client from robusta.api import * class VolumeSnapshotParams(ActionParams): """ :var name: name of the PersistentVolumeClaim to backup :var namespace: namespace of the PersistentVolumeClaim to backup :example name: some_pvc_name """ name: str namespace: str = "defaul...
9846088
from math import ceil, log2 class _Signal(): """ Container for signals that can be used to describe connectivity within the design. :param abs_path: Absolute path to the defined signal, this can also only be the name itself, in case it will not be used for a connection vi...
9846101
import os, sys def change(path, text, changed): defs = 0 for dir, dirs, files in os.walk(path): for foundfile in files: content = "" try: with open(os.path.join(dir, foundfile), 'r') as f: content = f.read() #print(content)...
9846103
from tastypie import http from tastypie.authorization import Authorization from tastypie.exceptions import ImmediateHttpResponse class DocumentsAuthorization(Authorization): def is_authorized(self, request, object=None): if request.method == "GET": return True if request.user.is_ano...
9846104
import datetime from subprocess import Popen, PIPE from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.core.exceptions import PermissionDenied from django.contrib import messages from django.conf import settings from django.http import...
9846132
from itertools import count import torch import torch.nn as nn import torch.optim as optim from torchvision import transforms import numpy as np from torch.utils.data import DataLoader from tqdm import tqdm from rotation_network import RotationNetwork from rotation_dataset import RotationDataset import random from PIL ...
9846147
import re def abbreviate(string): output = '{}{}{}'.format result = [] for a in re.split(r'(\W+)', string): length = len(a) result.append(a if length < 4 else output(a[0], length - 2, a[-1])) return ''.join(result) # return ''.join(a if len(a) < 4 else output(a[0], len(a) - 2, a[-...
9846155
import os import torch import numpy as np import scipy.misc as m from tqdm import tqdm from torch.utils import data from PIL import Image from .utils import recursive_glob from augmentations import * from data.base_dataset import BaseDataset import random class Cityscapes_select_loader(BaseDataset): """citysca...
9846170
import flask from gtmcore.logging import LMLogger from gtmcore.auth.user import User from gtmcore.gitlib.git import GitAuthor from lmsrvcore.auth.identity import get_identity_manager_instance def get_logged_in_user() -> User: """A method to get the current logged in User object""" request_scoped_user = flask...
9846171
from os import getenv # Environment variable handling import time # Sleep/time import datetime import requests # For making HTTP requests to Prometheus import kubernetes # For talking to the Kubernetes API from kubernetes.client import ApiException from packaging ...
9846190
from lib import action class VaultIsInitializedAction(action.VaultBaseAction): def run(self): return self.vault.is_initialized()
9846214
from datetime import timedelta, date import mock from django.core import mail from django.db import connection from bluebottle.clients.utils import LocalTenant from bluebottle.deeds.tasks import deed_tasks from bluebottle.deeds.tests.factories import ( DeedFactory, DeedParticipantFactory ) from bluebottle.initiat...
9846242
import pytest from addon_helper import get_version, get_bl_version @pytest.fixture def bpy_module(cache): return cache.get("bpy_module", None) def test_versionID_pass(bpy_module): print(get_bl_version) if (2, 90, 0) == get_bl_version: expect_version = (3, 3, 0) else: expect_version =...
9846259
import paddle import os import sys sys.path.insert(0, os.getcwd()) from ppgan.apps import MPRPredictor import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--output_path", type=str, default='output_dir', ...
9846277
import collections import sys from collections.abc import Set from datetime import datetime, timedelta import regex as re from dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader ...
9846307
import numpy as np def sample_action(policy, state): """ Samples a policy for an action given the current state. """ choices = np.arange(0, policy.shape[1]) probabilities = policy[state] return np.random.choice(choices, p=probabilities) def get_epsilon_greedy_policy(Q, epsilon): num_act...
9846347
import torch import torch.nn as nn import torch.sparse from torch.autograd import Variable import numpy as np import sys from torch.autograd import Function import math import h5py from skimage.transform import resize ############################################################################### # Functions #########...
9846366
import unittest import checksieve class TestCommands(unittest.TestCase): def test_vacation_no_args(self): sieve = ''' require "vacation"; vacation; ''' self.assertTrue(checksieve.parse_string(sieve, True)) def test_vacation_bad_tag(self): sieve = ''' ...
9846413
from mpfmc.tests.MpfMcTestCase import MpfMcTestCase from mpfmc.transitions.push import PushTransition from kivy.uix.screenmanager import WipeTransition, NoTransition class TestTransitions(MpfMcTestCase): def get_machine_path(self): return 'tests/machine_files/transitions' def get_config_file(self): ...
9846452
from django.db import models from .users import User class Alert(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='alerts') target_symbol = models.CharField("Equipment Symbol", max_length=32, blank=False) base_symbol = models.CharField("Equipment Symbol", m...
9846461
import os import sys import inquirer from colorama import Fore, Style from .constants import ProjInfo def print_blue(text): print(Fore.BLUE + text + Style.RESET_ALL) def print_red(text): print(Fore.RED + text + Style.RESET_ALL) def print_yellow(text): print(Fore.YELLOW + text + Style.RESET_ALL) def print_gre...
9846466
import torch from tasks import (get_conv_gn_task, get_fullyconnect_task, get_conv_task) from nngeometry.object.pspace import (PMatDense, PMatDiag, PMatBlockDiag, PMatImplicit, PMatLowRank, PMatQuasiDiag) from nngeometry.generator import Jacobian from utils import check_ratio, check...
9846511
import urllib2 #from google.appengine.api import oauth print "[CreateUser]" print urllib2.urlopen('http://localhost:8888/createuser?id=a&type=b&pref=c&loc=d').read() print "[CreateSystem]" print urllib2.urlopen('http://localhost:8888/createsystem?id=a&holder=b&devices=c&fbps=d&gateways=e&wuclasses=f').read() print ...
9846517
from discord.ext import commands prefix = "?" bot = commands.Bot(command_prefix=prefix) @bot.event async def on_ready(): print("Hello, World!") bot.run(TOKEN)
9846531
from django.contrib import admin from core.notifications.models import Notification admin.site.register(Notification)
9846555
import base64 import hashlib from pathlib import Path from urllib.request import urlretrieve import click from director.context import pass_ctx DEPENDENCIES = [ ( "https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js", "sha256-ngFW3UnAN0Tnm76mDuu7uUtYEcG3G5H1+zioJw3t+68=", None, ),...
9846559
import bpy import os.path import subprocess import pathlib bl_info = { "name": "Trackmania Tools", "description": "Adds unofficial Trackmania 2020 support to Blender.", "author": "<NAME>", "version": (0, 1), "blender": (2, 90, 0), "category": "Import-Export", "location": "File > Export", ...
9846564
import PIL.Image as Image import numpy as np import random def encode(pic_path, text, name): text = " " + text text = list(text) img = Image.open(pic_path) width, height = img.size pixels = width * height if pixels < len(text): print("Encoding not Possible") else: while Tru...
9846569
import dpnp import numpy import pytest from tests.tests_perf.data_generator import * from tests.tests_perf.test_perf_base import DPNPTestPerfBase class TestDPNP(DPNPTestPerfBase): @pytest.mark.parametrize("dtype", [numpy.float64, numpy.float32, numpy.int64, numpy.int32]) @pytest.mark.parametrize("size", [32...
9846572
import tensorflow as tf #import tensorflow.python.ops as ops import numpy as np # The outer function is a constructor to create a loss function using a certain number of classes. class OrdinalCrossEntropy(tf.keras.losses.Loss): def __init__(self, num_classes, importance_weights = Non...
9846624
import subprocess from contextlib import contextmanager from functools import partial, wraps from itertools import product from pathlib import Path from shutil import rmtree from tempfile import mkdtemp import lightgbm as lgb import numpy as np import pytest import statsmodels.api as sm import xgboost as xgb from ligh...
9846638
TRAIN_START_DATE = '2019-01-01' TRAIN_END_DATE = '2019-12-31' TEST_START_DATE = '2020-01-01' TEST_END_DATE = '2020-12-31' TRADE_START_DATE = '2021-01-01' TRADE_END_DATE = '2021-07-31' PATH_OF_DATA = 'data' READ_DATA_FROM_LOCAL = 1 # 0 or 1 TECHNICAL_INDICATORS_LIST = ['macd', 'boll_ub', 'boll_lb', 'rsi_30', 'dx_30...
9846701
import unittest import checksieve class TestFileinto(unittest.TestCase): def test_fileinto_with_flags(self): sieve = ''' require ["fileinto", "imap4flags"]; fileinto :flags "\\\\Seen" "Mailbox"; ''' self.assertFalse(checksieve.parse_string(sieve, False)) def te...
9846720
from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ # API interval. API_INTERVAL_DEFAULT = 30000 # [ms] API_INTERVAL_REFERENCE = 'PAGE_LOCK_API_INTERVAL' API_INTERVAL = getattr( settings, API_INTERVAL_REFERENCE, API_INTERVAL_DEFAULT) #...
9846765
import sys sys.path.insert(0, "../../mxnet/python") import mxnet as mx import numpy as np import basic import data_processing import gen_v3 import gen_v4 # params vgg_params = mx.nd.load("./vgg19.params") style_weight = 1.2 content_weight = 10 dshape = (1, 3, 384, 384) clip_norm = 0.05 * np.prod(dshape) model_prefix...
9846769
import io import sys import time import engineio def test(eio_version, payload): s = engineio.Server() start = time.time() count = 0 s.handle_request({ 'REQUEST_METHOD': 'GET', 'QUERY_STRING': eio_version, }, lambda s, h: None) sid = list(s.sockets.keys())[0] while True: ...
9846780
from django.http import HttpResponse, JsonResponse from ..modelart.customize_service import ObjectDetectionService from django.shortcuts import render detect_service = ObjectDetectionService() def detect(request): if request.method == 'POST': # 获取对象 obj = request.FILES.get('image') data = {obj.n...
9846807
from ._true_measure import TrueMeasure from ..util import TransformError, DimensionError from ..discrete_distribution import DigitalNetB2 from numpy import * from scipy.stats import norm class Uniform(TrueMeasure): """ >>> u = Uniform(DigitalNetB2(2,seed=7),lower_bound=[0,.5],upper_bound=[2,3]) >>> u.gen_...
9846816
from haystack.forms import SearchForm from haystack.query import EmptySearchQuerySet, SearchQuerySet from variant.models import Variant class VariantAutocompleteForm(SearchForm): def no_query_found(self): return EmptySearchQuerySet() def search(self): if not self.is_valid(): retu...
9846852
import torch.nn as nn import torch from utils.math import * import pdb class Policy(nn.Module): def __init__(self, state_dim, action_dim, hidden_size=(100, 100), activation='tanh', log_std=0): super().__init__() self.is_disc_action = False if activation == 'tanh': self.activatio...
9846889
import asyncio import atexit import dataclasses import logging import queue import socketserver import threading import time from collections.abc import Sequence from typing import Any, Callable, Dict, NamedTuple, Optional, Set, Tuple, Union from .captures import Capture, CaptureEntry from .messages import OscBundle, ...
9846982
from samtranslator.metrics.method_decorator import cw_timer from samtranslator.plugins import BasePlugin from samtranslator.swagger.swagger import SwaggerEditor from samtranslator.open_api.open_api import OpenApiEditor from samtranslator.public.sdk.resource import SamResourceType from samtranslator.public.sdk.template ...
9846998
import logging class defer: def __init__(self, *, name='defer'): self.name = name self.tasks = [] def __enter__(self): return self.tasks def __exit__(self, typ, val, tb): for fn in reversed(self.tasks): try: fn() except Exception as...
9847003
import sns def plot_gaussian(ax, data, size=5): ax.set_aspect('equal') ax.set_ylim((-size, size)) ax.set_xlim((-size, size)) ax.tick_params(labelsize=10) sns.kdeplot( data[:, 0], data[:, 1], cmap='Blues', shade=True, shade_lowest=False, ax=ax) ax...
9847012
from rpython.rtyper.lltypesystem import lltype, rffi from hippy import consts from hippy.error import PHPException from hippy.objspace import getspace from hippy.builtin import ( wrap_method, Optional, ThisUnwrapper, StringArg, LongArg, BoolArg, InstanceUnwrapper, handle_as_exception ) from hippy.klass import ...
9847018
import click from app import app from app import db from flask.cli import AppGroup from app.models.user import User user_command = AppGroup("user") @user_command.command("create") @click.argument("username") @click.argument("email") @click.argument("password") def create_user(username, email, password): user = U...
9847055
import datetime import mongomock import pytest from bson import ObjectId from sacredboard.app.data import NotFoundError from sacredboard.app.data.pymongo.genericdao import GenericDAO from sacredboard.app.data.pymongo.metricsdao import MongoMetricsDAO from sacredboard.tests.fixtures.metrics import m1, m2, m3 def mon...
9847117
from typing import Union from inspect import Parameter, Signature from ..primitives import Str, Float, Int, Bool, NoneType from ..array import Array, MaskedArray, Scalar, DType from ..containers import List, Tuple, Slice EMPTY = Parameter.empty VAR_P = Parameter.VAR_POSITIONAL VAR_KW = Parameter.VAR_KEYWORD KW_ONLY ...
9847118
import os import gzip import struct import array import numpy as np import pickle from hypergrad.util import dictslice def datapath(fname): datadir = os.path.expanduser('/home/jie/d2/bitbucket/hypergradient_bo/data/mnist') return os.path.join(datadir, fname) def mnist(): def parse_labels(filename): ...
9847154
import os import contextlib @contextlib.contextmanager def cd(path): '''Creates the path if it doesn't exist''' old_dir = os.getcwd() try: os.makedirs(path) except OSError: pass os.chdir(path) try: yield finally: os.chdir(old_dir)
9847156
from flask import url_for def test_create_error_report(auth_client): # GIVEN an empty database # WHEN we create a number of error reports resp = auth_client.post( url_for('error_report.create_error_report'), json={ 'description': '404 eror found', 'status_code': '40...
9847218
import json import pytest from pathlib import Path from nomenklatura.loader import FileLoader from nomenklatura.index import Index FIXTURES_PATH = Path(__file__).parent.joinpath("fixtures/") @pytest.fixture(scope="module") def donations_path(): return FIXTURES_PATH.joinpath("donations.ijson") @pytest.fixture(...
9847246
import numpy as np import spacy from past.builtins import xrange class EnvTextEncoder: def __init__(self, env, state_word2id): self.word2id = state_word2id self.id2template = env.get_id2template() self.template2id = env.get_template2id() self.id2obj = env.get_id2act_word() ...
9847255
from datetime import datetime from django.core.management.base import BaseCommand from django.db import connections, transaction from django.db.models import Max from usaspending_api.recipient.models import DUNS from usaspending_api.etl.broker_etl_helpers import dictfetchall from usaspending_api.etl.management.load_ba...
9847260
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import ctypes import numpy from nidaqmx._lib import ( lib_importer, wrapped_ndpointer, ctypes_byte_str, c_bool32) from nidaqmx.scale import Scale from nidaqmx.errors...
9847293
import logging import threading import time from brownie import Contract, chain, web3 from brownie.network.event import EventLookupError from eth_abi import encode_single from joblib import Parallel, delayed from yearn.events import decode_logs from yearn.multicall2 import fetch_multicall from yearn.outputs import vic...