id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
36089 | from maya import cmds
import copy
# TODO: Find a way to have different naming for different production.
# Maybe handle it in the rig directly?
class BaseName(object):
"""
This class handle the naming of object.
Store a name as a list of 'tokens'
When resolved, the tokens are joinned using a 'separator... |
36094 | from datetime import datetime
import traceback
import boto3
from botocore.exceptions import ClientError
from ...config import config
from ...log import log
class Submitter():
def __init__(self, event):
self.event = event
def find_instance(self, instance_id, mac_address): # pylint: disable=R0201
... |
36117 | from zhixuewang.urls import BASE_URL
class Url:
INFO_URL = f"{BASE_URL}/container/container/student/account/"
CHANGE_PASSWORD_URL = f"{BASE_URL}/portalcenter/home/updatePassword/"
TEST_URL = f"{BASE_URL}/container/container/teacher/teacherAccountNew"
GET_EXAM_URL = f"{BASE_URL}/classreport/class/cl... |
36151 | import pytest
from ssz.sedes import Bitvector
def test_bitvector_instantiation_bound():
with pytest.raises(ValueError):
bit_count = 0
Bitvector(bit_count)
|
36168 | import unittest
import acpc_python_client as acpc
from tools.constants import Action
from weak_agents.action_tilted_agent import create_agent_strategy, create_agent_strategy_from_trained_strategy, TiltType
from tools.io_util import read_strategy_from_file
from evaluation.exploitability import Exploitability
from tool... |
36170 | import functools
import operator
from collections.abc import Iterable
from typing import overload, Union, TypeVar
T = TypeVar('T')
S = TypeVar('S') # <1>
@overload
def sum(it: Iterable[T]) -> Union[T, int]: ... # <2>
@overload
def sum(it: Iterable[T], /, start: S) -> Union[T, S]: ... # <3>
def sum(it, /, start=0):... |
36225 | from camper.db import BarcampSchema, Barcamp
import datetime
def test_get_empty_registration_form(barcamps, barcamp):
barcamps.save(barcamp)
barcamp = barcamps.by_slug("barcamp")
assert barcamp.registration_form == []
def test_add_to_registration_form(barcamps, barcamp):
barcamps.save(barcamp)
fie... |
36230 | from pathlib import Path
from unittest.mock import call
import pytest
from dbt_sugar.core.clients.dbt import DbtProfile
from dbt_sugar.core.config.config import DbtSugarConfig
from dbt_sugar.core.flags import FlagParser
from dbt_sugar.core.main import parser
from dbt_sugar.core.task.audit import AuditTask
from dbt_su... |
36265 | import logging
from flask import Response, make_response, request
from microraiden import HTTPHeaders as header
from flask_restful.utils import unpack
from microraiden.channel_manager import (
ChannelManager,
)
from microraiden.exceptions import (
NoOpenChannel,
InvalidBalanceProof,
InvalidBalanceAmoun... |
36272 | from scipy import linalg
from sklearn.decomposition import PCA
from scipy.optimize import linear_sum_assignment as linear_assignment
import numpy as np
"""
A function that takes a list of clusters, and a list of centroids for each cluster, and outputs the N max closest images in each cluster to its centroids
"""
def cl... |
36278 | import copy
import time
from datetime import datetime
import binascii
import graphviz
import random
from .models.enums.start_location import StartLocation
from .models.enums.goal import Goal
from .models.enums.statue_req import StatueReq
from .models.enums.entrance_shuffle import EntranceShuffle
from .models.enums.ene... |
36289 | from logging import warning
from api import gitlab
from utilities import validate, types
gitlab = gitlab.GitLab(types.Arguments().url)
def get_all(projects):
snippets = {}
for project in projects:
for key, value in project.items():
details = gitlab.get_project_snippets(key)
i... |
36295 | import os
import aiohttp
import asyncio
import json
import time
import datetime
import logging
import gidgethub
import requests
from gidgethub import aiohttp as gh_aiohttp
import sys
import pandas as pd
sys.path.append("..")
from utils.auth import get_jwt, get_installation, get_installation_access_token
from utils.test... |
36298 | from .abstract import AbstractAgentBasedModel
import keras.backend as K
import numpy as np
from tensorflow import TensorShape
from keras.layers import Dense, Reshape
class TrajectorySamplerNetwork(AbstractAgentBasedModel):
'''
Supervised model. Takes in a set of trajectories from the current state;
lear... |
36305 | import numpy as np
from rampwf.utils import BaseGenerativeRegressor
class GenerativeRegressor(BaseGenerativeRegressor):
def __init__(self, max_dists, target_dim):
self.decomposition = 'autoregressive'
def fit(self, X_array, y_array):
pass
def predict(self, X_array):
# constant p... |
36342 | import cv2 as cv # opencv
import copy # for deepcopy on images
import numpy as np # numpy
from random import randint # for random values
import threading # for deamon processing
from pathlib import Path # for directory information
import os # for directory information
from constants import constants # const... |
36349 | from pathlib import Path
import click
import cligj
import geojson
import mercantile
from shapely.geometry import asShape, box
from shapely.ops import split
@click.command()
@cligj.features_in_arg
@click.option(
'-z',
'--min-zoom',
type=int,
required=True,
help='Min zoom level to create tiles for'... |
36368 | from .uniswap_v2_deltas import *
from .uniswap_v2_events import *
from .uniswap_v2_metadata import *
from .uniswap_v2_spec import *
from .uniswap_v2_state import *
|
36371 | from __future__ import annotations
import ast
import pytest
from flake8_pie import Flake8PieCheck
from flake8_pie.pie804_no_unnecessary_dict_kwargs import PIE804
from flake8_pie.tests.utils import Error, ex, to_errors
EXAMPLES = [
ex(
code="""
foo(**{"bar": True})
""",
errors=[PIE804(lineno=2, c... |
36376 | import pyClarion.base as clb
import pyClarion.numdicts as nd
import unittest
import unittest.mock as mock
class TestProcess(unittest.TestCase):
@mock.patch.object(clb.Process, "_serves", clb.ConstructType.chunks)
def test_check_inputs_accepts_good_input_structure(self):
process = clb.Process(
... |
36391 | from .pycrunchbase import (
CrunchBase,
)
from .resource import (
Acquisition,
Address,
Category,
Degree,
FundingRound,
Fund,
Image,
Investment,
IPO,
Job,
Location,
News,
Organization,
Page,
PageItem,
Person,
Product,
Relationship,
StockExc... |
36422 | from django.views.generic import DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from schedule.models import Calendar
from schedule.views i... |
36423 | import dill
import glob
import csv
import os
from os.path import basename, join
from joblib import Parallel, delayed
domain_path = '/datasets/amazon-data/new-julian/domains'
domain_subdirectory = 'only-overall-lemma-and-label-sampling-1-3-5'
domain_files = glob.glob(join(domain_path,
'o... |
36452 | import torch
from torch import nn
import torch.optim as optim
import torch.multiprocessing as mp
import numpy as np
import time
class MPManager(object):
def __init__(self, num_workers):
"""
manage a single-instruction-multiple-data (SIMD) scheme
:param int num_workers: The number of proces... |
36462 | import csv
def save_minimal_pairs(output_filename, to_output, write_header=True):
if isinstance(output_filename, str):
outf = open(output_filename, mode='w', encoding='utf-8-sig', newline='')
needs_closed = True
else:
outf = output_filename
needs_closed = False
writer = cs... |
36492 | c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
|
36510 | from polyphony import testbench
class C:
def __init__(self, x):
self.x = x
class D:
def __init__(self, c):
self.c = c
def alias02(x):
c0 = C(x)
c1 = C(x*x)
d = D(c0)
result0 = d.c.x == x
d.c = c1
result1 = d.c.x == x*x
c1.x = 0
result2 = d.c.x == 0
d.c = c0... |
36515 | import json
import requests
from rotkehlchen.assets.asset import Asset
from rotkehlchen.constants.timing import DEFAULT_TIMEOUT_TUPLE
from rotkehlchen.errors.misc import RemoteError
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.history.deserialization import deserialize_price
from... |
36547 | from sklearn.metrics import mean_squared_error, log_loss
from keras.models import Model
from keras.models import load_model
from keras.layers import Input, Dense
from keras.layers.recurrent import SimpleRNN
from keras.layers.merge import multiply, concatenate, add
from keras import backend as K
from keras import initia... |
36549 | import zengl
from defaults import defaults
from grid import grid_pipeline
from window import Window
window = Window(1280, 720)
ctx = zengl.context()
image = ctx.image(window.size, 'rgba8unorm', samples=4)
depth = ctx.image(window.size, 'depth24plus', samples=4)
image.clear_value = (0.2, 0.2, 0.2, 1.0)
ctx.includes[... |
36554 | import behave
@behave.when(u"I list triggers")
def step_impl(context):
context.trigger_list = context.service.triggers.list()
@behave.then(u'I receive a Trigger list of "{count}" objects')
def step_impl(context, count):
assert context.trigger_list.items_count == int(count)
if int(count) > 0:
for... |
36568 | import os
from flask import current_app
from flask import _app_ctx_stack as stack
class ConfigWriter(object):
def __init__(self, app=None, consul=None, vault=None):
self.app = app
self.consul = consul
self.vault = vault
if app is not None:
self.init_app(app, consul, v... |
36603 | import discord
import slash_util
class SampleCog(slash_util.Cog):
@slash_util.slash_command(guild_id=123)
async def pog(self, ctx: slash_util.Context):
await ctx.send("pog", ephemeral=True)
@slash_util.message_command(guild_id=123)
async def quote(self, ctx: slash_util.Context, message: discor... |
36652 | import numpy as np
import pytest
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from hcrystalball.metrics import get_scorer
from hcrystalball.model_selection import FinerTimeSplit
from hcrystalball.model_selection import get_best_not_fail... |
36659 | import os, pickle
import os.path as osp
import numpy as np
import cv2
import scipy.ndimage as nd
import init_path
from lib.dataset.get_dataset import get_dataset
from lib.network.sgan import SGAN
import torch
from torch.utils.data import DataLoader
import argparse
from ipdb import set_trace
import matplotlib.pyplot as... |
36682 | class Solution:
def divisorGame(self, N: int) -> bool:
return True if N % 2 == 0 else False |
36745 | import sys
import signal
from clint.textui import colored, puts
from downloader import Downloader
from extractor import Extractor
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
def main():
downloader = Downloader()
extractor = Extractor()
url = "https://pornhub.com"
puts(colored.green("getti... |
36769 | from .. import DomainAdaptationDataset, SimpleDataset
SolV4folders = [
"/fast-2/datasets/Solv4_strings_wav/audio/Cello",
"/fast-2/datasets/Solv4_strings_wav/audio/Contrabass",
"/fast-2/datasets/Solv4_strings_wav/audio/Violin",
"/fast-2/datasets/Solv4_strings_wav/audio/Viola"
]
def Solv4Strings_Domain... |
36782 | import pp
def test_mzi():
netlist = """
instances:
CP1:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 10
CP2:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 5
arm_t... |
36809 | from typing import List, Literal, Optional, Sequence
from pydantic import Field, root_validator, validator
from pydantic.main import BaseModel
from weaverbird.pipeline.steps.utils.base import BaseStep
from weaverbird.pipeline.steps.utils.render_variables import StepWithVariablesMixin
from weaverbird.pipeline.steps.ut... |
36845 | track = dict(
author_username='alexisbcook',
course_name='Data Cleaning',
course_url='https://www.kaggle.com/learn/data-cleaning',
course_forum_url='https://www.kaggle.com/learn-forum/172650'
)
lessons = [ {'topic': topic_name} for topic_name in
['Handling missing values', #1
... |
36950 | import json
try:
import cPickle as pickle
except:
import pickle
def save_json(data, file_path):
with open(file_path, "w") as f:
json.dump(data, f)
def save_json_pretty(data, file_path):
"""save formatted json, use this one for some json config files"""
with open(file_path, "w") as f:
... |
36982 | class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k |
36987 | import tkinter as tk
import tkinter.ttk as ttk
from .pixel_canvas import PixelCanvas
class DemoWindow(ttk.Frame):
def __init__(self, master, model_wrapper,
canvas_size=50, window_size=28,
refresh_period=50, test_image=None, **kw):
ttk.Frame.__init__(self, master=master... |
37009 | import os
try:
from xdebug.unittesting import XdebugDeferrableTestCase
except:
from SublimeTextXdebug.xdebug.unittesting import XdebugDeferrableTestCase
class TestBreakpointStep(XdebugDeferrableTestCase):
breakpoint_step_file = 'breakpoint_step.php'
breakpoint_step_file_local_path = os.path.join(Xdebu... |
37014 | from unittest import TestCase
from parameterized import parameterized
from tests.test_utils import mock_request_handler
from web.web_auth_utils import remove_webpack_suffixes, is_allowed_during_login
class WebpackSuffixesTest(TestCase):
def test_remove_webpack_suffixes_when_css(self):
normalized = remov... |
37061 | from instauto.api.client import ApiClient
from instauto.helpers.post import unlike_post
client = ApiClient.initiate_from_file('.instauto.save')
unlike_post(client, "media_id")
|
37074 | from pygsti.report.table import ReportTable
from ..util import BaseCase
class TableInstanceTester(BaseCase):
custom_headings = {
'html': 'test',
'python': 'test',
'latex': 'test'
}
def setUp(self):
self.table = ReportTable(self.custom_headings, ['Normal'] * 4) # Four form... |
37078 | from keras.models import Model
from keras.layers import Input
from keras.layers.core import Activation
from keras.layers.convolutional import Conv3D, Deconv3D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
def generator(phase_train=True, params={'z_siz... |
37102 | import logging
import os
from typing import Generic, List, Type, Any
import torch
import torch.nn as nn
from ..downloading.downloading_utils import from_cache
from ..featurization.featurization_api import T_BatchEncoding, T_Config, PretrainedFeaturizerMixin
class PretrainedModelBase(nn.Module, Generic[T_BatchEncodi... |
37114 | import pytest
from django.urls import reverse
class TestImageUpload:
@pytest.mark.django_db
def test_upload_image_not_authenticated(self, client, small_jpeg_io):
upload_url = reverse("cast:api:upload_image")
small_jpeg_io.seek(0)
r = client.post(upload_url, {"original": small_jpeg_io... |
37168 | import logging
l = logging.getLogger("archr.analyzers.datascout")
from ..errors import ArchrError
from . import Analyzer
# Keystone engine 0.9.2 (incorrectly) defaults to radix 16. so we'd better off only using 0x-prefixed integers from now.
# See the related PR: https://github.com/keystone-engine/keystone/pull/382
... |
37217 | import datetime as dt
import unittest
from AShareData import set_global_config
from AShareData.model import *
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
set_global_config('config.json')
def test_something(self):
self.assertEqual(True, False)
@staticmethod
def test... |
37259 | import contextlib
import random
import string
from password_strength import PasswordStats
from redbot.core import commands
from redbot.core.utils import chat_formatting as cf
from .word_list import *
GREEN_CIRCLE = "\N{LARGE GREEN CIRCLE}"
YELLOW_CIRCLE = "\N{LARGE YELLOW CIRCLE}"
ORANGE_CIRCLE = "\N{LARGE ORANGE CI... |
37266 | from sympy import *
# Implementation of QuaternionBase<Derived>::toRotationMatrix(void).
# The quaternion q is given as a list [qw, qx, qy, qz].
def QuaternionToRotationMatrix(q):
tx = 2 * q[1]
ty = 2 * q[2]
tz = 2 * q[3]
twx = tx * q[0]
twy = ty * q[0]
twz = tz * q[0]
txx = tx * q[1]
txy = ty * q[... |
37279 | import os
from importlib import import_module
from django.apps import apps
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.serializer import serializer_factory
from django.db.models import ForeignKey, ManyToManyField
from django.utils.inspect import get_func_args
from django.utils.mod... |
37307 | import collections
import datetime
import logging
import os
import sys
from pathlib import Path
import numpy as np
import pdfkit as pdfkit
from bs4 import BeautifulSoup
from sklearn.metrics import mean_absolute_error, mean_squared_error, confusion_matrix, classification_report, \
accuracy_score
from tldextract imp... |
37323 | import os
import tests
from tests import at_most, compile, savefile
import subprocess
node_present = True
erlang_present = True
if os.system("node -v >/dev/null 2>/dev/null") != 0:
print " [!] ignoring nodejs tests"
node_present = False
if (os.system("erl -version >/dev/null 2>/dev/null") != 0 or
os.sys... |
37350 | from tnparser.pipeline import read_pipelines, Pipeline
text1="I have a dog! Let's see what I can do with Silo.ai. :) Can I tokenize it? I think so! Heading: This is the heading And here continues a new sentence and there's no dot."
text2="Some other text, to see we can tokenize more stuff without reloading the model..... |
37425 | from flask import current_app, request, Response, make_response
from rdflib import ConjunctiveGraph
from werkzeug.exceptions import abort
from depot.middleware import FileServeApp
from .entity_blueprint import entity_blueprint
from whyis.data_extensions import DATA_EXTENSIONS
from whyis.data_formats import DATA_FORMAT... |
37427 | from enum import Enum
class Currency(Enum):
AUD = 'Australia Dollar'
BGN = 'Bulgaria Lev'
BRL = 'Brazil Real'
CAD = 'Canada Dollar'
CHF = 'Switzerland Franc'
CNY = 'China Yuan/Renminbi'
CZK = 'Czech Koruna'
DKK = 'Denmark Krone'
GBP = 'Great Britain Pound'
HKD = 'Hong Kong Doll... |
37429 | import time
import argparse
from datetime import datetime
import logging
import numpy as np
import os
import torch
import torch.nn.functional as F
import torch.multiprocessing as mp
from models import NavCnnModel, NavCnnRnnModel, NavCnnRnnMultModel, NavPlannerControllerModel
from data import EqaDataLoader
from metrics ... |
37430 | import os
import json
import argparse
from pathlib import Path
import pandas as pd
import dateutil
parser = argparse.ArgumentParser()
parser.add_argument("directory", type=Path help="Path to the directory.")
def main():
args = parser.parse_args()
dirs = sorted([d for d in os.listdir(args.directory) if os.pa... |
37434 | from BinaryModel import *
from numpy.random import rand
class MajorityModel(BinaryModel):
def __init__(self, filename=None):
self.mdlPrm = {
'addNoise' : False,
}
self.wkrIds = {}
self.imgIds = {}
if filename:
self.load_data(filename)
else:
... |
37447 | import os
import re
import gzip
import argparse
import pandas as pd
import numpy as np
from collections import defaultdict
def get_args():
"""
Parse command line arguments
"""
parser = argparse.ArgumentParser(description="Method to create track for escape mutations")
parser.add_argument("-xlsx",... |
37452 | from django.conf import settings
DRFSO2_PROPRIETARY_BACKEND_NAME = getattr(settings, 'DRFSO2_PROPRIETARY_BACKEND_NAME', "Django")
DRFSO2_URL_NAMESPACE = getattr(settings, 'DRFSO2_URL_NAMESPACE', "")
|
37453 | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... |
37457 | load(
"//tensorflow/core/platform:rules_cc.bzl",
"cc_library",
)
def poplar_cc_library(**kwargs):
""" Wrapper for inserting poplar specific build options.
"""
if not "copts" in kwargs:
kwargs["copts"] = []
copts = kwargs["copts"]
copts.append("-Werror=return-type")
cc_library(**kwargs)
|
37473 | from datetime import datetime, date
from marqeta.response_models.result import Result
from marqeta.response_models.kyc_question import KycQuestion
from marqeta.response_models import datetime_object
import json
import re
class KycResponse(object):
def __init__(self, json_response):
self.json_response = js... |
37485 | a = input("Enter the string:")
b = a.find("@")
c = a.find("#")
print("The original string is:",a)
print("The substring between @ and # is:",a[b+1:c]) |
37496 | import thoonk
from thoonk.feeds import SortedFeed
import unittest
from ConfigParser import ConfigParser
class TestLeaf(unittest.TestCase):
def setUp(self):
conf = ConfigParser()
conf.read('test.cfg')
if conf.sections() == ['Test']:
self.ps = thoonk.Thoonk(host=conf.get('Te... |
37499 | from unittest.mock import MagicMock
import google.protobuf.text_format as text_format
import numpy as np
from banditpylib.bandits import CvarReward
from banditpylib.data_pb2 import Actions, Context
from .ts import ThompsonSampling
class TestThompsonSampling:
"""Test thompson sampling policy"""
def test_simple_... |
37500 | from maru import pymorphy
from maru.lemmatizer.abstract import ILemmatizer
from maru.tag import Tag
from maru.types import Word
class PymorphyLemmatizer(ILemmatizer):
def lemmatize(self, word: Word, tag: Tag) -> Word:
best_parse = max(
pymorphy.analyze(word),
key=lambda parse: (
... |
37502 | import os
import xcffib
from xcffib.testing import XvfbTest
from xcffib.xproto import Atom, ConfigWindow, EventMask, GetPropertyType
conn = xcffib.connect(os.environ['DISPLAY'])
xproto = xcffib.xproto.xprotoExtension(conn)
def arrange(layout, windowids):
for lay, winid in zip(layout, windowids):
xproto.... |
37515 | import subprocess
__all__ = ['view_env', 'create_env', 'remove_env']
def view_env():
"""Get virtual environment info."""
cmd = f"conda info -e"
s = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
s = s.decode('utf-8').strip().split('\n')[2:]
s = [i.split(' ') for i in s]... |
37526 | import asyncio
import math
import networkx as nx
import ccxt.async_support as ccxt
import datetime
import logging
from .logging_utils import FormatForLogAdapter
__all__ = [
'FeesNotAvailable',
'create_exchange_graph',
'load_exchange_graph',
]
adapter = FormatForLogAdapter(logging.getLogger('peregrinearb.u... |
37546 | import json
from .fragment_doc import fragment_srt, fragment_syosetu, has_unbalanced_quotes, extract_kana_kanji
EXTRACT_KANA_KANJI_CASES = [
['asdf.!ä', ''],
['あいうえお', 'あいうえお'],
['asdこfdれ', 'これ'],
['「ああ、畜生」foo', 'ああ畜生'],
]
for [text, target] in EXTRACT_KANA_KANJI_CASES:
if extract_kana_kanji(text)... |
37607 | import sys;
from queue import Queue
from multiprocessing.managers import BaseManager
import etl;
import json
import extends;
import time;
authkey= "etlpy".encode('utf-8')
timeout=1;
rpc_port=8888
class ETLJob:
def __init__(self,project,jobname,config,id):
self.project= project;
self.jobname=jobnam... |
37614 | from blackboard import BlackBoardContent, BlackBoardClient, BlackBoardAttachment, BlackBoardEndPoints, \
BlackBoardCourse, BlackBoardInstitute
import os
import re
import requests
import datetime
import xmltodict
import argparse
import sys
import json
import getpass
import main
def test():
args = main.handle_ar... |
37627 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
class MapColorControl():
def __init__(self, colour_scheme, map_normalization,data):
self.colors = plt.get_cmap(colour_scheme)(range(256))[:,:3]
self.data = data
if self.data.min() <= 0:
self.d... |
37628 | from django.conf.urls import patterns, url
from lattice.views import (lattices)
from lattice.views import (saveLatticeInfo, saveLattice)
from lattice.views import (saveModel)
from lattice.views import (lattice_home, lattice_content_home, lattice_content_search, lattice_content_list, lattice_content_model_list, lattice... |
37633 | import unittest
import torch
from parameterized import parameterized
from torecsys.losses import *
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
class AdaptiveHingeLossTestCase(unittest.TestCase):
@parameterized.expand([
(4, 32,),
(16, 16,),
(32, 4,),
])
def test_for... |
37636 | import os
from sqlite3 import dbapi2 as sqlite3
class GarageDb:
def __init__(self, instance_path, resource_path):
self.db_file = os.path.join(instance_path, 'history.db')
self.init_file = os.path.join(resource_path, 'schema.sql')
# Run init script to ensure database structure
conn ... |
37645 | from flask_restful import Resource
from flask import request
class Shutdown(Resource):
def get(self):
shutdown = request.environ.get('werkzeug.server.shutdown')
if shutdown is None:
raise RuntimeError('Not running with the Werkzeug Server')
shutdown()
return 'Server shu... |
37675 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.labour import labour
def test_labour():
"""Test module labour.py by downloading
labour.csv and testing shape of
extracted data has 569 row... |
37703 | from hwt.synthesizer.unit import Unit
from hwt.interfaces.std import VectSignal
from hwt.hdl.types.struct import HStruct
from hwt.interfaces.utils import addClkRstn
class PrivateSignalsOfStructType(Unit):
def _declr(self):
addClkRstn(self)
self.a = VectSignal(8)
self.b = VectSignal(8)._m(... |
37711 | from _carmcmc import *
from carma_pack import CarmaModel, CarmaSample, Car1Sample, power_spectrum, carma_variance, \
carma_process, get_ar_roots
from samplers import MCMCSample
|
37712 | from django.conf.urls import url
from .views import tracon2022_afterparty_participants_view, tracon2022_afterparty_summary_view
urlpatterns = [
url(
r'^events/(?P<event_slug>tracon2022)/labour/surveys/kaatoilmo/results.xlsx$',
tracon2022_afterparty_participants_view,
name='tracon2022_afte... |
37739 | from __future__ import unicode_literals
import os, sys, subprocess, ast
from nbconvert.preprocessors import Preprocessor
from holoviews.core import Dimensioned, Store
from holoviews.ipython.preprocessors import OptsMagicProcessor, OutputMagicProcessor
from holoviews.ipython.preprocessors import StripMagicsProcessor
fr... |
37770 | import qcodes as qc
from qdev_wrappers.sweep_functions import _do_measurement, _do_measurement_single, \
_select_plottables
def measure(meas_param, do_plots=True):
"""
Function which measures the specified parameter and optionally
plots the results.
Args:
meas_param: parameter to measure
... |
37782 | import json
import os
import sys
import time
from os import path as osp
from pathlib import Path
from shutil import copyfile
import numpy as np
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm import tqdm
from model_temporal import LSTMSeqNetwork, B... |
37821 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
import d20_action_utils
###################################################
def GetConditionName():
return "Duelist"
print "Registering " + GetConditionName()
classEnum = stat_level_duelist
preciseStrikeEnum = 2400
#... |
37839 | import math
import os
import tempfile
from contextlib import contextmanager
from soap import logger
from soap.common.cache import cached
from soap.expression import operators, OutputVariableTuple
from soap.semantics.error import IntegerInterval, ErrorSemantics
flopoco_command_map = {
'IntAdder': ('{wi}', ),
... |
37928 | import os.path as osp
import os
import pylab as plt
import gc
import argparse
from utils import read_image
parser = argparse.ArgumentParser(description='Plot rank-5 results of S-ReID, SP-ReID and SSP-ReID')
parser.add_argument('-d', '--dataset', type=str, default='market1501')
# Architecture
parser.add_argument('-a... |
37933 | import unittest
from unittest.mock import MagicMock
from datetime import timedelta
from osgar.bus import Bus
from osgar.node import Node
class NodeTest(unittest.TestCase):
def test_usage(self):
empty_config = {}
bus = Bus(logger=MagicMock())
node = Node(config=empty_config, bus=bus.handl... |
37946 | import os
import json
import pickle
import collections
import numpy as np
from s2and.consts import CONFIG
DATA_DIR = CONFIG["main_data_dir"]
OUTPUT_DIR = os.path.join(DATA_DIR, "s2and_mini")
if not os.path.exists(OUTPUT_DIR):
os.mkdir(OUTPUT_DIR)
# excluding MEDLINE because it has no clusters
DATASETS = [
"a... |
37983 | from .eval_card import EvaluationCard
from .evaluator import Evaluator
from .lookup import LookupTable
|
37985 | import re
from email_validator import validate_email, EmailSyntaxError
from virtool.users.utils import PERMISSIONS
RE_HEX_COLOR = re.compile("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")
def strip(value: str) -> str:
"""
Strip flanking whitespace from the passed string. Used to coerce values in Cerberus validators... |
37995 | import os
import subprocess
from pretty_print import Print_C
class Runner:
run_kases = 3
def __init__(self, scheme, testcases):
self.scheme = scheme
self.testcases = testcases
self.bin_file_template = f"build/test_results/{{testcase}}/bin/{scheme}"
self.myout_template = f"buil... |
38022 | import datetime
from django.db import models
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
class Guest(models.Model):
"""
A temporary user.
Fields:
``user`` - The temporary user.
``last_used`` - The last time we noted this user doing something... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.