id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4863920 | from rsqueakvm.error import PrimitiveFailedError
from rsqueakvm.model.compiled_methods import W_CompiledMethod
from rsqueakvm.model.variable import W_BytesObject, W_WordsObject
from rsqueakvm.primitives import expose_primitive, assert_valid_index, index1_0
from rsqueakvm.primitives.constants import *
# _______________... |
4863931 | import xarray as xr
from shapely import geometry
import matplotlib.pyplot as plt
import geopandas as gpd
import rioxarray as rioxr
def row2cell(file, x, y):
minX = file.coords[x].min()
maxX = file.coords[x].max()
minY = file.coords[y].min()
maxY = file.coords[y].max()
poly = geometry.box(minX, minY... |
4864061 | from abc import ABCMeta, abstractmethod
import tools.module_parameters as pars
class BaseTask():
__metaclass__ = ABCMeta
def __init__(self,name):
self.name = name
@abstractmethod
def save(self):
pass
class DataTask(BaseTask):
"""
base module for data setting files (.json)
... |
4864069 | import os, time, unittest, json, asyncio
from aiopyql import data
from tests.main_test import async_test
os.environ['DB_USER'] = 'josh'
os.environ['DB_PASSWORD'] = '<PASSWORD>'
os.environ['DB_HOST'] = 'localhost' if not 'DB_HOST' in os.environ else os.environ['DB_HOST']
os.environ['DB_PORT'] = '3306'
os.environ['DB_NA... |
4864092 | import networkzero as nw0
address = nw0.advertise("reverso")
while True:
message = nw0.wait_for_message_from(address)
nw0.send_reply_to(address, message[::-1])
|
4864102 | import multiprocessing
import time
import redis
import random
import sys
import argparse
from urlparse import urlparse
import os
from itertools import chain
from collections import defaultdict
import math
def ping(r):
r.ping()
def jsonset(r):
r.execute_command('JSON.SET', 'j', '.', '{}')
def runWorker(ctx):
... |
4864116 | from typing import Type
def concretize_abstract_wrangler(abstract_class: Type) -> Type:
"""Makes abstract wrangler classes instantiable for testing purposes by
implementing abstract methods of `BaseWrangler`.
Parameters
----------
abstract_class: Type
Class object to inherit from while ov... |
4864122 | import pyparsing as pp
pp.ParserElement.setDefaultWhitespaceChars(' \t\r')
name = pp.Word(pp.alphanums + '_') | pp.QuotedString('"')
# Literals
string_literal = (
pp.QuotedString("'", escChar="\\")
^ pp.QuotedString('"', escChar="\\")
^ pp.QuotedString("'''", escChar="\\", multiline=True)
)
expression_l... |
4864163 | import numpy as np
import os
import argparse
import pandas as pd
import glob as gb
import pdb
"""
Convert VideoSSL listfiles (rawframes/videos) to mmaction listfile format
"""
np.random.seed(3)
# python convert_videossl_listfiles_to_mmaction_format.py ucf101 --src_listfile_dir /home/jinchoi/src/video-data-aug/da... |
4864168 | import threading
class Fetcher(object):
def __init__(self, c):
assert hasattr(c, 'fetch')
self.c = c
# TODO: temporarily unmount the 'fetch' method to this class
def sync_fetch(self):
"""Executes fetch function, then makes itself basically become
the fetched object"""... |
4864180 | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def can_paginate(self, operation_name: str = None):
"""
C... |
4864182 | import numpy as np
from collections import defaultdict
from sklearn.cluster import KMeans
class Labeller(object):
# get's new node labels
def __init__(self):
self.current = -1 # needs to be -1 so first one is 0
def get_new_node_id(self):
self.current += 1
return str(self.current)
... |
4864258 | import numpy as np
import nifty
#
# Parser for swc skeleton format
# http://research.mssm.edu/cnic/swc.html.
def read_swc(input_path, return_radius=False, return_type=False):
""" Read skeleton stored in .swc
For details on the swc format for skeletons, see
http://research.mssm.edu/cnic/swc.html.
Thi... |
4864307 | from __future__ import annotations
from typing import TYPE_CHECKING
from kubernetes.client import V1Container
from streams_explorer.models.k8s_config import K8sConfig
if TYPE_CHECKING:
from streams_explorer.core.k8s_app import K8sApp
class K8sConfigParser:
"""Base class for parsing configuration of stream... |
4864322 | import numpy as np
from matplotlib import pyplot as plt
import tensorflow.keras.backend as K
from tensorflow.keras import Sequential, Model
from tensorflow.keras.layers import Flatten, Dense, Input, Conv2D, Activation, multiply
from tensorflow.keras.layers import UpSampling2D, ZeroPadding2D, Dropout, Embedding
from t... |
4864357 | from bitmovin_api_sdk.encoding.encodings.muxings.progressive_webm.progressive_webm_api import ProgressiveWebmApi
from bitmovin_api_sdk.encoding.encodings.muxings.progressive_webm.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.encodings.muxings.progressive_webm.information.information_api ... |
4864367 | from . import model
from . import sample_data
def train_epochs(num_epochs=1):
print("Training Mixture RNN for", num_epochs, "epochs")
net = model.MixtureRNN(mode=model.NET_MODE_TRAIN, n_hidden_units=128, n_mixtures=10, batch_size=100, sequence_length=120)
x_t_log = sample_data.generate_data()
loader =... |
4864381 | import os
import pytest
import time
import uuid
from aioresponses import aioresponses
import snappy
from mock import patch
from collections import namedtuple
import responses
import gtmcore
import gtmcore.dispatcher.dataset_jobs
from gtmcore.configuration import Configuration
from gtmcore.dataset.io.manager import IO... |
4864406 | import os
import numpy as np
import pickle
import torchfile # pip install torchfile
# FLAGS(?)
T7_PATH = './resnet-18.t7'
# Open ResNet-18 torch checkpoint
print('Open ResNet-18 torch checkpoint: %s' % T7_PATH)
o = torchfile.load(T7_PATH)
# Load weights in a brute-force way
print('Load weights in a brute-force way'... |
4864415 | import os
import random
import matplotlib.pyplot as plt
import torch
import json
import argparse
import pandas as pd
from tqdm import tqdm
from pprint import pprint
from asteroid.metrics import F1Tracker
from asteroid.binarize import Binarize
from asteroid.models.conv_tasnet import VADNet
from asteroid.data.vad_datas... |
4864429 | import itertools
import random
import sys
from abc import ABC, abstractmethod
from math import cos, fabs, floor, log, pi, sin, sqrt
from typing import Generator, Iterator, List, Optional, Sequence, Tuple
from synthplayer import params
from synthplayer.oscillators import *
class ModSine(Oscillator):
"""Sine Wave ... |
4864449 | from __future__ import annotations
from typing import List, Optional
from opentrons.drivers.asyncio.communication import SerialConnection
from dataclasses import dataclass
from opentrons.hardware_control.emulation.app import (
TEMPDECK_PORT,
THERMOCYCLER_PORT,
SMOOTHIE_PORT,
MAGDECK_PORT,
)
@dataclass... |
4864475 | import tensorflow as tf
import tensorflow_probability as tfp
from scipy.stats import norm
from numpy.linalg import cholesky
import numpy as np
def rmn(rowcov, colcov):
"""
Generate random draws from a zero-mean matrix-normal distribution.
Parameters
-----------
rowcov : np.ndarray
Row cov... |
4864477 | def modified_Seminario_method(inputfilefolder, outputfilefolder, vibrational_scaling):
# Program to implement the Modified Seminario Method
# Written by <NAME>, TCM, University of Cambridge
# Reference using AEA Allen, <NAME>, <NAME>, J. Chem. Theory Comput. (2018), doi:10.1021/acs.jctc.7b00785
#... |
4864494 | import sys
import os
sys.path.append(os.path.abspath("../"))
from unittest import TestCase
from komand_rapid7_insightidr.connection.connection import Connection
from komand_rapid7_insightidr.actions.advanced_query_on_log import AdvancedQueryOnLog
from komand.exceptions import PluginException
import json
import loggin... |
4864497 | import collections
class Solution:
def maxProduct(self, words: List[str]) -> int:
dic = collections.defaultdict(set)
for i in range(len(words)):
for ch in words[i]:
dic[i].add(ch)
res = 0
for i in range(1,len(words)):
for j in range(i)... |
4864549 | from tensorboard import summary
from tensorboard import FileWriter
import numpy as np
def test_log_histogram_summary():
logdir = './experiment/histogram'
writer = FileWriter(logdir)
for i in range(10):
mu, sigma = i * 0.1, 1.0
values = np.random.normal(mu, sigma, 10000) # larger for bette... |
4864565 | import logging, re
from util import constants
from django.apps import apps
class ReactionCompoundMatch(object):
"""A match of a compound in a reaction.
Contains the parsed name (what the user entered), the parsed
stoichiometric coefficient, and a list of matcher.Match objects
of the potential ma... |
4864580 | import sys
sys.path.insert(0, ".")
sys.path.insert(0, "..")
from frag_bitmap import find_missing_tiles, make_bit_list
from gen_bitarray import BitBuffer
if sys.implementation.name != "micropython":
import pytest
def check_bitmaps(bitmaps, expected):
print("bitmaps:", bitmaps)
for i in bitmaps:
bm... |
4864581 | import numpy as np
import cv2
import logging
def get_keypoints_from_indices(keypoints1, index_list1, keypoints2, index_list2):
"""Filters a list of keypoints based on the indices given"""
points1 = np.array([kp.pt for kp in keypoints1])[index_list1]
points2 = np.array([kp.pt for kp in keypoints2])[index_... |
4864582 | import pyblish.api
class IntegrateFtrackComponentOverwrite(pyblish.api.InstancePlugin):
"""
Set `component_overwrite` to True on all instances `ftrackComponentsList`
"""
order = pyblish.api.IntegratorOrder + 0.49
label = 'Overwrite ftrack created versions'
families = ["clip"]
optional = T... |
4864605 | from imageUI import Ui_Dialog
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QLabel, QFileDialog, QMessageBox, QWidget
from PyQt5.QtGui import QPixmap
class My_Ui_Dialog(Ui_Dialog):
myDialog = None
def setupUi(self, Dialog):
super().setupUi(Dialog)
self.myDial... |
4864611 | import argparse
import logging
import mxnet as mx
import os
from cores.io.EvalDataProducer import EvalDataProducer
import cores.symbols.refineNet101 as net
from cores.utils import misc
from cores.utils import metrics
import numpy as np
import time
from PIL import ImageFont
from PIL import Image
from PIL i... |
4864616 | from django.urls import path
from ..test_app.views import ExceptionView, HedgehogView, NoPermissionView
urlpatterns = [
path("hedgehogs", HedgehogView.as_view({"post": "create"})),
path("hedgehogs/<int:pk>", HedgehogView.as_view({"get": "retrieve"})),
path("denied", NoPermissionView.as_view({"get": "list"... |
4864620 | from TextMessage import TextMessage
from TextMessageSender import TextMessageSender
textMessageSender = TextMessageSender()
textMessage = TextMessage(textMessageSender)
# Test for sending message
textMessage.sendMessage("Hi Design Pattern")
# Test for sending another message
textMessage.sendMessage("Hi World!") |
4864621 | def my_protocol(input_packed_pose=None, **kwargs):
"""
Relax the input `PackedPose` object.
Args:
input_packed_pose: A `PackedPose` object to be repacked. Optional.
**kwargs: PyRosettaCluster task keyword arguments.
Returns:
A `PackedPose` object.
"""
import pyroset... |
4864655 | import sys
import traceback
from typing import Any
import discord
from discord.ext import commands
from discord.ext.commands import errors
import bot_config
import errors as cerrors
import functions
class Logging(commands.Cog):
"""Handle logging stuff"""
def __init__(
self,
bot: commands.Bo... |
4864671 | import sys
class Node:
def __init__(self, data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self, root, data):
if root == None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
... |
4864672 | from __future__ import print_function
import sys
import os
os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=all
import copy
import unittest
import logging
import torch
import torch.nn.functional as F
import torch_mlu.core.mlu_model as ct
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(... |
4864679 | from fasteners import (
InterProcessLock,
try_lock,
)
from contextlib import contextmanager
from .path import exists
from ..dochelpers import exc_str
from ..utils import (
ensure_unicode,
get_open_files,
unlink,
)
import logging
lgr = logging.getLogger('datalad.locking')
def _get(entry):
"""... |
4864684 | from configs import user_messages as u_msg, config
class Settings:
def __init__(self, duration, short_break=None, long_break=None, intervals=None):
self.duration = duration
self.short_break = short_break
self.long_break = long_break
self.intervals = intervals
@classmethod
... |
4864707 | from toee import *
from utilities import *
def OnBeginSpellCast( spell ):
print "Meteor Swarm OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
game.particles( "sp-evocation-conjure", spell.caster )
def OnSpellEffect( spell )... |
4864726 | from progressbar import ProgressBar
from grayskull.cli import CLIConfig
from grayskull.cli.stdout import manage_progressbar, print_msg
def test_print_stdout(capsys):
CLIConfig().stdout = True
print_msg("TEST-OUTPUT")
captured_out = capsys.readouterr()
assert captured_out.out == "TEST-OUTPUT\n"
def ... |
4864737 | from aetherling.space_time import *
from aetherling.space_time.type_helpers import valid_ports
from aetherling.space_time.ram_st import DefineRAM_ST
from aetherling.modules.counter import AESizedCounterModM
from aetherling.modules.term_any_type import TermAnyType
from magma import *
from magma.circuit import DefineCirc... |
4864738 | import os
import re
import sys
# amount of cmd line args
if len(sys.argv) != 2:
print("Missing path argument")
exit(1)
# results directory
dir = sys.argv[1]
if not os.path.isdir(dir):
print("unable to find directory: {:s}".format(dir))
exit(1)
participantNamePattern = re.compile("cont_.*\.csv")
outp... |
4864748 | import os
from deepstar.filesystem.frame_set_dir import FrameSetDir
class FrameSetSubDir:
"""
This class implements the FrameSetSubDir class.
"""
@classmethod
def path(cls, frame_set_id):
"""
This method returns the path to a frame set sub directory.
:param int frame_set... |
4864752 | from inliner import transformers, utils
import ast
class FunctionInliner(ast.NodeTransformer):
def __init__(self, functions_to_inline):
self.inline_funcs = functions_to_inline
def visit_Expr(self, node):
node = self.generic_visit(node)
if isinstance(node.value, ast.Assign):
... |
4864790 | import pathlib
import json
import enum
from cvat.apps.engine.models import Task
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from opentpod.object_detector import provider
class Status(enum.Enum):
CREATED = 'created'
TRAINING = 'training'
TRAIN... |
4864807 | def lock_up():
def decorator(func):
setattr(func, "lock", True)
return func
return decorator
|
4864831 | import tensorflow as tf
import numpy as np
def weight(shape):
return tf.get_variable('weight', shape, initializer=tf.contrib.layers.xavier_initializer())
def bias(shape, value=0.1):
return tf.get_variable('bias', shape, initializer=tf.constant_initializer(value))
def Fcnn(x,insize,outsize,name,activation=None,nob... |
4864858 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class UpResBlock(nn.Module):
def __init__(self, ch):
super(UpResBlock, self).__init__()
self.c0 = nn.Conv2d(ch, ch, 3, 1, 1)
nn.init.normal_(self.c0.weight, 0.02)
self.c1 = nn.Conv2d(ch, ch, 3, 1, 1)
... |
4864866 | from dynamicserialize.dstypes.com.raytheon.uf.common.datastorage.records import AbstractDataRecord
class FloatDataRecord(AbstractDataRecord):
def __init__(self):
super(FloatDataRecord, self).__init__()
self.floatData = None
def getFloatData(self):
return self.floatData
def setFl... |
4864891 | from cast.access_log import get_last_request_position
from cast.access_log import get_dataframe_from_position
class TestParseAccesslog:
def test_get_access_log_position(self, access_log_path, last_request_dummy):
position = get_last_request_position(access_log_path, last_request_dummy)
assert posi... |
4864924 | import unittest
import uuid
import numpy as np
from fate_arch.session import computing_session as session
from federatedml.param.statistics_param import StatisticsParam
from federatedml.statistic.data_statistics import DataStatistics
from federatedml.feature.instance import Instance
class TestStatisticCpn(unittest.... |
4864941 | import sys
sys.path.append('/foo/smth.py:module')
def extend_path_foo():
sys.path.append('/foo/smth.py:from_func')
|
4864968 | from . import set_property
from . import show
def init_parser(config_parser):
subparsers = config_parser.add_subparsers(title='hailctl dev config subcommand', dest='hailctl dev config subcommand', required=True)
set_parser = subparsers.add_parser(
'set',
help='Set deploy configuration propert... |
4864995 | from django.shortcuts import render, redirect
from .forms import *
from .models import *
from academic.models import ClassRegistration
def add_department(request):
forms = DepartmentForm()
if request.method == 'POST':
forms = DepartmentForm(request.POST)
if forms.is_valid():
forms... |
4865011 | def df2libffm(df, field_Category, field_Numeric=[]):
libffm = []
num_n = len(field_Numeric)
csr = OneHotEncoder().fit_transform(df[field_Category])
for i in range(len(csr.indptr) - 1):
ls = []
k = csr.indptr[i + 1] - csr.indptr[i]
for j in range(k):
ls.append((k - j +... |
4865037 | from leapp.actors import Actor
from leapp.libraries.actor import sanebackendsmigrate
from leapp.models import InstalledRedHatSignedRPM
from leapp.tags import ApplicationsPhaseTag, IPUWorkflowTag
class SanebackendsMigrate(Actor):
"""
Actor for migrating sane-backends configuration files.
Adds USB quirks f... |
4865040 | from __future__ import absolute_import
import mock
import time
from django.core.cache import cache
from django.core.signals import request_finished
from django.test import TestCase, TransactionTestCase
from modeldict import ModelDict
from modeldict.base import CachedDict
from .models import ModelDictModel
class Mo... |
4865134 | import re
re_host = re.compile("Host:\s*(.*)\r\n")
class CouchDBRouter(object):
# look at the routing table and return a couchdb node to use
def lookup(self, name):
""" do something """
return ("127.0.0.1",5984)
router = CouchDBRouter()
# Perform content-aware routing based on the stream data.... |
4865153 | from rest_framework.reverse import reverse
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from thenewboston.utils.signed_requests import generate_signed_request
from v1.banks.helpers.most_trusted import get_most_trusted_bank
def primary_validator_updated(client, signing_key, validator, status):
... |
4865159 | from globals import *
import life as lfe
import action
import traceback
import logging
import sys
def has_goal(life, name):
return [g for g in life['goals'].values() if g['name'] == name]
def get_active_goals(life):
_active = []
for goal in [g for g in life['goals'].values() if not g['complete']]:
if perfor... |
4865195 | from torch.distributions import Distribution
import torch
from copy import deepcopy
from typing import TypeVar, Callable, Union, Tuple
from torch.nn import Module, Parameter
from abc import ABC
from functools import lru_cache
from .state import NewState
from ..distributions import DistributionWrapper
from ..typing impo... |
4865197 | from django import forms
from .models import Model, ModelLog, Metadata
class ModelForm(forms.ModelForm):
class Meta:
model = Model
fields = ('uid', 'name', 'description', 'url', 'project')
widgets = {
'uid': forms.HiddenInput(),
'project': forms.HiddenInput()
... |
4865206 | import math
import torch
import numpy as np
import pickle as pkl
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from rdkit import Chem
from rdkit.Chem import AllChem
def one_hot_vector(val, lst, add_unknown=True):
if add_unkn... |
4865232 | import io
import json
import logging
import copy
from django.core.files import File
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.base import ModelState
from django.db.models.fields.files import FieldFile
from wagtail.core.models import Page
from wagtail.core.blocks import StreamVal... |
4865263 | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
class ContentTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ContentType
fields = '__all__'
|
4865334 | from __future__ import print_function
import sys
from geneimpacts import VEP
def isfunctional(csq):
if csq['BIOTYPE'] != 'protein_coding': return False
if csq['Feature'] == '' or csq['EXON'] == '': return False
return ("splic" in csq['Consequence']) or any(c in ('stop_gained', 'stop_lost',
... |
4865347 | import unittest
from elliottlib.cli.find_builds_cli import _filter_out_inviable_builds, _find_shipped_builds
from elliottlib.brew import Build
import elliottlib
from flexmock import flexmock
import json
import mock
class TestFindBuildsCli(unittest.TestCase):
"""
Test elliott find-builds command and internal f... |
4865380 | import FWCore.ParameterSet.Config as cms
#Trigger bit requirement
import HLTrigger.HLTfilters.triggerResultsFilter_cfi as hlt
HLTZEROBIASSIGSD = hlt.triggerResultsFilter.clone()
HLTZEROBIASSIGSD.triggerConditions = cms.vstring('HLT_Physics_v*',)
HLTZEROBIASSIGSD.hltResults = cms.InputTag( "TriggerResults", "", "HLT" )... |
4865382 | import torch
from torch_geometric.transforms import TargetIndegree
from torch_geometric.data import Data
def test_target_indegree():
assert TargetIndegree().__repr__() == 'TargetIndegree(cat=True)'
edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]])
data = Data(edge_index=edge_index)
out = Targe... |
4865434 | import random
from itertools import product
from gridworld import *
class QAgent(Agent):
"""
A Q-Learning agent with optimistic initialization.
"""
def __init__(self, num_bandits, epsilon = 0.1, decrease_epsilon = False, alpha = 0.05, decrease_alpha = False, gamma = 1):
Agent.__init__(self, num... |
4865438 | from botocore.exceptions import ClientError
from ..commons import init_logger
class BaseConfig:
def __init__(self, log_level, ssm_interface):
self.log_level = log_level
self._logger = init_logger(__name__, log_level)
self._ssm = ssm_interface
def _fetch_from_event(self):
rais... |
4865446 | import copy
import json
from elasticsearch import ElasticsearchException, TransportError, RequestError, helpers
from ..web import base
from .. import config
from ..auth import require_login, require_superuser
log = config.log
"""
EXAMPLE_SESSION_QUERY = {
"size": 0,
"query": {
"match": {
"_all": "test... |
4865494 | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
return tuple(sorted(A)) == tuple(A) or tuple(sorted(A, reverse=True)) == tuple(A)
|
4865539 | from scripts import vectorize_raster, triangulate_raster, fill_facets
def vectorize(infile, outfile, classes, classfile, weight, nodata, smoothing, bidx, cartoCSS, axonometrize, nosimple, setNoData, nibbleMask, outvar):
vectorize_raster.vectorizeRaster(infile, outfile, classes, classfile, weight, nodata, smoothing... |
4865541 | import pytest
import numpy as np
import healpy as hp
import pysm3
try:
from mpi4py import MPI
except ImportError:
pytest.skip("mpi4py failed to import, skip MPI tests", allow_module_level=True)
@pytest.fixture
def mpi_comm():
comm = MPI.COMM_WORLD
return comm
def test_read_map_mpi_pixel_indices(mpi... |
4865569 | from hydra.experimental import initialize as hydra_init
# Initialize hydra.
hydra_init(config_dir="conf", strict=False)
|
4865575 | import argparse
from typing import List
import torch
import numpy as np
from annoy import AnnoyIndex
from code_search import shared, utils
from code_search.torch_utils import np_to_torch, torch_gpu_to_np, get_device
from code_search.data_manager import DataManager, get_base_languages_data_manager
from code_search.mod... |
4865580 | import configparser
from clint.textui import progress
import os
import conadb
from pyaxmlparser import APK
import os
import urllib.request
import adbutils
from ppadb.client import Client as AdbClient
import time
config = configparser.ConfigParser()
config.read('WSAU.ini')
mslauncherurl = config['MicrosoftLauncher']['U... |
4865611 | from django.contrib import admin
# from mptt.admin import MPTTModelAdmin
from gallery.models import Category, Photo
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {
'slug': ('name', )
}
admin.site.register(Category, CategoryAdmin)
class PhotoAdmin(admin.ModelAdmin):
prepopulated_fiel... |
4865631 | import emacspy_threads, threading, time
emacspy_threads.call_soon_in_main_thread(lambda: print('a'))
emacspy_threads.init()
emacspy_threads.call_soon_in_main_thread(lambda: print('b'))
def test():
time.sleep(1)
emacspy_threads.call_soon_in_main_thread(lambda: print('c'))
emacspy_threads.run_in_main_thread... |
4865647 | from sys import argv
from context import Instpector, endpoints
def get_followers(**options):
instpector = Instpector()
if not instpector.login(user=options.get("user"), password=options.get("password")):
return
followers = endpoints.factory.create("followers", instpector)
for follower in foll... |
4865667 | import pytest
from torch.nn import AvgPool1d as _AvgPool1D
from neuralpy.layers.pooling import AvgPool1D
def test_AvgPool1D_should_throws_type_error():
with pytest.raises(TypeError):
AvgPool1D()
@pytest.mark.parametrize(
"kernel_size, stride, padding, ceil_mode, count_include_pad, name",
[
... |
4865688 | import numpy
from .carlsim import *
from pyNN import common
from . import simulator
from .standardmodels.synapses import StaticSynapse, STDPMechanism
from pyNN.connectors import AllToAllConnector,OneToOneConnector,FixedProbabilityConnector
class Connection(common.Connection):
def __init__(self, group_id1,... |
4865729 | import numpy as np
import igl
from context import gpytoolbox
# Test: 3D Mesh taken from the internet is centered at 0
v,f = igl.read_triangle_mesh("unit_tests_data/bunny.obj")
u = gpytoolbox.normalize_points(v)
# Check that it's centered at zero: max and min should be symmetric
assert(np.all(np.min(u,axis=0)==-np.max... |
4865742 | import os
import logging
log = logging.getLogger('chameleon.config')
environment = dict(
(k[10:], v) for (k, v) in (
((j.lower(), x) for (j, x) in os.environ.items()))
if k.startswith('chameleon_')
)
# Define which values are read as true
TRUE = ('y', 'yes', 't', 'true', 'on', '1')
# If eager parsing... |
4865785 | from sequana.sniffer import sniffer
from sequana import sequana_data
from . import test_dir
def test_sniffer():
assert sniffer(sequana_data("test_measles.sam")) == "SAM"
assert sniffer(sequana_data("test_measles.bam")) == "BAM"
assert sniffer(sequana_data("test_measles.cram")) == "CRAM"
assert sniffer... |
4865814 | from datetime import datetime, timedelta
from functools import lru_cache, wraps
from typing import List, Union
import markdownify as md
from lxml import etree, html
BASE_URL = "https://satori.tcs.uj.edu.pl"
def parse_news(response: str) -> List[str]:
dom = html.fromstring(response)
dom.make_links_absolute(BASE_URL... |
4865913 | from gtmcore.http import ConcurrentRequestManager, ConcurrentRequest
import time
import pytest
import asyncio
class TestAsyncHTTP(object):
def test_resolve_many_200(self):
request1 = ConcurrentRequest('https://jsonplaceholder.typicode.com/todos/1')
arm = ConcurrentRequestManager()
result =... |
4865934 | import torch
from log_lin_connect import *
from torch import nn
class LinearQuant(torch.nn.Linear):
def __init__(self, *args, fsr=7, bitwight=3, lin_back=True, with_sign=True, **kwargs):
super(LinearQuant, self).__init__(*args, **kwargs)
self.quantizer = LogQuant(fsr, bitwight, lin_back, with_sign)... |
4865938 | import os
import numpy as np
from skyportal.tests import api
def test_gcn_GW(super_admin_token, view_only_token):
datafile = f'{os.path.dirname(__file__)}/../data/GW190425_initial.xml'
with open(datafile, 'rb') as fid:
payload = fid.read()
data = {'xml': payload}
status, data = api('POST', ... |
4865941 | import os
import wx
import wx.lib.buttons as buttons
from wx.adv import Animation, AnimationCtrl
from configs.configs import Configs
class Builders(object):
def __init__(self):
self.conf = Configs()
if 'RESOURCEPATH' in os.environ:
self.asset_dir = '{}/assets'.format(os.environ['RESO... |
4865945 | import logging
from discord.utils import parse_time
log = logging.getLogger(__name__)
class Session:
def __init__(self, data):
self._data = data
@property
def session_id(self):
return self._data["session_id"]
@property
def sequence(self):
return self._data["sequence"]
... |
4865958 | import os
import math
import time
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import StepLR
import numpy as np
import config
import scipy as sp
import scipy.stats
from task_generator import TaskGenerator,split_fine_grained_dataset,mini_imagenet_folder... |
4865962 | import numpy as np
import pickle
import os.path as osp
import pyflex
from softgym.envs.rope_env import RopeNewEnv
from copy import deepcopy
from softgym.utils.pyflex_utils import random_pick_and_place, center_object
class RopeFlattenEnv(RopeNewEnv):
def __init__(self, cached_states_path='rope_flatten_init_states.p... |
4865975 | import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.patches as patches
import math
import sys
class SketchPlotter:
"""
A class to read plot the geometry from a json sketch file
"""
def __init__(self, sketch, title = None, opts = None):
"""
Init... |
4866019 | import numpy as np
import multiprocess as multi
from colorspacious import deltaE, cspace_convert
from psutil import virtual_memory
import os, math
from dithermaps import DIFFUSION_MAPS, get_bayer_matrix
from constants import DATA_LOC
import PySimpleGUI as sg
import sg_extensions
def index2rgb(arr, pal)... |
4866053 | import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Containers.Sequential import Sequential
from PuzzleLib.Modules.Conv2D import Conv2D
from PuzzleLib.Modules.Activation import Activation, relu
from PuzzleLib.Modules.MaxPool2D import MaxPool2D
from PuzzleLib.Modules.AvgPool2D import AvgPool2D
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.