id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
103860 | import numpy as np
from pymoo.experimental.deriv import DerivationBasedAlgorithm
from pymoo.algorithms.base.line import LineSearchProblem
from pymoo.algorithms.soo.univariate.exp import ExponentialSearch
from pymoo.algorithms.soo.univariate.golden import GoldenSectionSearch
from pymoo.core.population import Population... |
103865 | import argparse
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
import torch
from volksdep.converters import torch2onnx
from vedaseg.runners import InferenceRunner
from vedaseg.utils import Config
def parse_args():
parser = argparse.ArgumentParser(description='Convert to... |
103909 | from __future__ import print_function
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
import urllib.request
import json
from geopy.distance import vincenty
test_20 = {
"points": [[10.773687, 106.703263], [10.731158, 106.716759], [... |
103918 | import os
import torch
import numbers
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from torch.utils.data import Subset, TensorDataset
import numpy as np
def get_dataset(args, config):
if config.data.random_flip is False:
tran_transform = test_transform = trans... |
103920 | import networkzero as nw0
address = nw0.advertise("myservice3", 1234)
print("Service is at address", address) |
103928 | import os
import shutil
from vilya.libs.permdir import get_repo_root
from vilya.models.project import CodeDoubanProject
from tests.base import TestCase
class TestBasic(TestCase):
def test_create_git_repo(self):
git_path = os.path.join(get_repo_root(), 'abc.git')
CodeDoubanProject.create_git_repo... |
103944 | import random, sys, gzip
class tour:
def __init__(self):
self.path = [None] * 1
self.fit = 0
self.travel = 0
def mutate(self):
a = random.randint(0, len(self.path)-1)
b = random.randint(0, len(self.path)-1)
temp = self.path[a]
self.path[a] = self.path[b]
self.path[b] = temp
def blanktour(self... |
103961 | from __future__ import absolute_import
import openshift as oc
import base64
import json
def get_kubeconfig():
"""
:return: Returns the current kubeconfig as a python dict
"""
return json.loads(oc.invoke('config',
cmd_args=['view',
... |
104015 | try:
with open('../../../assets/img_cogwheel_argb.bin','rb') as f:
cogwheel_img_data = f.read()
except:
try:
with open('images/img_cogwheel_rgb565.bin','rb') as f:
cogwheel_img_data = f.read()
except:
print("Could not find binary img_cogwheel file")
# create the cogwheel image data
cogwheel_im... |
104081 | import math
from misc.callback import callback
# Drawing parameters
class ManiaSettings():
viewable_time_interval = 1000 # ms
note_width = 50 # osu!px
note_height = 15 # osu!px
note_seperation = 5 # osu!px
replay_opacity = 50 # %
@stat... |
104100 | import sys
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.modules.vggNet import VGGFeatureExtractor
class TVLoss(nn.Module):
def __init__(self, weight=1.0):
super(TVLoss, self).__init__()
self.weight = weight
self.l1 = nn.L1Loss... |
104118 | import tensorflow as tf
import numpy as np
PROJ_EPS = 1e-5
EPS = 1e-15
MAX_TANH_ARG = 15.0
# Real x, not vector!
def tf_atanh(x):
return tf.atanh(tf.minimum(x, 1. - EPS)) # Only works for positive real x.
# Real x, not vector!
def tf_tanh(x):
return tf.tanh(tf.minimum(tf.maximum(x, -MAX_TANH_ARG), MAX_TA... |
104124 | import time
import requests
from pysmashgg.exceptions import *
# Runs queries
def run_query(query, variables, header, auto_retry):
# This helper function is necessary for TooManyRequestsErrors
def _run_query(query, variables, header, auto_retry, seconds):
json_request = {'query': query, 'variables': v... |
104125 | from ctypes import POINTER, c_char_p, byref
from ...ffi import utils
from ...ffi.ontology.facades import CTtsFacade
from ...ffi.utils import hermes_protocol_handler_tts_facade, hermes_drop_tts_facade
class TtsFFI(object):
def __init__(self, use_json_api=True):
self.use_json_api = use_json_api
sel... |
104137 | from click.testing import CliRunner
from modelindex.commands.cli import cli
def test_cli_invocation():
runner = CliRunner()
result = runner.invoke(cli)
assert result.exit_code == 0
def test_cli_check_ok():
runner = CliRunner()
result = runner.invoke(cli, ["check", "tests/test-mi/11_markdown/rexn... |
104139 | import torch
import torch.nn as nn
from models.utils import parse_model_params, get_params_str
from models.utils import sample_gauss, nll_gauss
class RNN_GAUSS(nn.Module):
"""RNN with Gaussian output distribution."""
def __init__(self, params, parser=None):
super().__init__()
self.model_arg... |
104169 | import numpy as np
from numpy.linalg import inv
class GeoArray(np.ndarray):
def __new__(cls, input_array, crs=4326, mat=None):
obj = np.asarray(input_array).view(cls)
obj.crs, obj.mat = crs, mat.reshape((2,3))
return obj
def __array_finalize__(self, obj):
if obj is None: re... |
104182 | import struct
from suitcase.fields import BaseField
from suitcase.fields import BaseStructField
from suitcase.fields import BaseFixedByteSequence
class SLFloat32(BaseStructField):
"""Signed Little Endian 32-bit float field."""
PACK_FORMAT = UNPACK_FORMAT = b"<f"
def unpack(self, data, **kwargs):
... |
104197 | import numpy as np
from matplotlib import pyplot as plt
'''
Function for plotting training and validation curves.
'''
def learning_curves(history, multival=None, model_n=None, filepath=None, plot_from_epoch=0, plot_to_epoch=None):
n = len(history)
num_epochs = len(history[0]['loss'])
if plot_to_epoch is ... |
104223 | from kaishi.image.util import validate_image_header
def test_validate_image_header():
invalid_file = "tests/data/image/empty_unsupported_extension.gif"
valid_file = "tests/data/image/sample.jpg"
assert validate_image_header(invalid_file) is False
assert validate_image_header(valid_file) is True
|
104232 | import pytest
import schedule
from orchestrator.cli.scheduler import run
from orchestrator.schedules import ALL_SCHEDULERS
from orchestrator.schedules.scheduling import scheduler
def test_scheduling_with_period(capsys, monkeypatch):
ref = {"called": False}
@scheduler(name="test", time_unit="second", period... |
104261 | from src.utilities.app_context import LOG_WITHOUT_CONTEXT
from anuvaad_auditor.loghandler import log_info, log_exception
import csv
import uuid
class ParseCSV (object):
def __init__(self):
pass
def get_parallel_sentences(filename, source_language, target_language, skip_header=True):
parallel_s... |
104275 | def variable_argument( var1, *vari):
print "Out-put is",var1
for var in vari:
print var
variable_argument(60)
variable_argument(100,90,40,50,60) |
104310 | import os, time
from slackclient import SlackClient
from pyslack import SlackClient as slackclient
client = slackclient(os.environ.get('SLACK_BOT_TOKEN'))
BOT_NAME = 'aws_bot'
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
# starterbot's ID as an environment variable
# BOT_ID = os.environ.get("BOT_ID")
... |
104414 | from __future__ import absolute_import, division, print_function
import subprocess
import os
import sys
import pandas
import socket
from time import sleep
from typing import IO, Any, Optional
perf_cmd = [
"perf",
"record",
"--no-buildid",
"--no-buildid-cache",
"-e",
"raw_syscalls:*",
"--s... |
104428 | from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Task
read_only_fields = ('slug',) |
104430 | from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from core.models import Category, Post
from users.models import UserProfile
from django.contrib.auth.models import User
import pytest
@pytest.mark.django_db
class CategoryTest(TestCase):
def create_category(self, ti... |
104529 | from .vcoco_evaluation import VCOCOEvaluator
from .hico_evaluation import HICOEvaluator
from detectron2.evaluation.evaluator import DatasetEvaluator, DatasetEvaluators, inference_on_dataset
from detectron2.evaluation.testing import print_csv_format, verify_results
__all__ = [k for k in globals().keys() if not k.starts... |
104533 | import socket
from contextlib import closing
from typing import cast
from .logging import LoggingDescriptor
_logger = LoggingDescriptor(name=__name__)
def find_free_port() -> int:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("127.0.0.1", 0))
s.setsockopt(socket.S... |
104563 | import os
import glob
import random
class PairGenerator(object):
person1 = 'person1'
person2 = 'person2'
label = 'same_person'
def __init__(self, lfw_path='./tf_dataset/resources' + os.path.sep + 'lfw'):
self.all_people = self.generate_all_people_dict(lfw_path)
def generate_all_people_di... |
104575 | import matplotlib.pyplot as plt
import cv2
import numpy as np
def plot_imgs(imgs, titles=None, cmap='brg', ylabel='', normalize=True, ax=None,
r=(0, 1), dpi=100):
n = len(imgs)
if not isinstance(cmap, list):
cmap = [cmap]*n
if ax is None:
_, ax = plt.subplots(1, n, figsize=(6... |
104601 | import numpy as np
import utils
from dataset_specifications.dataset import Dataset
class ConstNoiseSet(Dataset):
def __init__(self):
super().__init__()
self.name = "const_noise"
self.std_dev = np.sqrt(0.25)
def get_support(self, x):
return (x-2*self.std_dev, x+2*self.std_dev)... |
104624 | from collections import OrderedDict, defaultdict
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import time
import torch
from FClip.line_parsing import OneStageLineParsing
from FClip.config import M
from FClip.losses import ce_loss, sigmoid_l1_loss, focal_loss, l12loss
from FClip.nms import ... |
104674 | import json
from lints.vim import VimVint, VimLParserLint
def test_vint_undefined_variable():
msg = ['t.vim:3:6: Undefined variable: s:test (see :help E738)']
res = VimVint().parse_loclist(msg, 1)
assert json.loads(res)[0] == {
"lnum": "3",
"col": "6",
"text": "[vint]Undefined var... |
104678 | import unittest
import numpy as np
import pytest
from audiomentations import TanhDistortion
from audiomentations.core.utils import calculate_rms
class TestTanhDistortion(unittest.TestCase):
def test_single_channel(self):
samples = np.random.normal(0, 0.1, size=(2048,)).astype(np.float32)
sample_... |
104690 | from distutils.core import setup
setup(
name='eagle-diff',
version='0.1.0',
description='Show differences between Cadsoft Eagle files',
author='<NAME>',
author_email='<EMAIL>',
long_description=open('README.md').read(),
license=open('LICENSE').read(),
url='https://github.com/fxkr/eagle-... |
104706 | import re, os, glob
def CollectData(N, mem):
for fn in glob.glob("search_tmp.*"):
os.remove(fn)
with open("search.cpp", "rt") as f:
src = f.read()
ints = mem / 8
src = re.sub(r"const int SIZE = (\d*);", r"const int SIZE = %d;" % N, src)
src = re.sub(r"const int ARR_SAMPLE... |
104714 | import pytest
from tests.communication.test_FileComm import TestFileComm as base_class
class TestAsciiFileComm(base_class):
r"""Test for AsciiFileComm communication class."""
@pytest.fixture(scope="class", autouse=True)
def filetype(self):
r"""Communicator type being tested."""
return "as... |
104799 | import os
import pickle
import random
import traceback
from collections import defaultdict
from telethon import utils as telethon_utils
from telethon.sync import events
from plugins.base import Telegram, PluginMount
from utils import get_url
class Action(Telegram, metaclass=PluginMount):
command_name = "auto_repl... |
104804 | import os
import toml
import jsbsim
configuration = toml.load('../config/default_configuration.toml') # included: '/Users/######/Programme/jsbsim-code' #an System anpassen.
sim = jsbsim.FGFDMExec(os.path.expanduser(configuration["simulation"]["path_jsbsim"]))
sim.load_model('c172p')
print(sim.print_property_catalog(... |
104835 | import random
from binary_search_tree import BinarySearchTree
def test_bst_size():
bst = BinarySearchTree()
assert len(bst) == 0
for i in range(5):
bst.insert(i)
assert len(bst) == i + 1
def test_bst_insert_at_right_pos():
bst = BinarySearchTree()
bst.insert(15)
assert bst._... |
104840 | from __future__ import print_function # Python 2/3 compatibility
import boto3
def create_quotes():
table = client.create_table(
TableName='Quotes.EOD',
KeySchema=[
{
'AttributeName': 'Symbol',
'KeyType': 'HASH' # Partition key
},
... |
104936 | import json
def extract_json_data(filename):
with open(filename, "r") as file:
data = json.load(file)
return data |
104998 | from mgt.datamanagers.data_manager import Dictionary
class DictionaryGenerator(object):
@staticmethod
def create_dictionary() -> Dictionary:
"""
Creates a dictionary for a REMI-like mapping of midi events.
"""
dictionary = [{}, {}]
def append_to_dictionary(word):
... |
105030 | from .device_address_pb2_grpc import *
from .device_address_pb2 import *
from .device_pb2_grpc import *
from .device_pb2 import *
from .lorawan_pb2_grpc import *
from .lorawan_pb2 import *
|
105080 | from OpenAttack import substitute
import sys, os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.abspath(__file__)),
".."
))
import OpenAttack
def get_attackers_on_chinese(dataset, clsf):
triggers = OpenAttack.attackers.UATAttacker.get_triggers(clsf, dataset, clsf.tokenizer)
attackers = ... |
105082 | from datetime import datetime
from notifications_utils.template import SMSMessageTemplate
from app import statsd_client
from app.celery.service_callback_tasks import send_delivery_status_to_service
from app.config import QueueNames
from app.dao import notifications_dao
from app.dao.notifications_dao import dao_update... |
105108 | import torch, torchvision
class CIFAR10(torchvision.datasets.CIFAR10):
def __init__(self, root, part, labeled_factors, transform):
super().__init__(root, part == 'train', transform = transform, download = True)
if len(labeled_factors) == 0:
self.has_label = False
self.nclass = []
self.class_freq = []
... |
105114 | import numpy as np
from scipy.interpolate import RectBivariateSpline
def TemplateCorrection(T, It1, rect, p0 = np.zeros(2)):
threshold = 0.1
x1_t, y1_t, x2_t, y2_t = rect[0], rect[1], rect[2], rect[3]
Iy, Ix = np.gradient(It1)
rows_img, cols_img = It1.shape
rows_rect, cols_rect = T.sh... |
105137 | import logging
import tempfile
import unittest
from os import path
from Bio import SeqIO
from staramr.blast.JobHandler import JobHandler
from staramr.blast.plasmidfinder.PlasmidfinderBlastDatabase import PlasmidfinderBlastDatabase
from staramr.blast.resfinder.ResfinderBlastDatabase import ResfinderBlastDatabase
from ... |
105150 | import unittest
import subprocess
import psutil
import sys
import os
import numpy as np
import time
import socket
# Using pygame for gamepad interface
import pygame
# ROS
import rospy
import actionlib
import sensor_msgs.msg
import geometry_msgs.msg
import trajectory_msgs.msg
import rosgraph
import std_srvs.srv
import ... |
105164 | import boto3
from kaos_backend.constants import DOCKER_REGISTRY, REGION, CLOUD_PROVIDER
def get_login_command():
if CLOUD_PROVIDER == 'AWS':
# ecr = boto3.client('ecr', region_name=REGION)
#
# raw_auth_data = ecr.get_authorization_token()['authorizationData'][0]['authorizationToken']
... |
105207 | from .unet import *
from .vae import *
from .others import *
from .pconv_unet import *
from .discriminator import *
from .resnet_cls import *
|
105233 | from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.rdd import RDD
from pyspark.mllib.linalg import SparseVector, VectorUDT, Vectors
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
import re
import numpy as np
#data pr... |
105280 | s = input()
s = s.upper()
c = 0
for i in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
for j in s:
if(i!=j):
c = 0
else:
c = 1
break
if(c==0):
break
if c==1:
print("Pangram exists")
else:
print("Pangram doesn't exists")
|
105299 | from .audio_provider import AudioProvider
from .visual_provider import VisualProvider
from .multifile_audiovisual_provider import MultiFile_AVProvider
from .singlefile_audiovisual_provider import SingleFile_AVProvider
|
105318 | from django_mptt_acl.rules import DefaultRoleRule
class ManageRole(object):
name = 'manage'
permissions = ('read', 'update', 'delete', 'invite', 'create')
required_permissions_ancestors = ('read',)
required_permissions_descendants = permissions
rules = (DefaultRoleRule,) |
105357 | from datetime import date, datetime
from pytz import utc
from parameterized import parameterized, param
import dateparser
from tests import BaseTestCase
class TestParseFunction(BaseTestCase):
def setUp(self):
super().setUp()
self.result = NotImplemented
@parameterized.expand([
param... |
105358 | import fastscapelib_fortran as fs
import numpy as np
import xsimlab as xs
from .grid import UniformRectilinearGrid2D
@xs.process
class TotalVerticalMotion:
"""Sum up all vertical motions of bedrock and topographic surface,
respectively.
Vertical motions may result from external forcing, erosion and/or
... |
105397 | import arcade
import imgui
import imgui.core
from imdemo.page import Page
class Rect(Page):
def draw(self):
imgui.begin("Rectangle")
draw_list = imgui.get_window_draw_list()
p1 = self.rel(20, 35)
p2 = self.rel(90, 80)
draw_list.add_rect(*p1, *p2, imgui.get_color_u32_rgba(1... |
105399 | import tomotopy as tp
model = tp.DTModel()
print(model.alpha)
# print(model.eta)
print(model.lr_a)
print(model.lr_b)
print(model.lr_c)
print(model.num_timepoints)
print(model.num_docs_by_timepoint)
model.add_doc(["new", "document"], timepoint=0)
|
105406 | import argparse
from agutil import status_bar
import subprocess
import csv
import shutil
from qtl.annotation import Annotation
import tempfile
def run(args):
print("Parsing GTF")
gtf = Annotation(args.gtf.name)
print("Parsing GCT")
numRows = int(subprocess.check_output("wc -l %s" % args.gct.name, shell... |
105466 | import os
import subprocess
import argparse
import torch
import json
# import h5py
import gzip, csv
import numpy as np
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
from transformers import *
def get_sentence_features(batches, tokenizer, model, device, maxlen=500):
features = tokenizer.batc... |
105478 | from __future__ import print_function
import sys
import shutil
import os
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
import os
import datetime
import socket
from .. import test
from . import settings
from .. import lib
from . import resource_suite
from ..configuration impo... |
105485 | import datetime
from test_plus.test import TestCase
from qa_tool.tests.helpers import RelevancyScoreBuilder, AlgorithmBuilder, SearchLocationBuilder
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from human_services.services_at_location.test... |
105506 | import pathlib
import tempfile
import cbor2
from retry import retry
from pycardano import *
from .base import TestBase
class TestMint(TestBase):
@retry(tries=4, delay=6, backoff=2, jitter=(1, 3))
def test_mint(self):
address = Address(self.payment_vkey.hash(), network=self.NETWORK)
# Load ... |
105511 | def pytest_configure():
import os
os.environ.setdefault('SUPERTOKENS_ENV', 'testing')
os.environ.setdefault('SUPERTOKENS_PATH', '../supertokens-root')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.Django.settings')
|
105538 | from __future__ import unicode_literals
import os
import appdirs
from reviewbot.config import config
from reviewbot.utils.api import get_api_root
from reviewbot.utils.filesystem import make_tempdir
from reviewbot.utils.log import get_logger
from reviewbot.utils.process import execute
logger = get_logger(__name__)
... |
105570 | from .pylspm import PyLSpm
from .results import PyLSpmHTML
from .boot import PyLSboot
from .rebus import rebus
from .blindfolding import blindfolding
from .bootstraping import bootstrap
from .mga import mga
from .gac import gac
from .pso import pso
from .tabu2 import tabu
from .permuta import permuta
from ... |
105578 | from typing import Tuple
from enum import Enum
class NeutralChargeRule(Enum):
"""
Strict enumeration of different methods to maintain charge neutrality for single residues.
"""
# Ions will not be used to neutralize system. This means OpenMM will add a neutralizing background charge.
NO_IONS = 0
... |
105602 | import operator
from typing import List
import torch
from torch.fx import GraphModule
import mqbench.nn.qat as qnnqat
from mqbench.utils.logger import logger
from mqbench.utils.registry import register_model_quantizer
from mqbench.prepare_by_platform import BackendType
from mqbench.custom_quantizer import ModelQuanti... |
105620 | from gmtpy import GMT
gmt = GMT( config={'BASEMAP_TYPE':'fancy'})
gmt.pscoast( R='5/15/52/58', # region
J='B10/55/55/60/10c', # projection
B='4g4', # grid
D='f', # resolution
S=(114,159,207), # wet fill color
G=(2... |
105643 | import logging
import numpy as np
from typing import Dict, List, Tuple
from transformers import PreTrainedTokenizer
from transformers.tokenization_utils_base import BatchEncoding
class RstPreprocessor:
"""
Class for preprocessing a list of raw texts to a batch of tensors.
"""
def __init__(
... |
105655 | import errno
import os
import random
import socket
import time
import unittest
import docker.client
from sourced.ml.core.utils.bblfsh import BBLFSH_VERSION_HIGH, BBLFSH_VERSION_LOW, check_version
@unittest.skipIf(os.getenv("SKIP_BBLFSH_UTILS_TESTS", False), "Skip ml_core.utils.bblfsh tests.")
class BblfshUtilsTests... |
105669 | from decimal import Decimal
from typing import Iterable, Optional, TypeVar
from stock_indicators._cslib import CsIndicator
from stock_indicators._cstypes import List as CsList
from stock_indicators._cstypes import Decimal as CsDecimal
from stock_indicators._cstypes import to_pydecimal
from stock_indicators.indicators.... |
105702 | from bluesky import Msg
from bluesky.callbacks.olog import logbook_cb_factory
text = []
def f(**kwargs):
text.append(kwargs['text'])
def test_default_template(RE):
text.clear()
RE.subscribe(logbook_cb_factory(f), 'start')
RE([Msg('open_run', plan_args={}), Msg('close_run')])
assert len(text[0])... |
105704 | from unittest import TestCase
from pykalman.sqrt import BiermanKalmanFilter
from pykalman.tests.test_standard import KalmanFilterTests
from pykalman.datasets import load_robot
class BiermanKalmanFilterTestSuite(TestCase, KalmanFilterTests):
"""Run Kalman Filter tests on the UDU' Decomposition-based Kalman Filter"... |
105733 | import flask
import os
from dotenv import load_dotenv
from pathlib import Path
import sys
sys.path.append('fraud_graph/')
import fraud_times.quiz_statistics as quiz_stats
import fraud_times.quiz_orm as quiz_orm
import get_scores as get_scores
import create_dataset2 as create_dataset
import json
# Does not override en... |
105749 | from django.core import mail
from django.test.utils import override_settings
from base.tests.base import SeleniumTestCase
CAPTCHA = 'test'
@override_settings(CAPTCHA=CAPTCHA)
class ContactFormTest(SeleniumTestCase):
def test_contact_form(self):
self.assertEqual(mail.outbox, [])
username = 'joh... |
105766 | import re
from collections import deque
def parse(script):
"""Parse Nuke node's TCL script string into nested list structure
Args:
script (str): Node knobs TCL script string
Returns:
Tablet: A list containing knob scripts or tab knobs that has parsed
into list
"""
qu... |
105775 | from __future__ import print_function
import sys
import cv2
import pdb
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as... |
105799 | import sys
import os
import unittest
import maya.cmds as cmds
import maya.OpenMaya as om
import maya.OpenMayaAnim as oma
import maya.OpenMayaFX as omfx
import pymel.versions
from pymel.util.testing import TestCaseExtended
if not hasattr(cmds, 'about'):
import maya.standalone
maya.standalone.initialize()
#===... |
105802 | import pytest
import supercollider
from tests.shared import server
def test_synth_create(server):
synth = supercollider.Synth(server, "sine", { "freq": 440.0, "gain": -24 })
assert synth.id > 0
synth.free()
def test_synth_get_set(server):
synth = supercollider.Synth(server, "sine", { "freq": 440.0, ... |
105826 | import logging
from asyncio import gather
from virtool.db.utils import get_one_field
from virtool.jobs.db import PROJECTION, cancel
logger = logging.getLogger(__name__)
WORKFLOW_NAMES = (
"jobs_build_index",
"jobs_create_sample",
"jobs_create_subtraction",
"jobs_aodp",
"jobs_nuvs",
"jobs_pat... |
105872 | import sys
import numpy as np
np.set_printoptions(precision=2, threshold=sys.maxsize)
from scipy.linalg import block_diag
from qpsolvers import solve_qp
from util import util
from pnc.data_saver import DataSaver
class IHWBC(object):
"""
Implicit Hierarchy Whole Body Control
------------------
Usage:... |
105876 | from qds_sdk.cloud.cloud import Cloud
class GcpCloud(Cloud):
'''
qds_sdk.cloud.GcpCloud is the class which stores information about gcp cloud config settings.
The objects of this class can be use to set gcp cloud_config settings while create/update/clone a cluster.
'''
def __init__(self):
s... |
105944 | import jinja2
from lib.notify.all_notifiers import get_notifier_class, DEFAULT_NOTIFIER
from logic import user as user_logic
from app.db import with_session
@with_session
def notify_user(user, template_name, template_params, notifier_name=None, session=None):
if notifier_name is None:
notification_prefere... |
105950 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .base import * # pylint: disable=wildcard-import
from .grid_search import * # pylint: disable=wildcard-import
|
105972 | import os
import sys
sys.path.append('../')
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import pygsp as pg
from modules.my_io import readDatasets
from modules import xsphere
# Plotting options
import matplotlib
matplotlib.use('cairo') # Cairo
ma... |
105978 | from formation import fields as F
from formation.field_types import MultiValueField
from formation.fields import get_field_index
from formation.form_base import Form
from formation.forms import county_form_selector
EDITABLE_FIELDS = {
F.ContactPreferences,
F.FirstName,
F.MiddleName,
F.LastName,
F.... |
105979 | from pwn import *
elf=ELF('./binary_200')
#remote server has no elf named binary_200, so we load local elf
r=remote('bamboofox.cs.nctu.edu.tw',22002)
print 'start'
#r=process('./binary_200')
sysadr=elf.symbols['canary_protect_me']
#use gdb to justify canary in args of printf
r.sendline('%15$08x')
print 'leak canary ... |
105995 | from collections import namedtuple
def _namedtuple(typename, field_names):
"""Fixes hashing for different tuples with same content
"""
base = namedtuple(typename, field_names)
def __hash__(self):
return hash((self.__class__, super(base, self).__hash__()))
return type(typename, (base,), {... |
106000 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
__all__ = ['FixupResNet', 'fixup_resnet18', 'fixup_resnet34', 'fixup_resnet50', 'fixup_resnet101', 'fixup_resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_pla... |
106060 | import logging
import psutil
from icrawl_plugin import IHostCrawler
from utils.features import CpuFeature
logger = logging.getLogger('crawlutils')
class CpuHostCrawler(IHostCrawler):
def get_feature(self):
return 'cpu'
def crawl(self, **kwargs):
logger.debug('Crawling %s' % (self.get_feat... |
106077 | import unittest
from collections import namedtuple
from operator import attrgetter, itemgetter
from foil.order import partition_ordered, partition
MockTuple = namedtuple('MockTuple', ('a', 'b'))
def is_even(x):
return True if x % 2 == 0 else False
class TestPartitionOrdered(unittest.TestCase):
def test_... |
106098 | import pytest
from copy import deepcopy
from unittest.mock import patch
from pycliarr.api.radarr import RadarrCli, RadarrMovieItem
from pycliarr.api.exceptions import RadarrCliError
TEST_ROOT_PATH = [{"path": "some/path/", "id": 1},{"path": "yet/otherpath/", "id": 3}]
TEST_JSON = {'somefield': "some value"}
TEST_MOVIE... |
106113 | from sqlalchemy import and_, or_, func
from datetime import datetime
from flask import Blueprint, request, make_response, render_template, flash, g, session, redirect, url_for, jsonify, abort, current_app
from flask.ext.babel import gettext
from dataviva import db, lm, view_cache
# from config import SITE_MIRROR
from ... |
106117 | import random
import torch
from tensorboardX import SummaryWriter
from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy
from plotting_utils import plot_gate_outputs_to_numpy
class Tacotron2Logger(SummaryWriter):
def __init__(self, logdir, hparams):
super(Tacotron2Logger, self).__ini... |
106131 | from WhatsAppManifest.manifest.whatsapp.path import Path
from WhatsAppManifest.automator.whatsapp.database.base import WhatsAppDatabase
class WhatsAppDatabaseWA(WhatsAppDatabase):
"""
WhatsApp WA Database
"""
_database = Path.wa
|
106158 | from flare.algorithm_zoo.distributional_rl_algorithms import C51
from flare.model_zoo.distributional_rl_models import C51Model
from flare.algorithm_zoo.distributional_rl_algorithms import QRDQN
from flare.model_zoo.distributional_rl_models import QRDQNModel
from flare.algorithm_zoo.distributional_rl_algorithms import I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.