id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3392173 | from .abstract_command import AbstractCommand
from ..services.config_handler import ConfigHandler
from ..services.console_logger import ColorPrint
from ..services.state import StateHolder
from ..services.state_utils import StateUtils
class RepoBranch(AbstractCommand):
sub_command = "repo"
command = "branch"
... |
3392192 | import json
from .traversable import Traversable
def load(*args, **kwargs):
j = json.load(*args, **kwargs)
return Traversable(j)
def loads(*args, **kwargs):
j = json.loads(*args, **kwargs)
return Traversable(j)
def dump(obj, *args, **kwargs):
if isinstance(obj, Traversable):
obj = obj... |
3392199 | import numpy as np
from numpy.lib.utils import source
import pandas as pd
import torch
import librosa
import soundfile
from utils import check_type, extract_audio, mono_load
from config import InferenceConfig as IC
from csrc.configurations import DatasetConfig as DC
from csrc.configurations import ModelConfig as MC
f... |
3392205 | class Solution:
# K: 鸡蛋数目
# N: 楼层数
# dp(K, N)
# dp(K, N) = 1 + min[0<=i<=N]( max(dp(K, N-i), dp(K-1, i-1)) )
# 会超出时间限制
def superEggDrop(self, K: int, N: int) -> int:
m = {}
def dfs(K, N):
if K == 1: return N
if N == 0: return 0
if (K, N) in m: return m[(K, N)]
result = float(... |
3392224 | from django.utils.translation import gettext_lazy as _
import logging
from smsapi.client import SmsApiPlClient
from smsapi.exception import SmsApiException
from trench.backends.base import AbstractMessageDispatcher
from trench.responses import (
DispatchResponse,
FailedDispatchResponse,
SuccessfulDispatch... |
3392226 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
cache = dict()
def load_wordnet(directory=None, recache=False):
"""Load the wordnet graph and wordnet categories used in [Huth et al 2012].
Parameters
----------
directory : str or None
Direc... |
3392234 | import os
import json
from hotbox_designer.reader import HotboxWidget
from hotbox_designer.data import load_templates, load_json
from hotbox_designer.manager import (
launch_manager, initialize, show, hide, switch, load_hotboxes) |
3392258 | import os
import shutil
import urllib.request
def init_counter(path_to_count_content):
if not os.path.exists(path_to_count_content):
return 0
else:
already_existing_no_of_files = len(os.listdir(path_to_count_content))
print("Already downloaded files: ", already_existing_no_of_files)
... |
3392281 | import torch
from torch.nn import functional as F
from malib.algorithm.common import misc
from malib.utils.typing import Dict, Any
from malib.algorithm.common.loss_func import LossFunc
from malib.backend.datapool.offline_dataset_server import Episode
from malib.algorithm.dqn.policy import DQN
class QMIXLoss(LossFun... |
3392434 | from vit.formatter import Number
class Urgency(Number):
def format(self, urgency, task):
return "{0:.2f}".format(urgency)
|
3392454 | import z5py
from copy import deepcopy
import nifty.tools as nt
from concurrent import futures
def extract_boundaries(path, in_key, out_key):
with z5py.File(path) as f:
ds_in = f[in_key]
shape = ds_in.shape[1:]
chunks = ds_in.chunks[1:]
blocks = deepcopy(chunks)
chunks = tup... |
3392485 | from typing import List, Union
import torch
from numpy import ndarray
from torch import LongTensor, Tensor, nn
from ..lib import mpi
from ..prelude import ArrayLike, Self
class Device:
"""Utilities for handling devices"""
def __init__(self, use_cpu: bool = False, gpu_indices: List[int] = []) -> None:
... |
3392507 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import random
import numpy as np
import sys
from collections import deque
class UCBDrAC():
"""
Upper Confidence Bound Data-regularized Actor-Critic (UCB-DrAC) object
"""
def __init__(self,
... |
3392519 | from utils.rnn import rnn_utils
from utils.bert import bert_utils
import tensorflow as tf
import numpy as np
class RNN(object):
"""
default scope: bert
"""
def __init__(self, config, *args, **kargs):
self.config = copy.deepcopy(config)
tf.logging.info(" begin to build {}".format(self.config.get("scope", "bert... |
3392547 | import unittest
from katas.kyu_8.leonardo_dicaprio_and_oscars import leo
class LeonardoTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(leo(88), 'Leo finally won the oscar! Leo is happy')
def test_equals_2(self):
self.assertEqual(leo(86), 'Not even for Wolf of wallstreet?... |
3392555 | from pyNastran.op2.dev.op2 import OP2
import struct
import numpy as np
model = OP2(r'example.op2')
print(model._postheaderpos)
directory = model.directory()
for key, data in directory.items():
print(key, data)
dbnames = model.dbnames
table_ids = dbnames.keys()
dtype = np.dtype([
('EKEY', np.int32),
... |
3392564 | from unittest import TestCase
from semanticpy.transform.tfidf import TFIDF
from nose.tools import *
import numpy
class TFIDFTest(TestCase):
""" """
EPSILON = 4.90815310617e-09
@classmethod
def same(self, matrix1, matrix2):
difference = matrix1 - matrix2
max = numpy.max(difference)
... |
3392651 | import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from IPython import embed
import os
from torch.utils.data.sampler import SubsetRandomSampler
def get(batch_size, data_root='./data/', train=True, val=True, num_samples=500, validation=0, data_augment=1, **kwargs):
dat... |
3392653 | import os
import random
import subprocess
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from dja... |
3392715 | import os
import json
import discord
from discord.ext import commands
import subprocess
import app.data.firestore as data
import app.data.static as static
import app.periods.voting as voting
import app.periods.results as results
import app.periods.submissions as submissions
import app.data.leaderboard as lead... |
3392773 | import json
import unittest
from parameterized import parameterized
from repro.models.liu2019 import BertSumExt, BertSumExtAbs, TransformerAbs
from repro.testing import get_testing_device_parameters
from . import FIXTURES_ROOT
class TestLiu2019Models(unittest.TestCase):
def setUp(self) -> None:
# The e... |
3392817 | from tstree import *
def test_TSTree_get_set():
urls = TSTree()
urls.set("/apple/", "Apple")
urls.set("/grape/", "Grape")
urls.set("/kiwi/", "Kiwi")
urls.set("/kumquat/", "Kumquat")
urls.set("/pineapple/", "Pineapple")
assert urls.get("/apple/") == "Apple"
assert urls.get("/grape/") =... |
3392827 | from flask import Flask, render_template, send_from_directory
from flask import jsonify
from flask_socketio import SocketIO, emit
import threading
app = Flask(__name__, static_url_path='')
global socketio, activations_per_state, properties
socketio = SocketIO(app)
@app.route('/scripts/<path:path>')
def send_js(path)... |
3392836 | import yaml
import pytest
from salteventsd.loader import SaltEventsdLoader
from testfixtures import compare
def _build_data(data, tmpdir):
"""
Helper method to create a dummy config file
"""
f = tmpdir.join("custom_eventsd")
f.write(yaml.dump(data))
return f
def test_custom_config_file_load(... |
3392844 | from metaflow import FlowSpec, step
class CounterBranchHelperFlow(FlowSpec):
@step
def start(self):
self.creature = "dog"
self.count = 0
self.next(self.add_one, self.add_two)
@step
def add_one(self):
self.increment = 1
self.count += self.increment
... |
3392849 | import json
import nltk
class SimpleReaderARC_Question_Choice():
"""
Reader for ARC QA dataset:
{"id":"MCAS_2000_4_6",
"question":{"stem":"Which technology was developed most recently?",
"choices":[
{"text":"cellular telephone","label":"A"},
{"text":"te... |
3392899 | import click
import os
import os.path
import sys
import shutil
import yaml
import random
import string
import itertools
import time
import pysam
from pkg_resources import get_distribution
from subprocess import call, check_call
from .bapHelp import *
from .bap1ProjectClass import *
from ruamel import yaml
from ruamel.... |
3392945 | import argparse
import time
import gc
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from models.models import GroupIM
from utils.user_utils import TrainUserDataset, EvalUserDataset
from utils.group_utils import TrainGroupDataset, EvalGroupDataset
from eval.evaluate import evaluate_u... |
3392977 | from collections import OrderedDict
import pandas as pd
from tests import project_test, generate_random_tickers, generate_random_dates, assert_output
@project_test
def test_date_top_industries(fn):
tickers = generate_random_tickers(10)
dates = generate_random_dates(2)
fn_inputs = {
'prices': pd.D... |
3393009 | import numpy as np
from scipy import linalg as ln
def chained_integrator_dynamics(dt=0.1, n=2, decay=1, amplification = 1, fullB=False):
''' forward euler discretization of
dx_i/dt = x_{i+1}; dx_n/dt = u
with added decay of states or amplification
of integration terms '''
if hasattr(dec... |
3393122 | from .sources import (RecordsSource, SupportsMoveToRecordsDirectory,
SupportsToFileobjsSource,
FileobjsSource, SupportsToDataframesSource)
from .targets.base import (RecordsTarget, SupportsMoveFromRecordsDirectory,
MightSupportMoveFromTempLocAfterFi... |
3393136 | from typing import Any, Dict, List
from botocore.exceptions import ClientError
from chaoslib.exceptions import ActivityFailed
from chaoslib.types import Configuration, Secrets
from chaosaws import aws_client
from chaosaws.types import AWSResponse
__all__ = ["create_document", "send_command", "delete_document"]
def... |
3393150 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attachments', '0004_db_index'),
]
operations = [
migrations.AlterField(
model_name='attachment',
name='object_id',
field=models.CharField(db_index=True, ... |
3393158 | import os, sys
import glob
import math
import time
import numpy as np
import torch
class IamondbData(object):
def __init__(self, data, bsz, device='cpu', Xmean=None, Xstd=None):
"""
data -- list[Tensor] -- there is no order among the Tensors
"""
self.bsz = bsz
data_ne... |
3393178 | from matplotlib.backends.backend_qt5 import SubplotToolQt, UiSubplotTool
from matplotlib.backends.qt_compat import QtCore, QtWidgets
class CustomUiSubplotTool(UiSubplotTool):
def __init__(self, *args, **kwargs):
super(UiSubplotTool, self).__init__(*args, **kwargs)
self.setObjectName('SubplotTool')
... |
3393276 | from unittest import TestCase
from scrapy.http import HtmlResponse, Request
from slybot.spidermanager import SlybotSpiderManager
from .utils import open_spider_page_and_results, PATH
class SpiderTest(TestCase):
smanager = SlybotSpiderManager("%s/data/SampleProject" % PATH)
def test_spider_with_selectors(sel... |
3393313 | import dataclasses
from koala.typing import *
from koala.message.base import JsonMessage
@dataclasses.dataclass
class RpcMessage:
meta: JsonMessage
body: bytes = b""
@classmethod
def from_msg(cls, meta: JsonMessage, body: bytes = b"") -> 'RpcMessage':
msg = RpcMessage(meta=meta, body=body)
... |
3393348 | text = input('enter any text: ')
def translate(line):
result=[]
for x in line.lower():
if x in ['a','e','i','o','u']:
result.append(x)
else:
result.append(x)
result.append('o')
result.append(x)
return result
print("".join(translate(text))) |
3393367 | from datetime import datetime
import protocol
from threading import Event
from collections import namedtuple
from lifx.color import modify_color
import color
import time
DEFAULT_DURATION = 200
DEFAULT_TIMEOUT = 2.0
DEFAULT_RETRANSMITS = 10
StatsTuple = namedtuple('StatsTuple', ['dropped_packets', 'sent_packets'])
cl... |
3393391 | import torch.nn as nn
import torch.nn.functional as F
class SimpleNN(nn.Module):
"""
Simple neural network aims to add non-linearity to feature->reward mapping
No spatial learning involved
"""
def __init__(self, input_size, hidden_size=10):
super(SimpleNN, self).__init__()
self.bl... |
3393435 | from bitmovin_api_sdk.encoding.manifests.smooth.smooth_api import SmoothApi
from bitmovin_api_sdk.encoding.manifests.smooth.default.default_api import DefaultApi
from bitmovin_api_sdk.encoding.manifests.smooth.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.manifests.smooth.representations... |
3393477 | from . import affine_transformation
from . import epa
from . import images
from . import orientation
from . import rofl
__all__ = [
'affine_transformation',
'epa',
'images',
'orientation',
'rofl',
]
|
3393499 | import time
from helpers import utils
import socket
import threading
tcp_port = 53007
ws_port = 53008
sock = socket.socket()
sock.bind(("0.0.0.0", tcp_port))
sock.listen(1)
def actual_parrot(sock):
try:
buf = b"Hi to the friendly perrot.\n"
sock.send(buf)
while len(buf) > 0:
... |
3393512 | import numpy as np
from scipy import linalg
from ..processing import knee
import warnings
warnings.filterwarnings("ignore")
def wgr_regress(y, X):
n, ncolX = X.shape
Q,R,perm = linalg.qr(X, mode='economic', pivoting=True)
if R.ndim == 0:
p = 0
elif R.ndim == 1:
p = int(abs(R[0])... |
3393518 | import numpy as np
from scipy.ndimage import gaussian_filter
import sys
from scipy.spatial import Delaunay
import os
import subprocess
#from matplotlib import image as mpimg
from PIL import Image, ImageDraw
import shutil
GAUSS = 2
OUTDIR = 'dm/temp/'
PERSISTENCE_THRESHOLD = 512
l = 512
w = 512
def... |
3393533 | from unittest.mock import Mock, call
import pytest
from markovchain.storage.base import Storage
class StorageTest(Storage):
def replace_state_separator(self, old_separator, new_separator):
pass
def get_dataset(self, key, create=False):
pass
def add_links(self, links, dataset_prefix=''):
... |
3393541 | import numpy as np
def errorcheck(transcount: np.ndarray, statetime: np.ndarray,
toltime: float) -> bool:
# check transitions counting went wrong
if np.any(np.diag(transcount) != 0):
raise Exception(
("Transition Count Matrix have diagonal "
"elements 'm[i,i] !=... |
3393550 | class Solution(object):
def removeDuplicates(self, nums):
if len(nums) <= 1:
return len(nums)
slow = 0
for i in range(1, len(nums)):
if nums[i] != nums[slow]:
slow += 1
nums[slow] = nums[i]
return slow + 1 |
3393556 | import attrdict
import model_hub.huggingface as hf
def test_config_parser() -> None:
args = {"pretrained_model_name_or_path": "xnli", "num_labels": 4}
config = hf.parse_dict_to_dataclasses((hf.ConfigKwargs,), args, as_dict=True)[0]
target = attrdict.AttrDict(
{
"pretrained_model_name_... |
3393578 | import os
from typing import List
import numpy as np
import torch
import pytest
from persia.helper import ensure_persia_service
from persia.ctx import BaseCtx, DataCtx
from .utils import random_port
EMBEDDING_CONFIG = {"slots_config": {"age": {"dim": 8}}}
RAW_EMBEDDING_CONFIG = {
"slots_config": {
"use... |
3393619 | import os
import string
def get_test_resource(path: str) -> str:
return os.path.join(os.path.dirname(__file__), 'resources', path)
def cmp_str_lines(s1: str, s2: str) -> bool:
s1l, s2l = s1.strip().splitlines(), s2.strip().splitlines()
if len(s1l) != len(s2l):
return False
for l1, l2 in zip(... |
3393622 | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['file_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexObjectTyp... |
3393645 | import discord
from discord.ext import commands
class VoiceLogging(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
async with self.bot.db.execute("SELECT channel_id, delete_after FROM voice_loggi... |
3393689 | from ctypes import cdll
import ctypes
lib = cdll.LoadLibrary('./cpp/libsolvers.so')
lib.solve_list_sort.restype = ctypes.c_uint64
lib.solve_shortest_path.restype = ctypes.c_uint64
lib.unit_test()
def solve_sorted_list(target_prefix, previous_hash, nb_elements):
try:
return lib.solve_list_sort(target_prefi... |
3393697 | from gui.textutil import default_font
from gui.skin.skinparse import makeFont
from util import try_this
from gui.uberwidgets.formattedinput2.formattedinput import FormattedInput
import wx
from gui.uberwidgets.formattedinput2.fontutil import StyleToDict, TupleToFont
from common import setpref, pref
from trace... |
3393700 | import asyncio
import base64
import binascii
import gc
import re
import time
from aiohttp import web
import json
from jsonrpcserver.aio import methods
from jsonrpcserver import config, status
from jsonrpcserver.exceptions import JsonRpcServerError
from spruned.application import exceptions
from spruned.application.e... |
3393729 | import itertools
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
class DeepMutualLoss(nn.Module):
def __init__(self, base_criterion, w, temperature=1.0):
super().__init__()
self.base_criterion = base_crit... |
3393747 | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import pytorch_lightning as pl
from pytorch_lightning.metrics.functional import accuracy
def get_cifar_dloaders(batch_size=64, size=32, path='../data/cifar10_data', num_workers=20):
batch_size=ba... |
3393766 | from typing import Dict, List, Tuple
import numpy as np
import pandas as pd
from tqdm import tqdm
from data.dataset import train, test, books
def baseline_model() -> Tuple[Dict[int, List], Dict[int, List]]:
global train, test
sol = test.groupby(["user_id"])["book_id"].agg({"unique"}).reset_index()
gt = ... |
3393878 | import importlib
import pyspark.pandas as ps
from pyspark.sql import SparkSession
from hamilton import base
from hamilton import driver
from hamilton import log_setup
from hamilton.experimental import h_spark
if __name__ == '__main__':
log_setup.setup_logging(log_level=log_setup.LOG_LEVELS['INFO'])
spark = ... |
3393885 | from setuptools import setup
version = "1.0.6"
setup(
name="zhixuewang",
version=version,
keywords=["智学网", "zhixue", "zhixuewang"],
description="智学网的api",
license="MIT",
author="anwenhu",
author_email="<EMAIL>",
packages=["zhixuewang", "zhixuewang.student", "zhixuewang.te... |
3393906 | from aif360.detectors.mdss.ScoringFunctions.ScoringFunction import ScoringFunction
from aif360.detectors.mdss.generator import get_entire_subset, get_random_subset
from aif360.detectors.mdss.ScoringFunctions import (
Bernoulli,
BerkJones,
Gaussian,
ScoringFunction,
Poisson,
)
import pandas as pd
... |
3393920 | from L1TriggerConfig.DTTrackFinder.L1MuDTTFMasksOnline_cfi import *
from L1TriggerConfig.RCTConfigProducers.L1RCTChannelMaskOnline_cfi import *
from L1TriggerConfig.GctConfigProducers.L1GctChannelMaskOnline_cfi import *
from L1TriggerConfig.GMTConfigProducers.L1MuGMTChannelMaskConfigOnline_cfi import *
from L1TriggerCo... |
3393937 | TAGS = (
'KICK', 'SNAR', 'DEEP', 'BRAS', 'STRI', 'PERC', 'HHAT', 'CYMB', 'EVOL', 'EXPR',
'BASS', 'LEAD', 'PAD', 'TXTR', 'CRD', 'SFX', 'ARP', 'METL', 'ACOU', 'ATMO',
'NOIS', 'GLCH', 'HARD', 'SOFT', 'DARK', 'BRGT', 'UNTG', 'EPIC', 'FAIL', 'LOOP',
'MINE', 'FAV'
)
TAG_LOOK = {
... |
3393943 | import os
import stat
import hashlib
import shutil
from confiture.schema.containers import Value
from confiture.schema.types import Path
from marty.remotemethods import DefaultRemoteMethodSchema, RemoteMethod, RemoteOperationError
from marty.datastructures import Tree, Blob
class LocalRemoteMethodSchema(DefaultRemo... |
3393950 | def neighbours(r, c, R, C):
for rows, cols in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
if 0 <= rows < R and 0 <= cols < C:
yield rows, cols
# Another way to write directions is:
i, j = 0, 0 # Assuming this is the start position
dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
for x, y in di... |
3394009 | from distutils.core import setup
setup(
name='RFHO',
version='0.2',
packages=['rfho', 'rfho.examples'],
# TODO have to decide what to do with things in examples. examples.common is a useful
# class but maybe its misplaced.
url='',
license='',
author='<NAME>',
author_email='<EMAIL>',... |
3394072 | from ..utils.python import resolve_underlying_function
_SLASH_REQUIRES_KEY_NAME = '__slash_requirements__'
def requires(req, message=None):
"""A decorator specifying that the decorated tests requires a certain precondition in order to run
:param req: Either a function receiving no arguments and returning a ... |
3394130 | import os
from pathlib import Path
import responses
from wikidict import download
from wikidict.constants import BASE_URL, DUMP_URL
WIKTIONARY_INDEX = """<html>
<head><title>Index of /frwiktionary/</title></head>
<body bgcolor="white">
<h1>Index of /frwiktionary/</h1><hr><pre><a href="../">../</a>
<a href="20191120/... |
3394168 | from api.model.food import Food
from api.model.foodComment import FoodComment
from api.model.ingredient import Ingredient
from api.model.inclusion import Inclusion
from api.model.ateIngredient import AteIngredient
from api.model.ateFood import AteFood
from api.model.restaurant import Restaurant
from api.model.diet impo... |
3394192 | import yaml
import sys
from insights.core.evaluators import SingleEvaluator
from insights.formats import EvaluatorFormatterAdapter, get_response_of_types
from yaml.representer import Representer
from insights.core import ScanMeta
Representer.add_representer(ScanMeta, Representer.represent_name)
class YamlFormat(Sin... |
3394234 | from django.test import TestCase
from chain.core.models import Unit, Metric, Device, ScalarSensor, Site, \
PresenceSensor, Person, Metadata
from chain.core.models import GeoLocation
from chain.core.api import HTTP_STATUS_SUCCESS, HTTP_STATUS_CREATED
from chain.core.hal import HALDoc
from chain.core import resources... |
3394235 | import os
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from skimage import io
from time import time
from .utils import chk_mkdir, Logger, MetricList
from .dataset import ImageToImage2D, Image2D
class Model:
"""
Wrapper f... |
3394268 | import yaml
from operatorcourier.build import BuildCmd
class _literal(str):
pass
def _literal_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
def _get_empty_formatted_bundle():
return dict(
data=dict(
customResourceDefinitions='',
... |
3394273 | import os
import pytest
import tempfile
import shutil
import sys
from programs.utils import ship_files2spark
if 'SPARK_HOME' not in os.environ:
os.environ['SPARK_HOME'] = '/usr/lib/spark'
@pytest.fixture(scope="module")
def spark():
tempdir = tempfile.mkdtemp()
# Add the directory with pyspark and py4... |
3394296 | from pyradioconfig.parts.jumbo.profiles.Profile_LongRange import Profile_Long_Range_Jumbo
from pyradioconfig.parts.common.profiles.nixi_regs import *
from pyradioconfig.parts.common.profiles.profile_common import buildCrcOutputs, buildFecOutputs, buildFrameOutputs, \
buildWhiteOutputs, buildLongRangeOutputs
class ... |
3394303 | from falcon_kit import run_support as support
from pypeflow.simple_pwatcher_bridge import (
PypeLocalFile, makePypeLocalFile, fn,
PypeTask,
PypeProcWatcherWorkflow, MyFakePypeThreadTaskBase)
from falcon_kit.FastaReader import FastaReader
import glob
import json
import logging
import os
import pp... |
3394305 | from django.conf.urls import url
from bookmarks.views import bookmark, listing, weekly, weekof
urlpatterns = [
url(r'^bookmark$', bookmark),
url(r'^listing$', listing),
url(r'^weekly$', weekly),
url(r'^weekof$', weekof),
]
|
3394329 | import django.apps
class PGHistoryTestsConfig(django.apps.AppConfig):
name = 'pghistory.tests'
def ready(self):
import pghistory.models
User = django.apps.apps.get_model('auth', 'User')
# Track events to user group relationships
pghistory.track(
pghistory.AfterIns... |
3394363 | from collections import OrderedDict
import logging
import re
from r2d7.core import DroidCore
logger = logging.getLogger(__name__)
class FactionLister(DroidCore):
@property
def faction_icon_pattern(self):
raise NotImplementedError()
def __init__(self):
super().__init__()
pattern ... |
3394398 | import torch
torch.backends.cudnn.benchmark = True
import torch.nn.functional as F
import numpy as np
from .dqn import DQN
class QRDQN(DQN):
"""Quantile Regression DQN (QR-DQN) agent.
Args:
state_size (int): dimension of state.
action_size (int): dimension of action.
num_support (in... |
3394445 | import airsimneurips
import threading
import time
class ReproduceResetRaceCondition():
def __init__(self, drone_name = "drone_1"):
self.airsim_client = airsimneurips.MultirotorClient()
self.airsim_client_2 = airsimneurips.MultirotorClient()
self.airsim_client_3 = airsimneurips.MultirotorCli... |
3394477 | import numpy as np
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from keras_balanced_batch_generator import make_generator
def example_binary():
num_samples = 100
num_classes = 2
input_shape = (2,)
batch_size = 16
x = np.random.rand(num_s... |
3394488 | import os
import re
from setuptools import setup, find_packages
v = open(os.path.join(os.path.dirname(__file__), "sqlserverport", "__init__.py"))
VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), "README.md")
setup(
name="... |
3394540 | from modules import modules
from adder_graph import adder_graph as graph
from adder_graph import adder_node as node
from util import lg
import networkx as nx
import pydot
from functools import reduce
from itertools import cycle
# Class that generates parallel prefix adder trees
# Trees are initialized to a serial str... |
3394575 | import unittest
from keras.layers import Embedding
from entity_embeddings.config import Config, get_embedding_size
from entity_embeddings.network.network import EmbeddingNetwork
from entity_embeddings.processor.target_type import TargetType
from entity_embeddings.util.dataframe_utils import create_random_csv, remove_... |
3394585 | import numpy as np
import matplotlib.pyplot as plt
import csv
import os
import matplotlib as mpl
from scipy.stats.stats import pearsonr
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
def main():
NOPROB = True
model_dir = "../Model_4-32/"
legend_entries ... |
3394595 | from . import compiler as C
from . import error as Q
from . import module as M
import argparse
import os.path
import sys
parser = argparse.ArgumentParser(description='Compile Rain code.')
parser.add_argument('--output', '-o', metavar='FILE', default=None,
help='Executable file to produce.')
parser.... |
3394697 | from django.contrib import admin
from pyconcz_2016.proposals.admin import EntryAdmin
class Proposals:
configs = {}
def register(self, config):
self.configs[config.key] = config
admin.site.register(
config.model,
getattr(config, 'admin', EntryAdmin)
)
def... |
3394713 | import pytest
import os
import numpy as np
import pandas as pd
import taxcrunch.multi_cruncher as mcr
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def test_a18_validation():
taxcrunch_in = os.path.join(CURRENT_PATH, "taxsim_validation/taxcrunch_in_a18.csv")
crunch = mcr.Batch(taxcrunch_in)
t... |
3394754 | import click
from .app import commands as app
from .sandbox import commands as sandbox
from .user import commands as user
from .report import commands as report
# import logging
# logger = logging.getLogger('veracode')
@click.group()
def main():
pass
main.add_command(app.app)
main.add_command(sandbox.sandbox)
ma... |
3394771 | import KratosMultiphysics as Kratos
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.StatisticsApplication import MethodUtilities
from KratosMultiphysics.StatisticsApplication.test_utilities import GetRandomValue
from KratosMultiphysics.StatisticsApplication.test_utilities import GetR... |
3394835 | from highton.call_mixins import Call
from highton import fields
class ListEmailCallMixin(Call):
"""
A mixin to get all emails of inherited class
These could be: people || companies || kases || deals
"""
EMAILS_OFFSET = 25
def list_emails(self, page=0, since=None):
"""
Get th... |
3394843 | import json
import os
import boto3
def get_return(code, message, request, response):
return {
"statusCode": code,
"headers": {
"Access-Control-Allow-Credentials": True,
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
},
... |
3394864 | import pathlib
import sys
import numpy as np
import pytest
import radontea
import sinogram
# fails on Windows and macOS
@pytest.mark.xfail(sys.platform != "linux", reason="don't know why")
def test_2d_fmp():
sino, angles = sinogram.create_test_sino(A=100, N=101)
r = radontea.fourier_map(sino, angles)
#... |
3394874 | from lego.apps.feeds.constants import ADD, REMOVE
from .tasks import feed_fanout
from .utils import chunks
class FeedManager:
fanout_chunk_size = 10
def add_activity(self, activity, recipients, feed_classes):
for feed in feed_classes:
self._feed_operation(ADD, activity, set(recipients),... |
3394901 | import re
from typing import List, Optional
import regex
def make_pattern(
patterns: List[str],
with_breaks: bool = False,
name: Optional[str] = None,
) -> str:
r"""
Create OR pattern from a list of patterns.
Parameters
----------
patterns : List[str]
List of patterns to merg... |
3394931 | import chess
class Heuristics:
# The tables denote the points scored for the position of the chess pieces on the board.
pTable = [
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0],
[1.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 1.0],
... |
3394941 | import os
def run_command(command, job_name, output_file, error_file, partition, num_task, time, mem_per_cpu, gpu_num):
bash_file_lines = "#!/bin/bash\n#\n"
bash_file_lines += '#SBATCH --job-name=' + job_name + '\n'
bash_file_lines += '#SBATCH --output=' + output_file + '\n'
bash_file_lines += '#SBATC... |
3395025 | import sys
from multiprocessing import Process, Lock
import csv
from collections import OrderedDict
import pymongo
from pymongo import MongoClient
import numpy as np
import datetime
import time
import math
db = None
lock = Lock()
procs = []
#----------------Mongo functions-----------------------
def connect_MongoDB()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.