id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
72470 | from vehiculo import vehiculo
class autobus(vehiculo):
def tarifaAutobus(self):
return float(vehiculo.tarifa(self)) + ((vehiculo.random * 100) * 0.10)
|
72472 | import os
import tempfile
import shutil
import multiprocessing
import pickle
from copy import deepcopy
from enum import Enum
from typing import Optional, List, Tuple, Dict, Any
from typing_extensions import Literal
import rdkit.Chem as Chem
from ccdc.docking import Docker as DockerGold
from ccdc.io import MoleculeRea... |
72499 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.targets['0.2'] = ""
self.defaultTarget = '0.2'
self.description = "deprecated: use virtual/base instead"
def setDependencies(self):
self.runtimeDependencies["virtual/base"] = None
from Package.VirtualPackag... |
72509 | import os
import zstandard
import json
import jsonlines
import io
import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime.datetime,)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
... |
72518 | import os
from PIL import Image
from math import ceil, sqrt
from .exceptions import CollageOfZeroFramesError
from .utils import does_path_exists
from typing import List
# Module to create collage from list of images, the
# images are the extracted frames of the input video.
class MakeCollage:
"""
Class t... |
72562 | import copy
from proxy import Proxy
class ProxyList(list):
"""
A proxy wrapper for a normal Python list.
A lot of functionality is being reproduced from Proxy. Inheriting Proxy would
simplify things a lot but I get type errors when I try to do so. It is not exactly
clear what a partial copy entail... |
72574 | from jaxrl.agents.awac.awac_learner import AWACLearner
from jaxrl.agents.bc.bc_learner import BCLearner
from jaxrl.agents.ddpg.ddpg_learner import DDPGLearner
from jaxrl.agents.drq.drq_learner import DrQLearner
from jaxrl.agents.sac.sac_learner import SACLearner
from jaxrl.agents.sac_v1.sac_v1_learner import SACV1... |
72577 | import csv
import os
import random
import uuid
import pickle
from multiprocessing import Pool
from collections import Counter
import numpy as np
import imgaug.augmenters as iaa
from PIL import Image
def rotate_save(img, flip, angle, label, new_label_dict, out_dir):
filename = str(uuid.uuid4()) + ".png"
new_l... |
72592 | from typing import List, Optional, Tuple
from django.http import HttpRequest
from django_scim.filters import UserFilterQuery
from zerver.lib.request import RequestNotes
# This is in a separate file due to circular import issues django-scim2 runs into
# when this is placed in zerver.lib.scim.
class ZulipUserFilterQu... |
72606 | from geospacelab import preferences
import geospacelab.datahub.sources.madrigal.utilities as utilities
from geospacelab.datahub import DatabaseModel
class WDCDatabase(DatabaseModel):
def __new__(cls, str_in, **kwargs):
obj = super().__new__(cls, str_in, **kwargs)
return obj
wdc_database = WDCDa... |
72607 | import cv2
import numpy as np
import sys
sys.path.append('build')
import kosutils
from tracker import *
# Setting the dimensions for output window
H = 700
W = 700
dispWindow = np.zeros((H,W,3),dtype=np.uint8)
PREDICTOR_PATH = "../shape_predictor_5_face_landmarks.dat"
# Creating the object for obj3D class
obj1 = kos... |
72643 | from django.conf.urls import url
from .views import TakeLevelView
urlpatterns = [
url(r'^source$', TakeLevelView.as_view(), name='source_examen'),
]
|
72655 | import itertools
from contextlib import suppress
from copy import deepcopy
from pymongo import MongoClient
from tinydb_serialization import SerializationMiddleware
from tinymongo import TinyMongoClient
from tinymongo.serializers import DateTimeSerializer
from tinymongo.tinymongo import generate_id
from quokka.utils.t... |
72718 | import numpy as np
from tsfuse.transformers.uniqueness import *
from tsfuse.data import Collection
def test_has_duplicate_true():
x = Collection.from_array([1, 2, 3, 3])
actual = HasDuplicate().transform(x).values
np.testing.assert_equal(actual, True)
def test_has_duplicate_false():
x = Collection.... |
72722 | from paiargparse import PAIArgumentParser
from tfaip.util.logging import logger
from calamari_ocr.ocr.training.cross_fold_trainer import (
CrossFoldTrainer,
CrossFoldTrainerParams,
)
logger = logger(__name__)
def run():
return main(parse_args())
def parse_args(args=None):
parser = PAIArgumentParse... |
72726 | import sys
import unittest
import pendulum
from src import (
Stocks,
StocksCommandService,
)
from minos.networks import (
InMemoryRequest,
Response,
)
from tests.utils import (
build_dependency_injector,
)
class TestStocksCommandService(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> N... |
72787 | import logging
import os
from typing import Optional, List
import pandas as pd
from .sketch import sketch_fasta, sketch_fastqs
from .parser import mash_dist_output_to_dataframe
from ..utils import run_command
from ..const import MASH_REFSEQ_MSH
def mash_dist_refseq(sketch_path: str, mash_bin: str = "mash") -> str:
... |
72790 | from Screens import PluginBrowser as PBBase
from Screens.InfoBarGenerics import InfoBarNotifications
OriginalPluginBrowser = PBBase.PluginBrowser
if not issubclass(OriginalPluginBrowser, InfoBarNotifications):
class PluginBrowser(OriginalPluginBrowser, InfoBarNotifications):
def __init__(self, *args, **kwargs):
... |
72808 | import json
import os
import pytest
import requests
from tests.acceptance.helpers import ENDPOINT_ACTIVATE
from tests.acceptance.helpers import ENDPOINT_CONFIG
from tests.acceptance.helpers import create_and_validate_request_and_response
from tests.acceptance.helpers import sort_response
expected_activate_ab = """[
... |
72830 | import matlab.engine
import argparse
import torch
from torch.autograd import Variable
import numpy as np
import time, math, glob
import scipy.io as sio
import cv2
parser = argparse.ArgumentParser(description="PyTorch EDSR Eval")
parser.add_argument("--cuda", action="store_true", help="use cuda?")
parser.add... |
72832 | from trading_ig import IGService
from trading_ig.config import config
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# if you need to cache to DB your requests
from datetime import timedelta
import requests_cache
from predefined_functions.initialisation import Initialisation
class... |
72882 | from textbox.data.dataloader.abstract_dataloader import AbstractDataLoader
from textbox.data.dataloader.single_sent_dataloader import SingleSentenceDataLoader
from textbox.data.dataloader.paired_sent_dataloader import PairedSentenceDataLoader
from textbox.data.dataloader.attr_sent_dataloader import AttributedSentenceDa... |
72894 | from records_mover.url.s3.awscli import aws_cli
from mock import patch, call
import unittest
class TestAwsCli(unittest.TestCase):
@patch("records_mover.url.s3.awscli.dict")
@patch("records_mover.url.s3.awscli.os")
@patch("records_mover.url.s3.awscli.create_clidriver")
def test_aws_cli(self,
... |
72895 | from .assetmapper import AssetMapper
from .assetfactory import AssetFactory
from .sqlserver import SqlServerTableMapper
|
72916 | import torch.nn as nn
import torch.nn.functional as F
import params as P
import utils
class Net(nn.Module):
# Layer names
FLAT = 'flat'
FC5 = 'fc5'
RELU5 = 'relu5'
BN5 = 'bn5'
FC6 = 'fc6'
CLASS_SCORES = FC6 # Symbolic name of the layer providing the class scores as output
def __init__(self, input_shape=P.IN... |
72957 | from array_stack import ArrayStack
def delimiter_matched_v1(expr):
"""Return True if all delimiters are properly match; False otherwise.
>>> delimiter_matched_v1('[(2+x)*(3+y)]')
True
>>> delimiter_matched_v1('{[{(xbcd))]}')
False
"""
left, right = '({[', ')}]'
S = ArrayStack()
... |
72984 | import urllib.parse
assert urllib.parse.unquote("foo%20bar") == "foo bar"
import urllib.request
with urllib.request.urlopen('https://httpbin.org/headers') as f:
f.read()
# issue 1424
text = """Hello
World"""
assert urllib.parse.urlencode({"text": text}) == "text=Hello%0AWorld"
print('passed all tests') |
73012 | from hknweb.academics.views.base_viewset import AcademicEntityViewSet
from hknweb.academics.models import Instructor
from hknweb.academics.serializers import InstructorSerializer
class InstructorViewSet(AcademicEntityViewSet):
queryset = Instructor.objects.all()
serializer_class = InstructorSerializer
|
73035 | from sevenbridges.meta.fields import (
StringField, DateTimeField, CompoundField, BooleanField
)
from sevenbridges.meta.resource import Resource
from sevenbridges.models.compound.jobs.job_docker import JobDocker
from sevenbridges.models.compound.jobs.job_instance import Instance
from sevenbridges.models.compound.jo... |
73042 | from ldtcommon import ATTR_SURFACING_PROJECT
from ldtcommon import ATTR_SURFACING_OBJECT
from ldtcommon import TEXTURE_FILE_PATTERN
from ldt import context
from ldtui import qtutils
"""
.. module:: Maya import material
:synopsis: MayaTextureImport Plugin. Imports textureSets to maya Surfacing Projects
.. moduleauth... |
73043 | getObject = {
'id': 37401,
'memoryCapacity': 242,
'modifyDate': '',
'name': 'test-dedicated',
'diskCapacity': 1200,
'createDate': '2017-10-16T12:50:23-05:00',
'cpuCount': 56,
'accountId': 1199911
}
getAvailableRouters = [
{'hostname': 'bcr01a.dal05', 'id': 12345},
{'hostname': ... |
73065 | class FileSystemAuditRule(AuditRule):
"""
Represents an abstraction of an access control entry (ACE) that defines an audit rule for a file or directory. This class cannot be inherited.
FileSystemAuditRule(identity: IdentityReference,fileSystemRights: FileSystemRights,flags: AuditFlags)
FileSystemAuditR... |
73104 | import json
from uuid import UUID
from pymongo import MongoClient
data = {}
def _convertForJson(d):
for k,v in d.items():
if isinstance(v, UUID):
d[k] = str(v)
if isinstance(v, list):
v = [str(s) for s in v]
d[k] = v
return d
db = MongoClient().artifact_databa... |
73121 | import sys
import numpy as np
import pandas as pd
from pspy import so_dict, so_map
d = so_dict.so_dict()
d.read_from_file(sys.argv[1])
binary = so_map.read_map(d["template"])
if binary.data.ndim > 2:
# Only use temperature
binary.data = binary.data[0]
binary.data = binary.data.astype(np.int16)
binary.data[:]... |
73146 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def plot_2ala_ramachandran(traj, ax=None, weights=None):
import mdtraj as md
if ax == None:
ax = plt.gca()
if isinstance(weights, np.ndarray):
ax.hist2d(
md.compute_phi(traj)[1].reshape(-1),
... |
73182 | import sys, getopt
import json
import requests
from pprint import pprint
def handleRequest(argv):
"""Function to read user request, form http message and send it"""
try:
opts, args = getopt.getopt(argv,"",["help","version=","repo=","org=","branch=","user=","apitoken=","updateversion="])
except getopt.GetoptError:... |
73207 | from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.types import Message
from aiogram_dialog import Dialog, Window, DialogManager
from aiogram_dialog.tools import render_transitions
from aiogram_dialog.widgets.input import MessageInput
from aiogram_dialog.widgets.kbd import Next, Back
from aio... |
73220 | import unittest
from lib import Monitor
from cloudasr.test_doubles import PollerSpy
from cloudasr.messages.helpers import *
class TestMonitor(unittest.TestCase):
def setUp(self):
self.poller = PollerSpy()
self.scale_workers = ScaleWorkersSpy()
self.create_poller = lambda: self.poller
... |
73260 | import os
import yaml
import argparse
import datetime
import shutil
parser = argparse.ArgumentParser()
parser.add_argument('--preprocessedoutputdir', type=str, help="intermediate preprocessed pipeline data directory")
parser.add_argument('--trainoutputdir', type=str, help="intermediate training pipeline data directory... |
73264 | import asyncio
import random
import pytest
import uuid
from collections import defaultdict
import aiotask_context as context
@asyncio.coroutine
def dummy3():
yield from asyncio.sleep(random.uniform(0, 2))
return context.get("key")
@asyncio.coroutine
def dummy2(a, b):
yield from asyncio.sleep(random.un... |
73297 | from binaryninja_cortex.platforms import MCU
class Chip(MCU):
NAME="STM32F3"
ROM_OFF=0x08000000
RAM_OFF=0x20000000
IRQ=MCU.IRQ+ [
"NVIC_WWDG_IRQ",
"NVIC_PVD_IRQ",
"NVIC_TAMP_STAMP_IRQ",
"NVIC_RTC_WKUP_IRQ",
"NVIC_FLASH_IRQ",
"NVIC_RCC_IRQ",
"NVIC... |
73313 | from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
from phi.fluidformat import *
def text_to_pixels(text, size=10, binary=False, as_numpy_array=True):
image = Image.new("1" if binary else "L", (len(text)*size*3//4, size), 0)
draw = ImageDraw.Draw(image)
try:
font = ImageF... |
73334 | Experiment(description='Testing the pure linear kernel',
data_dir='../data/tsdlr/',
max_depth=10,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=500, ... |
73335 | import crypt
from base64 import encodestring
try:
from django.conf import settings
_CHARSET = settings.DEFAULT_CHARSET
_LDAP_SALT_LENGHT = settings.LDAP_PASSWORD_SALT_SIZE
except:
_CHARSET = 'utf-8'
_LDAP_SALT_LENGHT = 8
from hashlib import (sha1,
sha256,
s... |
73378 | import json
import logging
from django.http import HttpResponse
from pollaris.app.models import SearchLog
def log_failed_search(request):
"""API route to log searches that failed on FE to the Pollaris DB"""
body = json.loads(request.body)
logging.info(f"Logging failed search: {body}")
address_json =... |
73397 | from conans import ConanFile, CMake, tools
import os
class LibmikmodConan(ConanFile):
name = "libmikmod"
description = "Module player and library supporting many formats, including mod, s3m, it, and xm."
topics = ("libmikmod", "audio")
url = "https://github.com/conan-io/conan-center-index"
homepag... |
73437 | from collections import OrderedDict
class MyObj(object):
b = 1
a = 2
def __init__(self):
object.__setattr__(self, '_attrs', OrderedDict())
self.c = 1
self.d = 2
def __setattr__(self, key, value):
assert key != '_attrs'
self._attrs[key] = value
def __getat... |
73456 | import pytest
from plenum.common.exceptions import MissingNodeOp, InvalidNodeOp
from plenum.common.messages.fields import NonNegativeNumberField, AnyValueField, HexField, BooleanField, Base58Field
from plenum.common.messages.message_base import MessageBase
from plenum.common.messages.node_message_factory import Messag... |
73462 | from ...accounts import Account, account_factory
import tempfile
import os
import pickle
from os import listdir
from os.path import isfile, join
class LocalFileSystemAccountAdapter():
def __init__(self, root=None):
if root is None: root = tempfile.gettempdir()
if not os.path.exists(root+"/accounts... |
73471 | from setuptools import setup, find_packages
from dexy.version import DEXY_VERSION
import platform
is_windows = platform.system() == 'Windows'
if is_windows:
os_specific_requires = []
else:
os_specific_requires = ['pexpect']
setup(
author='<NAME>',
author_email='<EMAIL>',
classifiers=[... |
73486 | import json
import logging.config
import os
import re
from string import Template
from jans.pycloudlib import get_manager
from jans.pycloudlib.persistence import render_couchbase_properties
from jans.pycloudlib.persistence import render_base_properties
from jans.pycloudlib.persistence import render_hybrid_properties
f... |
73496 | import importlib
import sys
import tensorflow as tf
LSTM_SIZE = 2048
def resnet_rnn_model(features, model_params, example_description, training):
# Get hyperparameters
dropout_rate = model_params['resnet_rnn'].get('dropout_rate', 0.5)
# Reshape inputs into proper dimensions
for (name, f), d in zip(... |
73561 | import os, sys
import numpy as np
from math import sqrt
# testing without install
#sys.path.insert(0, '../build/lib.macosx-10.9-x86_64-3.8')
import poppunk_refine
# Original PopPUNK function (with some improvements)
def withinBoundary(dists, x_max, y_max, slope=2):
boundary_test = np.ones((dists.shape[0]))
fo... |
73567 | from Raspi_MotorHAT.Raspi_PWM_Servo_Driver import PWM
class Servos(object):
def __init__(self, addr=0x6f, deflect_90_in_ms = 0.9):
"""addr: The i2c address of the PWM chip.
deflect_90_in_ms: set this to calibrate the servo motors.
it is what a deflection of 90 degrees is
... |
73569 | def verify_format(_, res):
return res
def format_index(body): # pragma: no cover
"""Format index data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result = {
'id': body['id'].split('/', 1)[-1],
'fields': body['fields']
}
... |
73574 | import pandas as pd
def read_clean_csv(path, sep='|'):
"""will read and clean a csv file'"""
df = pd.read_csv(path, sep=sep)
if('Unnamed: 0' in df.columns.values):
df = remove_unnamed(df)
return(df)
def remove_unnamed(df):
df = df.drop('Unnamed: 0', 1)
return df
|
73624 | from .version import __version__
from .scienceworld import ScienceWorldEnv
from .scienceworld import BufferedHistorySaver
|
73642 | import numpy as np
import pickle
"""
The first part of this file is to test if the data.py prepare the data correctly
The second part of this file is to test if the data_FlIC_plus.py prepare the data correctly
"""
### The first part
n_joint = 9 # the number of joint that you want to display
y_test = np.load('y_test_fl... |
73647 | from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
Point2D.__doc__ = 'Represents a 2D Cartesian coordinate'
Point2D.x.__doc__ = 'x-coordinate'
Point2D.y.__doc__ = 'y-coordinate'
print(help(help(Point2D))) |
73692 | from __future__ import print_function
from __future__ import division
import random
import time
import itertools as it
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
from utils import load_data
from train_lstm import LSTM
from train_tdlstm import TDLSTM
from train_tclstm import TC... |
73695 | import torch
from torch import nn
from torch.nn import functional as F
from .activations import sigmoid, HardSwish, Swish
from .utils_i2rnet import (
relu_fn,
round_filters,
round_repeats,
drop_connect,
get_same_padding_conv2d,
Conv2dDynamicSamePadding,
get_model_params,
efficientnet_par... |
73696 | from minos.cqrs import (
CommandService,
)
from minos.networks import (
Request,
Response,
ResponseException,
enroute,
)
from ..aggregates import (
PaymentAggregate,
)
class PaymentCommandService(CommandService):
"""PaymentCommandService class."""
def validate_card(self, card_number:... |
73726 | import torch
from torch.utils.data import Dataset
from random import choice
from pytorch_pretrained_bert import BertTokenizer, BertModel
max_len = 400
device = "cuda:0"
# bert_path = './pretrain/bert-base-chinese/'
# tokenizer = BertTokenizer.from_pretrained(bert_path + 'vocab.txt')
# BERT = BertModel.from_pretrained(... |
73728 | import unittest
from hidden_word import checkio
class Tests(unittest.TestCase):
TESTS = {
"Basics": [
{
"input": [
"""DREAMING of apples on a wall,
And dreaming often, dear,
I dreamed that, if I counted all,
-How many would appear?""",
"... |
73774 | class Rect(object):
def __init__(self, cx, cy, width, height, confidence):
self.cx = cx
self.cy = cy
self.width = width
self.height = height
self.confidence = confidence
self.true_confidence = confidence
def overlaps(self, other):
if abs(self.cx - other.c... |
73784 | from .ReportDaily import *
# Find personal repositories that nonowners are pushing to.
# These repositories should be moved into organizations.
# Only look at active users (not suspended!) and only look at pushes
# of the last 4 weeks.
class ReportReposPersonalNonOwnerPushes(ReportDaily):
def name(self):
return "re... |
73788 | import pandas as pd
import numpy as np
import re
import nltk
from utils.utils import *
import time
from ql_score import ql_score
import pickle
class QL:
alpha = 0.5
mu=1500.
_inverted_index = {}
# data_root = './'
# _term_stats_path = data_root + 'clueweb_stats/term_stats.pkl'
# _term_st... |
73789 | from buidl.bech32 import (
cbor_encode,
cbor_decode,
bc32encode,
bc32decode,
uses_only_bech32_chars,
)
from buidl.helper import is_intable
from binascii import a2b_base64, b2a_base64
from math import ceil
import hashlib
class BCURStringFormatError(RuntimeError):
pass
def bcur_encode(data):... |
73795 | from datetime import datetime
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app import crud
from app.core.security import verify_password
from app.models.domain import Domain
from app.models.event import Event
from app.models.user import User
from app.schemas.user import UserCr... |
73823 | import time
from glob import glob
import subprocess
import os
from odyssey import run_signal_stem, slurm_fname, temp_dir, jobdir
if __name__ == "__main__":
print "Monitoring slurm jobs in {0}".format(os.getcwd())
while True:
for fname in glob(run_signal_stem + "*"):
jobname = fname[len(run_... |
73825 | import unittest
from unittest import mock
from printy.exceptions import InvalidFlag, InvalidInputType
from printy.core import Printy, WINDOWS
from printy.flags import Flags
class TestGlobalFlagsPrinty(unittest.TestCase):
""" Test case for formatting with a global set of flags specified """
def setUp(self):
... |
73826 | import tensorflow as tf
from deepsleep.nn import *
class DeepFeatureNet(object):
def __init__(
self,
batch_size,
input_dims,
n_classes,
is_train,
reuse_params,
use_dropout,
name="deepfeaturenet"
):
self.batch_size ... |
73901 | from concurrent.futures import Future, ThreadPoolExecutor
import logging
from vonx.indy.messages import StoredCredential
from vonx.web.view_helpers import (
IndyCredentialProcessor,
IndyCredentialProcessorException,
)
from api_indy.indy.credential import Credential, CredentialException, CredentialManager
fr... |
73910 | import sys
from unittest.mock import MagicMock
import pytest
from lightning_transformers.core.nlp import HFBackboneConfig, HFTransformerDataConfig
from lightning_transformers.task.nlp.text_classification import (
TextClassificationDataModule,
TextClassificationTransformer,
)
@pytest.mark.skipif(sys.platform... |
73940 | import unittest
import rxbp
from rxbp.flowable import Flowable
from rxbp.multicast.multicast import MultiCast
from rxbp.multicast.multicastsubscriber import MultiCastSubscriber
from rxbp.multicast.multicasts.loopflowablemulticast import LoopFlowableMultiCast
from rxbp.multicast.testing.testmulticast import TestMultiCa... |
73949 | from functools import partial
from itertools import groupby
from couchdbkit import ResourceNotFound
from corehq.apps.domain import SHARED_DOMAIN, UNKNOWN_DOMAIN
from corehq.blobs import CODES
from corehq.blobs.mixin import BlobHelper, BlobMetaRef
from corehq.blobs.models import BlobMigrationState, BlobMeta
from coreh... |
73983 | import os
from setuptools import find_packages, setup
from openwisp_ipam import get_version
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements ... |
73992 | from stack import Stack
class Graph:
def __init__(self):
self.vertices: list = []
self.adjacencyList: dict = {}
self.distance: dict = {}
self.prev: dict = {}
self.colors: dict = {}
self.entry: dict = {}
self.exit: dict = {}
self.time: int = 0
def... |
73993 | import csv
filename = 'ch02-data.tab'
data = []
try:
with open(filename) as f:
reader = csv.reader(f, dialect=csv.excel_tab)
c = 0
for row in reader:
if c == 0:
header = row
else:
data.append(row)
c += 1
except csv.Error a... |
74001 | import contextlib
from datetime import datetime, timedelta
from typing import Iterable, Optional, Tuple, Union
import jwt
with open("tests/key/private_key", "rb") as f:
private_key = f.read()
with open("tests/key/public_key", "rb") as f:
public_key = f.read()
ACCESS_COOKIE_NAME = "access"
REFRESH_COOKIE_NAM... |
74006 | import logging
from mpfmc.tests.MpfMcTestCase import MpfMcTestCase
from unittest.mock import MagicMock, ANY
try:
from mpfmc.core.audio import SoundSystem
from mpfmc.assets.sound import SoundStealingMethod
except ImportError:
SoundSystem = None
SoundStealingMethod = None
logging.warning("mpfmc.core... |
74020 | import time
import dweepy
import RPi.GPIO as GPIO
KEY = 'tweet_about_me'
OUTPUT_PIN = 18
OUTPUT_DURATION = 10
GPIO.setmode(GPIO.BCM)
GPIO.setup(OUTPUT_PIN, GPIO.OUT)
while True:
try:
for dweet in dweepy.listen_for_dweets_from(KEY):
print('Tweet: ' + dweet['content']['text'])
GPIO.o... |
74046 | import cv2, time
#TODO: fix ipcam
#import urllib2, base64
import numpy as np
class ipCamera(object):
def __init__(self,url, user = None, password = None):
self.url = url
auth_encoded = base64.encodestring('%s:%s' % (user, password))[:-1]
self.req = urllib2.Request(self.url)
self.r... |
74067 | import unittest
from rcwa import Source, Layer, Plotter, Crystal, Solver, LayerStack
from rcwa.shorthand import *
from rcwa.testing import *
from rcwa.matrices import *
from rcwa import numpyArrayFromFile, testLocation, numpyArrayFromSeparatedColumnsFile
import numpy as np
class TestSolver(unittest.TestCase):
de... |
74080 | defaults = '''
const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);
const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);
const mat4 mvp = mat4(
-0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,
1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617... |
74103 | from setuptools import setup, find_packages
import crisscross.metadata
with open("README.md", "r") as f:
long_description = f.read()
setup(
name='crisscross',
version=crisscross.metadata.version,
author='pnlng',
description='',
long_description=long_description,
long_description_content_... |
74112 | from deepproblog.utils import check_path
template = """
[Default]
batch_size = {0}
infoloss = {1}
name = poker_batch_{0}_infoloss_{1}
"""
i = 0
check_path("parameter_cfg/0.cfg")
for batch_size in [10, 25, 50, 100]:
for infoloss in [0, 0.5, 1.0, 2.0, 4.0]:
with open("parameter_cfg/{}.cfg".format(i), "w") ... |
74135 | from .quantum_register import QuantumRegister
from .classical_register import ClassicalRegister
import qsy.gates as gates
__version__ = '0.4.4'
|
74149 | from interact import *
def eva_model():
parser = ArgumentParser()
parser.add_argument('--gpt2', action='store_true', help="use gpt2")
parser.add_argument("--model_checkpoint", type=str, default="./models/", help="Path, url or short name of the model")
parser.add_argument("--max_history", type=int, defa... |
74173 | import os
import pytest
import taichi as ti
from taichi import approx
def run_mpm88_test():
dim = 2
N = 64
n_particles = N * N
n_grid = 128
dx = 1 / n_grid
inv_dx = 1 / dx
dt = 2.0e-4
p_vol = (dx * 0.5)**2
p_rho = 1
p_mass = p_vol * p_rho
E = 400
x = ti.Vector.field(... |
74198 | import argparse
import importlib
profiles = {
"core": True,
"legacy": False,
}
applications = {
"pyglet": "application_pyglet",
"pyglfw": "application_pyglfw",
"glut": "application_glut",
}
demos = {
"basic": "scene_basic",
"texturing": "scene_texture",
"... |
74200 | from brownie import *
import json
def main():
thisNetwork = network.show_active()
if thisNetwork == "development":
acct = accounts[0]
# configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "testnet" or thisNetwork == "rsk-mainnet":
acct = a... |
74249 | from kivy.animation import Animation
from kivy.clock import Clock
from kivy.lang.builder import Builder
from kivy.properties import (
BooleanProperty,
ListProperty,
NumericProperty,
OptionProperty,
StringProperty,
)
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemableBehavio... |
74261 | import FWCore.ParameterSet.Config as cms
siTrackerMultiRecHitUpdator = cms.ESProducer("SiTrackerMultiRecHitUpdatorESProducer",
ComponentName = cms.string('SiTrackerMultiRecHitUpdator'),
TTRHBuilder = cms.string('WithAngleAndTemplate'),
HitPropagator = cms.string('trackingRecHitPropagator'),
#AnnealingP... |
74268 | import numpy as np
from typing import Callable
from .base_score import BaseScore
class BleiLaffertyScore(BaseScore):
"""
This score implements method described in 2009 paper
Blei, <NAME>., and <NAME>erty. "Topic models." Text Mining.
Chapman and Hall/CRC, 2009. 101-124.
At the core this score he... |
74285 | from setuptools import setup
with open("README.md") as f:
long_description = f.read()
setup(
name="prefixdate",
version="0.4.0",
description="Formatting utility for international postal addresses",
long_description=long_description,
long_description_content_type="text/markdown",
url="http... |
74289 | from fabric.api import local, task
@task
def bower(command, args='', option=''):
"""
usage: fab bower:<command>, <args>, <option>
Execute bower commands.
See 'fab bower:help' for more information
"""
local('cd {{ project_name }} && bower {0} {1} {2}'.format(
command,
args,
... |
74319 | from flask import Flask, jsonify, request
from flask.views import MethodView
app = Flask(__name__)
languages = [{'name' : 'JavaScript'}, {'name' : 'Python'}, {'name' : 'Ruby'}]
def get_language(name):
return [language for language in languages if language['name'] == name][0]
class Language(MethodView)... |
74329 | import cPickle as pkl
import gzip
import os
import re
import sys
import numpy
import math
import random
from binary_tree import BinaryTree
def convert_ptb_to_tree(line):
index = 0
tree = None
line = line.rstrip()
stack = []
parts = line.split()
for p_i, p in enumerate(parts):
# openin... |
74343 | import argparse
import baselineUtils
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
import os
import time
from transformer.batch import subsequent_mask
from torch.optim import Adam,SGD,RMSprop,Adagrad
from transformer.noam_opt import NoamOpt
import numpy as np
import scipy.io... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.