id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1686645 | import json
import responses
from pbpstats.data_loader.live.boxscore.file import LiveBoxscoreFileLoader
from pbpstats.data_loader.live.boxscore.loader import LiveBoxscoreLoader
from pbpstats.data_loader.live.boxscore.web import LiveBoxscoreWebLoader
from pbpstats.resources.boxscore.live_boxscore_item import LiveBoxsc... |
1686688 | import pytest
import numpy as np
from astropy.utils.data import download_file
from jdaviz.app import Application
# This file is originally from
# https://data.sdss.org/sas/dr14/manga/spectro/redux/v2_1_2/7495/stack/manga-7495-12704-LOGCUBE.fits.gz
URL = 'https://stsci.box.com/shared/static/28a88k1qfipo4yxc4p4d40v4ax... |
1686700 | from __future__ import division, print_function, absolute_import
# noinspection PyUnresolvedReferences
from six.moves import range
import numpy as np
from scipy.misc import doccer
from ...stats import nonuniform
from ...auxiliary.array import normalize, nunique, accum
__all__ = ['markov']
_doc_default_callparams =... |
1686707 | from typing import Optional
import django_admin_relation_links
from adminutils import options
from authtools import admin as authtools_admin
from django.contrib import admin
from enumfields.admin import EnumFieldListFilter
from rangefilter.filter import DateRangeFilter
from solo.admin import SingletonModelAdmin
from ... |
1686719 | import pomdp_py
class Observation(pomdp_py.Observation):
"""Defines the Observation for the continuous light-dark domain;
Observation space:
:math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is
an estimate of the robot position :math:`g(x_t)\in\Omega`.
"""
# the n... |
1686737 | from .util import is_module_available
__all__ = []
if is_module_available("aspell"):
from .corrector_aspell import AspellChecker
__all__.extend(["AspellChecker"])
if is_module_available("jamspell"):
from .corrector_jamspell import JamspellChecker
__all__.extend(["JamspellChecker"])
|
1686740 | import logging
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from pss_project.api.serializers.rest.OLTPBenchSerializer import OLTPBenchSerializer
from pss_project.api.serializers.database.OLTPBenchResultS... |
1686744 | import time
from busio import I2C
from adafruit_seesaw.seesaw import Seesaw
from adafruit_seesaw.pwmout import PWMOut
from adafruit_motor import motor
import neopixel
import audioio
import audiocore
import board
print("The voyages of the CPX-1701!")
# Create seesaw object
i2c = I2C(board.SCL, board.SDA)
seesaw = Sees... |
1686753 | import datetime
import discord
import logging
from discord.ext import commands
from typing import Union, List
from cogs.utils.db_objects import LogConfig, BoardConfig, SlimEventConfig
log = logging.getLogger(__name__)
class Utils(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._me... |
1686810 | from django.db.models import Q
from django.core.exceptions import ValidationError
from settings.local import people_who_need_to_know_about_failures
from settings.local import inventorys_email
from email.mime.text import MIMEText
import ipaddr
import smtplib
import re
import urllib
# http://dev.mysql.com/doc/refman/... |
1686820 | from __future__ import annotations
from typing import Any, Dict, Optional, Text, Type
import dataclasses
import uuid
from rasa.engine.caching import Cacheable, TrainingCache
from rasa.engine.graph import ExecutionContext, GraphComponent, SchemaNode
from rasa.engine.storage.resource import Resource
from rasa.engine.sto... |
1686841 | from ..model import Model
from . import loadDefaultParams as dp
from . import timeIntegration as ti
class ThalamicMassModel(Model):
"""
Two population thalamic model
Reference:
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., & <NAME>. (2016). A thalamocortical neural mass
model of t... |
1686855 | import json
import uuid
from collections import OrderedDict
from ... import path
from ...iterutils import first
__all__ = ['SlnBuilder', 'SlnElement', 'SlnVariable', 'Solution', 'UuidMap']
class SlnElement:
def __init__(self, name, arg=None, value=None):
if (arg is None) != (value is None):
... |
1686869 | import click
from flask import g
import fastText
from .server import app
@click.command()
@click.argument('model', type=click.Path(exists=True))
def cli(model):
app.config["FT_SERVER_MODEL_PATH"] = model
app.run(host=app.config["HOST"], port=app.config["PORT"], debug=app.config["DEBUG"])
cli() |
1686874 | import json
import pytest
import uuid
from copy import deepcopy
from datetime import datetime, timezone
from time import time
from unittest import TestCase
from ..please_ack_decorator import PleaseAckDecorator
MESSAGE_ID = "abc123"
ON = ("RECEIPT", "OUTCOME")
class TestPleaseAckDecorator(TestCase):
def test_i... |
1686931 | import torch
from torch import nn, Tensor
import math
class LearnedPositionEncoder(nn.Module):
"""
Learned Position Encoder. Takes tensor of positional indicies and converts to learned embeddings
"""
def __init__(self, n_timesteps, d_model):
super().__init__()
self.embeddor = nn.E... |
1686935 | from setuptools import setup
with open('README.md', 'r') as file:
long_description = file.read()
setup(
name='serverlessplus',
packages=['serverlessplus'],
version='0.0.8',
license='Apache-2.0',
author='chenhengqi',
author_email='<EMAIL>',
description='serverless your django/flask apps... |
1686954 | import torch
import torch.nn as nn
import subprocess
import sys
import os
def is_distributed():
return torch.distributed.is_initialized()
def get_world_size():
if not torch.distributed.is_initialized():
return 1
return torch.distributed.get_world_size()
def get_rank():
if not t... |
1686978 | import os
import sys
import math
import pickle
import argparse
import time
from torch import optim
from torch.utils.tensorboard import SummaryWriter
sys.path.append(os.getcwd())
from utils import *
from motion_pred.utils.config import Config
from motion_pred.utils.dataset_h36m import DatasetH36M
from motion_pred.utils... |
1686982 | from colossalai.amp import AMP_TYPE
# ViT Base
BATCH_SIZE = 128
DROP_RATE = 0.1
NUM_EPOCHS = 2
clip_grad_norm = 1.0
|
1686995 | import copy
import os
import random
import numpy as np
import torch
import torch.nn as nn
from torch import fx
from torchvision.models import MNASNet, MobileNetV3, ShuffleNetV2
from torchvision.models.densenet import _DenseLayer
def matches_module_pattern(pattern, node, modules):
if len(node.args) == 0:
... |
1686999 | from river import metrics
__all__ = ["CohenKappa"]
class CohenKappa(metrics.base.MultiClassMetric):
r"""Cohen's Kappa score.
Cohen's Kappa expresses the level of agreement between two annotators on a classification
problem. It is defined as
$$
\kappa = (p_o - p_e) / (1 - p_e)
$$
where ... |
1687022 | import os
import unittest
import site # so that ai4water directory is in path
import sys
ai4_dir = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
site.addsitedir(ai4_dir)
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
from ai4water.datasets import busan_beach, load_nasdaq
from ai4wat... |
1687035 | from pypy.module.pypyjit.test_pypy_c.test_00_model import BaseTestPyPyC
class TestDicts(BaseTestPyPyC):
def test_strdict(self):
def fn(n):
import sys
d = {}
class A(object):
pass
a = A()
a.x = 1
for s in sys.modules.ke... |
1687042 | from core.advbase import *
from slot.a import *
from slot.d import*
def module():
return Summer_Ranzal
class Summer_Ranzal(Adv):
a1 = ('lo',0.4)
a3 = ('primed_defense', 0.08)
conf = {}
conf['slots.a'] = Resounding_Rendition() + Breakfast_at_Valerios()
conf['slots.frostbite.a'] = Primal_Crisis... |
1687105 | import ztom
mongo_rep = ztom.MongoReporter("test", "offline")
mongo_rep.init_db("localhost", 27017, "db_test", "test_collection")
mongo_rep.set_indicator("test_field_int", 1)
mongo_rep.set_indicator("test_field_str", "Hi")
mongo_rep.set_indicator("test_field_dict", {"level1": {"sublevel1": {"key1": "value1", "key1":... |
1687112 | from __future__ import print_function
from tqdm import tqdm
import math
from termcolor import colored
import numpy as np
from openrec.tf1.legacy.utils.evaluators import ImplicitEvalManager
import sys
import json
import pickle
class ImplicitModelTrainer(object):
"""
The ImplicitModelTrainer class implements lo... |
1687120 | import logging
import shutil
from os import path, link
from os.path import normpath
from django.conf import settings
logger = logging.getLogger(__name__)
def data_sample_pre_save(sender, instance, **kwargs):
destination_path = path.join(getattr(settings, 'MEDIA_ROOT'), 'datasamples/{0}'.format(instance.key))
... |
1687155 | from flask import Flask,render_template
from flask_mqtt import Mqtt
import ssl
import urllib.request as request
# import threading
app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = '************-ats.iot.YOUR_REGION.amazonaws.com'
app.config['MQTT_BROKER_PORT'] = 8883
app.config['MQTT_CLIENT_ID'] = "Dum... |
1687165 | import os
import sys
import cv2
import argparse
import glob
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import draw, transform
from scipy.optimize import minimize
from scipy.optimize import least_squares
import objs
import utils
#fp is in cam-ceil normal, height is in ca... |
1687190 | from trackintel.model.util import _copy_docstring
from functools import WRAPPER_ASSIGNMENTS
from trackintel.io.postgis import read_trips_postgis
class Test_copy_docstring:
def test_default(self):
@_copy_docstring(read_trips_postgis)
def bar(b: int) -> int:
"""Old docstring."""
... |
1687191 | import sys
from typing import Tuple, Callable, Any
from protoactor.persistence.messages import Event, Snapshot, RecoverSnapshot, RecoverEvent, PersistedEvent, \
PersistedSnapshot
from protoactor.persistence.providers.abstract_provider import AbstractSnapshotStore, AbstractEventStore
from protoactor.persistence.sna... |
1687208 | from setuptools import setup, find_packages
import medmnist
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
def requirements():
with open('requirements.txt') as f:
required = f.read().splitlines()
return required
setup(
name='medm... |
1687214 | from create_response import response
flag=0
while(flag==0):
user_response = input()
flag=response(user_response)
|
1687288 | from features.numpy_sift import SIFTDescriptor
import numpy as np
import features.feature_utils
from features.DetectorDescriptorTemplate import DetectorAndDescriptor
class np_sift(DetectorAndDescriptor):
def __init__(self, peak_thresh=10.0):
super(
np_sift,
self).__init__(
... |
1687301 | import glob
import logging
import os
import re
import shutil
import subprocess
import tempfile
from boto.s3.key import Key
from boto.s3.connection import S3Connection
"""
The functions below are minimal Python wrappers around Ghostscript, Tika, and
Tesseract. They are intended to simplify converting pdf files into u... |
1687326 | from qgreenland.tasks.common.fetch import FetchDataFiles
from qgreenland.tasks.common.misc import Unrar
from qgreenland.tasks.common.vector import Ogr2OgrVector
from qgreenland.util.luigi import LayerPipeline
class RarredVector(LayerPipeline):
"""Rename files to their final location."""
def requires(self):
... |
1687331 | from collections import defaultdict
import numpy as np
from dateutil import parser
from pandas import DataFrame
from peewee import *
from playhouse.db_url import connect
from config import app_config as cfg
# Connect to the database URL defined in the app_config
db = connect(cfg.database['url'])
def create_database... |
1687412 | from unittest.mock import ANY
import pytest
from rstream import schema
from rstream.client import Client
pytestmark = pytest.mark.asyncio
async def test_peer_properties(no_auth_client: Client) -> None:
result = await no_auth_client.peer_properties()
assert result["product"] == "RabbitMQ"
async def test_c... |
1687417 | from torch.nn import init
def init_net(net, init_type='normal'):
init_weights(net, init_type)
return net
def init_weights(net, init_type='normal', gain=0.02):
def init_func(m):
# this will apply to each layer
classname = m.__class__.__name__
if hasattr(m, 'weight') and (cla... |
1687427 | import os
from collections import defaultdict
"""
Run from actual_data directory to get the average runtimes for each actual data test
"""
files_for_avg = 3
valid_strs = ["data{0}.acp".format(i) for i in range(1, files_for_avg + 1)]
def is_file_path_valid_str(path):
for valid_str in valid_strs:
try:
... |
1687436 | import clr
def process_input(func, input):
if isinstance(input, list): return [func(x) for x in input]
else: return func(input)
def journalContainsAPIErrors(journal):
if journal.__repr__() == 'Journal': return journal.ContainsAPIErrors()
else: return False
OUT = process_input(journalContainsAPIErrors,IN[0]) |
1687441 | import requests
from . import constants, oauth_server
from .bc3_api import _create_session
try:
# noinspection PyCompatibility
from urlparse import urljoin, urlparse, parse_qs
from urllib import quote
except ImportError:
# noinspection PyCompatibility
from urllib.parse import urljoin, urlparse, pars... |
1687467 | import pathlib
import pytest
from opera.parser import tosca
from opera.storage import Storage
class TestNodePolicies:
@pytest.fixture
def service_template(self, tmp_path, yaml_text):
name = pathlib.PurePath("service.yaml")
(tmp_path / name).write_text(yaml_text(
# language=yaml
... |
1687537 | import numpy as np
from numpy.testing import assert_almost_equal
import torch
import torch.nn as nn
from torch.utils import data
import torch.optim as optim
from mbrltools.pytorch_utils import train, predict, _set_device
torch.manual_seed(0)
class MLP(nn.Module):
"""Multi-Layer Perceptron for the sake of testi... |
1687548 | import json
from datetime import datetime, timezone
from typing import Dict, Any, NamedTuple, Optional
from uuid import UUID
import bach
from bach import DataFrame
from sql_models.constants import DBDialect
from sql_models.util import is_postgres, is_bigquery
from sqlalchemy import create_engine
from sqlalchemy.engine... |
1687557 | import torch
import torch.nn
from .base import CplxToCplx, BaseCplxToReal
from ... import cplx
class CplxModReLU(CplxToCplx):
r"""Applies soft thresholding to the complex modulus:
$$
F
\colon \mathbb{C} \to \mathbb{C}
\colon z \mapsto (\lvert z \rvert - \tau)_+
... |
1687561 | from conf import settings
print(settings.MYSQL_HOST) # noqa
print(settings.MYSQL_PASSWD) # noqa
print(settings.EXAMPLE) # noqa
print(settings.current_env) # noqa
print(settings.WORKS) # noqa
assertions = {
"AGE": 15,
"A_DICT": {"NESTED_1": {"NESTED_2": {"NESTED_3": {"NESTED_4": 1}}}},
"BASE_IMAGE":... |
1687631 | from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier
from ..common.data.coco import dataloader
from ..common.models.retinanet import model
from ..common.train import train
import torch
from detectron2.config import LazyCall as L
from detectron2.solver.bu... |
1687634 | from .ge_exception import GeException
class GeNeedsReauthenticationError(GeException):
"""Error raised when the reauthentication is needed"""
pass |
1687647 | from .pipeline import Exec, Serial, Parallel, Node, Notebook, Params
from .glue import lazy_py, main, lazy_shell, Lazy
from .shared.constants import SameContainer, ContainerReuseContext
from .shared.imagepath import Path
from .image import Image, relpath
from .data import pipeline as temp_data, user as perm_data
from .... |
1687704 | from enum import Enum
class Device(Enum):
"""
Enumeration of the devices supported by
Nanograd.
Currently, Nanograd only supports CPU and GPU.
"""
CPU = 1
GPU = 2 |
1687713 | import click
from fabfile import minify, init_database, local_backup
def bake():
"""
Initialize the database from the backup and minify JS files to configure ("cook") the app.
Uses the functions already written in the fabfile.
"""
init_database('bombolone')
minify()
def serve():
"""
S... |
1687716 | import yaml
from samtranslator.yaml_helper import yaml_parse
def load_yaml(file_path):
"""
Loads a yaml file
Parameters
----------
file_path : Path
File path
Returns
-------
Object
Yaml object
"""
with open(file_path) as f:
data = f.read()
return ... |
1687734 | import numpy as np
from typing import Iterable, Tuple
import warnings
try:
from swarmlib.util.problem_base import ProblemBase
from swarmlib.pso.particle import Particle as PSOParticle
using_swarmlib = True
except ImportError:
using_swarmlib = False
# I like to give the little guys a run...but this i... |
1687765 | import rospy
import rosnode
def reset_vision():
# This will kill the realsense node on the NUC and the image pipeline. Both are set in the launch files to auto-restart.
rospy.logerr('Resetting the realsense nodes.')
rosnode.kill_nodes(['/realsense_nodelet_manager', '/acrv_realsense_wrist_ros'])
rospy.s... |
1687790 | from analytics_attributes import AdAnalyticsAttributes, AnalyticsAttributes
from api_object import ApiObject
#
# This module uses Pinterest API v3 and v4 in two classes:
# * Analytics synchronously retrieves user (organic) reports.
# * AdAnalytics synchronously retrieves advertising reports.
#
class Analytics(Analyt... |
1687801 | import click
from crud.cli.utils import CLICK_ENDPOINT, CLICK_MAPPING
@click.command(short_help="Put chained items in endpoint")
@click.argument("dest", type=CLICK_ENDPOINT)
@click.option("-k", "--kwargs", type=CLICK_MAPPING,
help="""kwargs dict as yaml/json format string or @file.yaml, i.e., '{"level":... |
1687830 | from snet.sdk.payment_strategies.payment_staregy import PaymentStrategy
class PrePaidPaymentStrategy(PaymentStrategy):
def __init__(self, concurrency_manager, block_offset=240, call_allowance=1):
self.concurrency_manager = concurrency_manager
self.block_offset = block_offset
self.call_all... |
1687878 | import pdb
import z3
import helpers.vcommon as CM
import settings
from data.inv.base import Inv
import data.inv.invs
dbg = pdb.set_trace
mlog = CM.getLogger(__name__, settings.LOGGER_LEVEL)
class PrePost(Inv):
"""
Set of Preconds -> PostInv
"""
def __init__(self, preconds, postcond, stat=None):
... |
1687882 | from dataclasses import dataclass
import multiprocessing
from io import StringIO
from unittest import mock
from typing import List
from pytest_cov.embed import cleanup_on_sigterm
import pytest
from outrun.rpc import Client, Encoding, InvalidTokenError, Server
def start_server_process(server: Server) -> multiprocess... |
1687892 | from maya.api import OpenMaya
__all__ = [
"average_vector",
"smooth_vectors"
]
def average_vector(vectors):
"""
Get the average vector of the all of the provided vectors. All vectors
will be added up and divided by the number of the provided vectors.
:param list[OpenMaya.MVector] vectors:
... |
1687897 | from __future__ import print_function
import importlib, inspect, os, sys
import numpy as np
from sklearn.datasets import make_classification, make_regression
from sklearn.metrics import accuracy_score, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
import h2o
... |
1687915 | from __future__ import unicode_literals
import datetime
from sqlalchemy import engine_from_config
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
from billy.db import tables
def setup_database(global_config, **settings):
""... |
1687934 | from oogway.request import request_payment, parse_request
from oogway.validate import validate
REQ1_RES = "bitcoin:1FHXDkRLhoCziRjftaPB3fELUYrZomFanx?amount=0.00020000&time=1598319207&exp=3600&message=oogway%20requests"
REQ2_RES = "bitcoin:1FHXDkRLhoCziRjftaPB3fELUYrZomFanx?amount=0.00020000&time=1598319712"
def tes... |
1687950 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tarfile
import cv2
import copy
import numpy as np
import tensorflow as tf
from utils.curve import points_to_heatmap_rectangle_68pt
from six.moves import xrange
from six.moves import... |
1687953 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from fontTools.misc.textTools import safeEval
from itertools import *
from functools import partial
from . import DefaultTable
from . import grUtils
import struct, operator, warnings
G... |
1687974 | import unittest
import groundstation.objects.object_factory as object_factory
from groundstation.objects.root_object import RootObject
from groundstation.objects.update_object import UpdateObject
class TestRootObject(unittest.TestCase):
def test_hydrate_root_object(self):
root = RootObject(
... |
1688012 | import time
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import service
from oslo_service import wsgi
from bm_instance_agent.api import app
from bm_instance_agent.conf import CONF
from bm_instance_agent import exception
LOG = logging.getLogger(__name__)
def parse_args(argv, de... |
1688037 | from panda3d.core import NodePath
from panda3d.core import Point3
from libpandadna import DNAStorage
from libpandadna import DNAVisGroup
from libpandadna import DNASuitPoint
from panda3d.core import loadPrcFileData
loadPrcFileData('', 'window-type none')
from direct.showbase.ShowBase import ShowBase
base = ShowBase()... |
1688040 | from IPython.display import display
from .odysis import (
Scene, DataBlock,
Warp,
ColorMapping, Grid,
VectorField, PointCloud,
Clip, Slice,
Threshold, IsoSurface
)
_current_scene = None
_current_datablock = None
def scene(mesh):
global _current_scene
global _current_datablock
_... |
1688051 | import sys
import os
import platform
import numpy as np
import matplotlib.pyplot as plt
import flopy
#Set name of MODFLOW exe
# assumes executable is in users path statement
version = 'mf2005'
exe_name = 'mf2005'
if platform.system() == 'Windows':
exe_name = 'mf2005.exe'
mfexe = exe_name
#Set the paths
loadpth ... |
1688074 | from __future__ import annotations
from hist import Hist, Stack, axis
def test_1D_empty_repr(named_hist):
h = named_hist.new.Reg(10, -1, 1, name="x", label="y").Double()
html = h._repr_html_()
assert html
assert "name='x'" in repr(h)
assert "label='y'" in repr(h)
def test_1D_var_empty_repr(nam... |
1688096 | from setuptools import setup, find_packages
import os
version = '4.0.1'
install_requires = [
'setuptools',
'requests',
'APScheduler',
'iso8601',
'python-dateutil',
'Flask',
'Flask-Redis',
'WSGIProxy2',
'gevent',
'sse',
'flask_oauthlib',
'PyYAML',
'request_id_middlewa... |
1688109 | from pprint import pprint
from pymldb import Connection
import rec.settings as _
def run_test_pipeline(mldb):
mldb.datasets(_.TEST_DATASET).delete()
mldb.procedures(_.DATASET_MANAGER_TEST).runs.post_json({})
print('nb test examples', mldb.datasets(_.TEST_DATASET)
.get()['status']['rowCount'])
... |
1688145 | import cocotb
import pyuvm.utility_classes as utility_classes
from pyuvm import *
import inspect
phase_list = {}
class my_comp(uvm_component):
def log_phase(self):
"""
Log this function to the phase list
"""
comp_name = self.get_name()
function_name =... |
1688160 | import logging
import os
import os.path
import galaxy.tools.parameters.basic
import galaxy.tools.parameters.grouping
from galaxy.tool_util.verify.interactor import ToolTestDescription
from galaxy.util import (
string_as_bool,
string_as_bool_or_none,
unicodify,
)
try:
from nose.tools import nottest
ex... |
1688182 | import torch
import torch.nn as nn
import torch.nn.functional as F
from cogkge.models.basemodel import BaseModel
class Rescal(BaseModel):
def __init__(self,
entity_dict_len,
relation_dict_len,
embedding_dim,
penalty_weight=0.0):
super().... |
1688201 | def dummy(): pass
function = type(dummy)
class Dummy:
def dummy(self): pass
classobj = type(Dummy)
instancemethod = type(Dummy().dummy)
NoneType = type(None)
str = str
ref = 'RPYJSON:null:RPYJSON'
int = int
float = float
bool = bool
dict = dict
list = list
tuple = tuple
|
1688257 | import os
import tensorflow as tf
slim = tf.contrib.slim
def load_checkpoints(checkpoint_dir, saver):
# Load latest checkpoint if available
all_checkpoint_states = tf.train.get_checkpoint_state(
checkpoint_dir)
if all_checkpoint_states is not None:
all_checkpoint_paths = \
al... |
1688274 | import tweepy
import os
import sys
import random
import logging
from multiprocessing import Queue, Process
"""
Retrieves a sample dataset of pre-2013 Twitter users
"""
DEFAULT_PERCENTAGE = 100
DEFAULT_MIN_ID = 0
DEFAULT_MAX_ID = 5000000000
logger = logging.getLogger(__name__)
def fetch_accounts(api,
... |
1688314 | from .base import Variable
import itertools
class InteractionType(Variable):
type = "Interaction"
def __init__(self, definition):
self.interactions = definition["interaction variables"]
self.name = "(Interaction: %s)" % str(self.interactions)
self.interaction_fields = self.interacti... |
1688325 | from azureml.core import Run
from mlapp.main import MLApp
from mlapp.handlers.wrappers.file_storage_wrapper import file_storage_instance
from mlapp.integrations.aml.utils.run_class import load_config_from_string, tag_and_log_run, tag_and_log_outputs
import argparse
from config import settings
from mlapp.managers.flow_... |
1688348 | from datetime import datetime
from app import DATETIME_FORMAT
from tests.app.db import (
create_api_key,
create_service,
create_notification,
create_template
)
from app.models import (
KEY_TYPE_NORMAL,
)
def test_get_api_key_stats_with_sends(admin_request, notify_db, notify_db_session):
ser... |
1688366 | from concurrent.futures import ThreadPoolExecutor, wait
import traceback
import os
import sys
import time
nworkers = int(sys.argv[1])
n = 40000
nruns = 11
import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg as sla
from test_data import discrete_laplacian
base_array = discrete_laplacian(n)
... |
1688370 | import time
from functools import wraps
import requests
from enum import IntEnum
try:
import gevent
do_sleep = gevent.sleep
except ImportError:
do_sleep = time.sleep
from pyVmomi import vim, Version as pyVmomi_version
from pyVim.connect import SmartConnect
import logging
from requests.exceptions import ... |
1688460 | import sys
import cftime
import numpy as np
import pandas as pd
import pytest
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import anomaly, climatology, month_to_season, calendar_average, climatology... |
1688494 | import unittest
from scenario_test_support import *
class S08AutoValueTest(unittest.TestCase):
archive = load_archive("08_auto_value/intellij_files")
compiler_xml_content = archive["08_auto_value/.idea/compiler.xml"]
def test_source_folders(self):
self.assertEqual([
"foo_profile", "m... |
1688497 | from bluedot import BlueDot, COLORS
from signal import pause
from random import choice
bd = BlueDot()
bd.resize(1,2)
def pressed(pos):
print("Pressed : {}".format(pos))
def moved(pos):
print("Moved : {}".format(pos))
def released(pos):
print("Released : {}".format(pos))
... |
1688518 | import os
import numpy as np
import scipy.signal
import torch
from matplotlib import pyplot as plt
def triplet_loss(alpha = 0.2):
def _triplet_loss(y_pred,Batch_size):
anchor, positive, negative = y_pred[:int(Batch_size)], y_pred[int(Batch_size):int(2*Batch_size)], y_pred[int(2*Batch_size):]
... |
1688535 | import logging
from assigner.config import requires_config
help = "Set configuration values"
logger = logging.getLogger(__name__)
@requires_config
def set_conf(conf, args):
"""Sets <key> to <value> in the config.
"""
conf[args.key] = args.value
def setup_parser(parser):
parser.add_argument("key"... |
1688556 | import torch.nn as nn
from HeadNeRFOptions import BaseOptions
from RenderUtils import ExtractLandMarkPosition, SoftSimpleShader
import torch
import torch.nn.functional as F
import FaceModels
from pytorch3d.structures import Meshes
from pytorch3d.renderer import (
PerspectiveCameras, RasterizationSettings, Textures... |
1688580 | class DataLinkError(RuntimeError):
GENERIC_ERROR_MESSAGE = 'Something went wrong. Please try again. \
If you continue to have problems, please contact us at <EMAIL>.'
def __init__(self, data_link_message=None, http_status=None, http_body=None, http_headers=None,
data_link_error_code=None, resp... |
1688591 | import os
import yaml
from sqlalchemy.orm.collections import attribute_mapped_collection
from emonitor.extensions import db
class Department(db.Model):
"""Department class"""
__tablename__ = 'departments'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
name... |
1688632 | from __future__ import absolute_import, division, print_function
# LIBTBX_SET_DISPATCHER_NAME phenix.rotalyze
# LIBTBX_SET_DISPATCHER_NAME molprobity.rotalyze
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1
import sys
from iotbx.cli_parser import CCTBXParser
from libtbx.utils import multi_out, show... |
1688719 | import argparse
import numpy as np
from os import path
import struct
from internal import db_handling
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--sift_feature_dir', required=True)
parser.add_argument('--query_txt_file', required=True)
parser.add_argument('--database_f... |
1688732 | import json
import logging
import os
from xia2.Driver.DriverFactory import DriverFactory
from xia2.Handlers.Phil import PhilIndex
logger = logging.getLogger("xia2.Wrappers.Dials.Scale")
def DialsScale(DriverType=None, decay_correction=None):
"""A factory for DialsScaleWrapper classes."""
DriverInstance = D... |
1688736 | from typing import TYPE_CHECKING
from protostar.commands.test.test_cases import TestCaseResult
if TYPE_CHECKING:
import queue
class TestResultsQueue:
def __init__(self, shared_queue: "queue.Queue[TestCaseResult]") -> None:
self._shared_queue = shared_queue
def get(self) -> TestCaseResult:
... |
1688738 | import sys
import bteve as eve
import random
import minpng
if sys.implementation.name == "circuitpython":
gd = eve.Gameduino()
else:
from spidriver import SPIDriver
gd = eve.Gameduino(SPIDriver(sys.argv[1]))
gd.init()
if 0:
gd.ClearColorRGB(0x20, 0x40, 0x20)
gd.Clear()
gd.cmd_text(gd.w // 2, ... |
1688764 | try:
# python2
from urlparse import urlparse
except Exception:
# python3
from urllib.parse import urlparse
from consolemenu.validators.base import BaseValidator
class UrlValidator(BaseValidator):
def __init__(self):
"""
URL Validator class
"""
super(UrlValidator, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.