id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3301295 | import os
import numbers
import torch
import torch.utils.data as data
import torch
import torchvision.transforms as transforms
import random
from PIL import Image, ImageOps
import numpy as np
import torchvision
from . import exp_transforms
import pdb
import cv2
from utils.flowlib import read_flow
from utils.util_flow i... |
3301336 | import json
import random
import time
from lib.Cb_constants.CBServer import CbServer
from lib.membase.api.rest_client import RestConnection
from lib.remote.remote_util import RemoteMachineShellConnection
from pytests.basetestcase import BaseTestCase
from pytests.security.ntonencryptionBase import ntonencryptionBase
fr... |
3301391 | from .rpc_block_digestors import *
from .rpc_dev_digestors import *
from .rpc_log_digestors import *
from .rpc_mining_digestors import *
from .rpc_node_digestors import *
from .rpc_state_digestors import *
from .rpc_submission_digestors import *
from .rpc_transaction_digestors import *
from .rpc_whisper_digestors impor... |
3301416 | from refnx.dataset.data1d import Data1D
from refnx.dataset.reflectdataset import ReflectDataset, OrsoDataset
from refnx._lib._testutils import PytestTester
from refnx._lib import possibly_open_file as _possibly_open_file
test = PytestTester(__name__)
del PytestTester
def load_data(f):
"""
Loads a dataset
... |
3301435 | from auth_helper import *
from campaignmanagement_example_helper import *
# You must provide credentials in auth_helper.py.
def main(authorization_data):
try:
# Setup a campaign with one ad group.
campaigns=campaign_service.factory.create('ArrayOfCampaign')
campaign=set_e... |
3301452 | import ast
import json
import numpy as np
from json.decoder import JSONDecodeError
from struct import unpack, calcsize
from laserchicken.io.utils import convert_to_short_type, convert_to_single_character_type
def read(path):
"""
Read point cloud data from a ply file.
:param path: path to the ply file
... |
3301552 | for _ in xrange(int(raw_input())):
n, a, b = map(int, raw_input().split())
a1, b1 = bin(a)[2:].count("1"), bin(b)[2:].count("1")
cnt = min(a1, n - b1) + min(n - a1, b1)
print int("1" * cnt + "0" * (n - cnt), 2)
|
3301623 | from random import random
from time import sleep
from dbnd import pipeline, task
@task
def fail_randomly(fail_chance=0.5):
"""made to test retry scenarios in the scheduler"""
if random() < fail_chance:
raise Exception("This day I fail")
else:
return "But on this day I succeed!"
@task
d... |
3301626 | from app.models import *
from app.services.steps import Step_VR_3
def test_step_vr3_is_complete_false_with_missing_arguments(app, db_session, client):
"""
Verify that this registrant is not ready to move on to vr3 next step.
"""
form_payload = {}
step = Step_VR_3(form_payload)
assert step.r... |
3301633 | from django.core.management.base import BaseCommand
from hub.models import Hub
class Command(BaseCommand):
def handle(self, *args, **options):
hubs_to_delete = [
# Math
'general mathematics',
'mathematical software',
'statistics theory',
'other ... |
3301641 | from . import vertex_pano, fragment_pano
from . import vertex_line, fragment_line
from . import geometry_line
|
3301660 | from typing import Optional
import torch
import numpy as np
import torch.nn.functional as F
from tqdm import tqdm
from torch.autograd import grad
from torch_geometric.data import Data
from graphwar.attack.targeted.targeted_attacker import TargetedAttacker
from graphwar.surrogate import Surrogate
from graph... |
3301678 | import numpy as np
from .common import delta_lookup, fit_func
from skimage.util import crop, pad
from skimage.transform import resize, warp
npa = np.array
def get_fit_func(fit_mode='quad'):
"""
Gets the fitting function matching the fit_mode ['quad', 'linear', 'exp']
:param fit_mode: choice of the fitting func... |
3301697 | from assemblyline import odm
@odm.model(index=True, store=True)
class Statistics(odm.Model):
count = odm.Integer(default=0)
min = odm.Integer(default=0)
max = odm.Integer(default=0)
avg = odm.Integer(default=0)
sum = odm.Integer(default=0)
first_hit = odm.Optional(odm.Date())
last_hit = od... |
3301701 | from rest_framework import serializers
from attendance.models.FaceId import FaceId
class FaceIdSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = FaceId
fields = '__all__'
|
3301722 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScNovaVenezaSpider(FecamGazetteSpider):
name = "sc_nova_veneza"
FECAM_QUERY = "cod_entidade:177"
TERRITORY_ID = "4211603"
|
3301728 | import logging
import os
import random
import shutil
import subprocess
import sys
import tempfile
import time
from ipaddress import ip_address
import dpkt
import pytest
import deckard
from contrib.namespaces import LinuxNamespace
from networking import InterfaceManager
def set_coverage_env(path, qmin):
"""Sets ... |
3301795 | from distest.exceptions import ResponseDidNotMatchError, UnexpectedResponseError
from re import match
async def assert_message_equals(message, matches):
""" If ``message`` does not match a string exactly, fail the test.
:param discord.Message message: The message to test.
:param str matches: The string t... |
3301886 | from enum import Enum
from collections import namedtuple
from loguru import logger
TorrentStat = namedtuple('TorrentStat', ['status', 'category', 'tracker'])
class TorrentStatus(Enum):
UNKNOWN = 'Unknown'
ALLOCATING = 'Allocating'
DOWNLOADING = 'Downloading'
UPLOADING = 'Upload... |
3301901 | import math
# https://medium.com/@ssbothwell/counting-inversions-with-merge-sort-4d9910dc95f0
def merge_sort_inversions(arr):
if len(arr) == 1:
return arr, 0
else:
a = arr[:math.floor(len(arr)/2)]
b = arr[math.floor(len(arr)/2):]
a, ai = merge_sort_inversions(a)
b, bi =... |
3301904 | import numpy as np
import json
import configure as conf
from collections import OrderedDict
def read_data(input_path, word_idx, if_increase_dict):
seqs = []
graphs = []
if if_increase_dict:
word_idx[conf.GO] = 1
word_idx[conf.EOS] = 2
word_idx[conf.unknown_word] = 3
with open(... |
3301916 | from __future__ import unicode_literals
from datetime import datetime, timedelta
import json
import logging
import requests
try: # pragma: nocover
from urllib.parse import urljoin # 3.x
except ImportError: # pragma: nocover
from urlparse import urljoin # 2.x
from . import exceptions
from . import utils
__... |
3301975 | import os
from juliabox.jbox_util import unquote, JBoxCfg
from juliabox.handlers import JBPluginHandler
from juliabox.db import JBoxUserV2, JBoxDBItemNotFound
from email_verify_tbl import EmailVerifyDB
__author__ = 'barche'
class EmailWhitelistHandler(JBPluginHandler):
provides = [JBPluginHandler.JBP_HANDLER,
... |
3301984 | from clld.web.maps import ParameterMap, Map, Layer, CombinationMap
from clld.web.util.helpers import JS, map_marker_img
from wals3.adapters import GeoJsonLects
class FeatureMap(ParameterMap):
def get_options(self):
return {
'icon_size': 20,
'max_zoom': 9,
'worldCopyJum... |
3302007 | from glob import glob
nImages = 0;
images = None;
nPixels = None;
averageImagef = None
averagedPixelColors = None;
#======================================
def setup():
global nPixels
size(240, 240);
nPixels = width*height;
initializeArrays();
loadImages();
computeAverageImage();
#======================... |
3302022 | import hashlib
import json
from ocean_provider.constants import BaseURLs
from ocean_provider.utils.services import Service
def get_access_service(address, metadata, diff_provider=False):
access_service_attributes = {
"main": {
"name": "dataAssetAccessServiceAgreement",
"creator": ... |
3302033 | from setuptools import setup, find_packages
setup(
name="been",
description="A life stream collector.",
version="0.1",
author="<NAME>",
author_email="<EMAIL>",
keywords="feed lifestream",
license="BSD",
classifiers=[
"Programming Language :: Python",
"Topic :: Internet :... |
3302035 | def add_custom_templates_directory(templates_setting, directory_path):
dirs = templates_setting[0].get('DIRS', [])
if 'directory_path' in dirs:
return
dirs.append(directory_path)
|
3302048 | import os
FAKE_PATH = "foobarbaz"
FIXTURE_PATH = "fixtures/has_executables"
TEST_APP = "Foo.app"
TEST_DIR = "tmp"
SOURCE_DIR = os.path.join(TEST_DIR, TEST_APP)
|
3302075 | from mod_python import apache
import sys, os, tempfile, urllib
from WebUtils import General
General._version = "1.0.0"
def page(req, smiles='', width=300, height=300, highlight='[]', numbers=0, **kwargs):
req.content_type = 'text/html'
page = General.ConstructHtmlHeader(title='RD Depict')
if smiles:
uSmil... |
3302079 | import sqlite3
class OperateSQL():
def __init__(self,path,logger):
self.path = path
self.logger = logger
def getConn(self):
try:
self.conn = sqlite3.connect(self.path)
except sqlite3.Error as err:
self.logger.info(err)
return
def updateSms(se... |
3302098 | import pytest
from aioelasticsearch import (AIOHttpConnectionPool, Elasticsearch,
ImproperlyConfigured)
from aioelasticsearch.pool import DummyConnectionPool
@pytest.mark.run_loop
async def test_mark_dead_removed_connection(auto_close, es_server, loop):
es = auto_close(Elasticsearch... |
3302115 | from pymatgen.analysis.local_env import VoronoiNN
import numpy as np
from itertools import product
from pymatgen.core.structure import Structure, IStructure
from pymatgen.core.periodic_table import Element, Specie
from pymatgen.core.bonds import get_bond_length
from pymatgen.analysis.local_env import get_neighbors_of_s... |
3302155 | from ..config import *
def privateruc(linecod):
s = linecod
b = s.b
b != 'private :: '
for t in s.atomic_target:
b != t
b != ', '
b.rstrip(', ')
b != s.newline |
3302161 | from rlzoo.algorithms.sac.sac import SAC
from rlzoo.common.policy_networks import *
from rlzoo.common.value_networks import *
import gym
""" load environment """
env = gym.make('Pendulum-v0').unwrapped
# env = DummyVecEnv([lambda: env]) # The algorithms require a vectorized/wrapped environment to run
action_s... |
3302209 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from redis.asyncio.client import Pipeline, Redis
def from_url(url, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
... |
3302224 | from sqlalchemy import create_engine, and_
from sqlalchemy.orm import sessionmaker
from audiocrawl.spiders.t_models import *
# from t_models import AudioDetaiListlDb
from audiocrawl.spiders.t_models import *
def connect():
engine = create_engine('sqlite:///crawl.sqlite', echo=True)
Session = sess... |
3302225 | import re
from random import randint
from typing import Any
from typing import Dict
from typing import List
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._animation.animation_base import AnimationBase
from apysc._event.custom_event_type impor... |
3302277 | import pandas as pd
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.linear_model import Perceptron
from sklearn.linear_model import RidgeClassifier
from sklearn.linear_model import SGDClassifier
from ... |
3302314 | from asyncmy.structs import B
def byte2int(b):
if isinstance(b, int):
return b
else:
return B.unpack(b)[0]
def int2byte(i: int):
return B.pack(i)
|
3302356 | import unittest
import irctokens
class DecodeTestPartial(unittest.TestCase):
def test(self):
d = irctokens.StatefulDecoder()
lines = d.push(b"PRIVMSG ")
self.assertEqual(lines, [])
lines = d.push(b"#channel hello\r\n")
self.assertEqual(len(lines), 1)
line = irctoken... |
3302372 | from rubicon_ml.client.asynchronous.config import Config
from rubicon_ml.client.asynchronous.mixin import ( # noqa F401
ArtifactMixin,
DataframeMixin,
TagMixin,
)
from rubicon_ml.client.asynchronous.artifact import Artifact
from rubicon_ml.client.asynchronous.dataframe import Dataframe
from rubicon_ml.cl... |
3302418 | import torch
'''
def onehot(x, max_size):
hot = torch.FloatTensor(*x.shape, max_size).to(x.device)
x = x.unsqueeze(-1)
hot.zero_()
hot.scatter_(-1, x, 1)
return hot.detach()
'''
def find_first(t, value=0):
# t: 1d tensor
mask = t == value
mask = mask.nonzero()
val = mask.sort()[0]... |
3302420 | import os
import random
import logging
import torch
import numpy as np
from transformers import (
BertConfig,
DistilBertConfig,
ElectraConfig,
BertTokenizer,
ElectraTokenizer,
BertForSequenceClassification,
DistilBertForSequenceClassification,
ElectraForSequenceClassification
)
from to... |
3302432 | from . import UuidUtil
import json
from .hci_socket import Emit
class BlenoPrimaryService(dict):
def __init__(self, options):
super(BlenoPrimaryService, self).__init__()
self['uuid'] = UuidUtil.removeDashes(options['uuid'])
self['characteristics'] = options['characteristics'] if 'character... |
3302439 | import os
import platform
import re
import signal
import subprocess
import sys
import ShUtil
import Util
kSystemName = platform.system()
class TestStatus:
Pass = 0
XFail = 1
Fail = 2
XPass = 3
Invalid = 4
kNames = ['Pass','XFail','Fail','XPass','Invalid']
@staticmethod
def getName(c... |
3302464 | import logging
import json
import traceback
from django.http import HttpResponse, HttpResponseForbidden, QueryDict
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from zipfelchappe.views import requires_pledge
from zipfelch... |
3302503 | import json
import copy
import random
import argparse
import pdb
def parse_args():
parser = argparse.ArgumentParser('Random down-sample json file', add_help=False)
parser.add_argument('--input_file', default='instances_train2017.json', type=str)
parser.add_argument('--sample_num', default=None, type=int)
... |
3302512 | import torch
import mxnet as mx
import numpy as np
from gluon2pytorch import gluon2pytorch
class AvgPoolTest(mx.gluon.nn.HybridSequential):
def __init__(self, pool_size=2, padding=0):
super(AvgPoolTest, self).__init__()
from mxnet.gluon import nn
with self.name_scope():
self.co... |
3302538 | from mod2 import *
class A:
a = 1
def f(x):
print x.a
def g(y):
print y+
o = B()
print B.a
|
3302572 | import os
import sys, getopt, argparse
import logging
import json
import time
import requests
class BadCallError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class LatencyTest(object):
def __init__(self):
self.latency_sum = ... |
3302592 | import textwrap
from todo.utils import get_terminal_size
from .base import Render
class RenderOutputWithTextwrap(Render):
def __init__(self, prefix, text_to_wrap):
self.prefix = prefix
self.text_to_wrap = text_to_wrap
def render(self, **kwargs):
kwargs.setdefault("subsequent_indent"... |
3302616 | from _utils import _gen_layer_name, _torch_typename
def _convert_sequential(builder, name, layer, input_names, output_names):
layers = layer.modules
n = len(layers)
inputs = input_names
for i in range(n):
l_ = layers[i]
l_outputs = None
l_name = _gen_layer_name(l_)
if... |
3302621 | from fabric.api import hide, run, env
import time
import json
def run_cmd(cmd):
with hide('output', 'running', 'warnings'):
return run(cmd, timeout=1200)
def check(**kwargs):
''' Login over SSH and execute shell command '''
jdata = kwargs['jdata']
logger = kwargs['logger']
env.gateway = j... |
3302634 | import re
from typing import Pattern
from faker.providers.bank.ru_RU import Provider as RuRuBankProvider
from faker.providers.credit_card import Provider as CreditCardProvider
class TestCreditCardProvider:
"""Test credit card provider methods"""
mastercard_pattern: Pattern = re.compile(
r'(?:5[1-5][... |
3302668 | import time
import pytest
from datetime import datetime
from osf_tests.factories import (
PreprintFactory,
AuthUserFactory
)
from osf.metrics import PreprintDownload
from api.base.settings import API_PRIVATE_BASE as API_BASE
@pytest.fixture()
def preprint():
return PreprintFactory()
@pytest.fixture()
d... |
3302671 | from unittest.mock import MagicMock
from belvo import resources
def test_statements_create(api_session):
statements = resources.Statements(api_session)
statements.session.post = MagicMock()
statements.create("fake-link-uuid", "fake-account-uuid", "2019", "12", attach_pdf=True)
statements.session.pos... |
3302711 | from future.utils import viewitems
import cherrypy
from os import listdir
from cherrypy import expose, tools
from WMCore.WebTools.FrontEndAuth import get_user_info
from WMCore.WebTools.Page import TemplatedPage
class SecureDocumentation(TemplatedPage):
"""
The documentation for the framework
"""
@... |
3302777 | import colorsys
import svgpathtools
def generate_color(hue, saturation=1.0, value=1.0):
rgb = colorsys.hsv_to_rgb(hue, saturation, value)
return "rgb({},{},{})".format(*[int(x * 255) for x in rgb])
def visualize_pen_transits(paths, svg_file):
# We will construct a new image by storing (path, attribute)... |
3302779 | from rest_framework import permissions
class UserPermissions(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
"""
Checks permissions
"""
has_action_permission... |
3302800 | mask = pd.to_datetime(survey_data_decoupled[["year", "month", "day"]], errors='coerce').isna()
trouble_makers = survey_data_decoupled[mask] |
3302810 | from showml.deep_learning.layers import Activation
import numpy as np
class Sigmoid(Activation):
"""A layer which applies the Sigmoid operation to an input.
"""
def forward(self, X: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-X))
def backward(self, X: np.ndarray) -> np.ndarray:
... |
3302811 | import itertools
import logging
from .constants import (SEVERITY_DICT, HGNC_TO_OMIM, CYTOBANDS)
from phizz.utils import (query_gene, query_gene_symbol)
from puzzle.models import Gene
logger = logging.getLogger(__name__)
def get_variant_id(variant):
"""Get a variant id from a cyvcf variant
Build a v... |
3302878 | import gzip
import os
import glob
for name in glob.glob('htmls/*'):
print(name)
sha = name.split('/').pop()
html = gzip.compress(bytes(open(name, 'r').read(),'utf8'))
#open('../../sdb/' + sha, 'wb').write( html )
#os.remove(name)
open(name, 'wb').write(html)
|
3302912 | def a():
i = 0
j = b(i)
return j
def b(z):
k = 5
if z == 0:
c()
return k / z
def c():
error()
a()
#https://pt.stackoverflow.com/q/163630/101
|
3302937 | import multiprocessing
import os
import subprocess
from setuptools import setup, find_packages, Command
from setuptools.command.build_ext import build_ext as _build_ext
class build_ext(_build_ext):
def run(self):
self.run_command('cmake')
_build_ext.run(self)
class build_cmake(Command):
des... |
3302970 | from __future__ import print_function
import unittest
import numpy as np
from SimPEG.data import Data
from SimPEG.potential_fields import gravity, magnetics
from SimPEG.electromagnetics.static import resistivity as dc
from SimPEG.utils.io_utils import (
write_grav3d_ubc,
read_grav3d_ubc,
write_gg3d_ubc,
... |
3303085 | import time
from studio import logs
logger = logs.get_logger('helloworld')
logger.setLevel(10)
i = 0
while True:
logger.info('{} seconds passed '.format(i))
time.sleep(1)
i += 1
|
3303086 | import numpy as np
from scipy.ndimage.filters import gaussian_filter
from scipy.stats import mode
from .libcudawrapper import deskewGPU as deskew
from .util import imread
def threshold_li(image):
"""Return threshold value based on adaptation of Li's Minimum Cross Entropy method.
From skimage.filters.thresho... |
3303109 | import plotly.graph_objs as go
from _plotly_utils.basevalidators import ColorscaleValidator
from ._core import apply_default_cascade, init_figure, configure_animation_controls
from .imshow_utils import rescale_intensity, _integer_ranges, _integer_types
import pandas as pd
import numpy as np
import itertools
from plotly... |
3303148 | import math
from PySide import QtCore
from guide import Guide
PI2 = 2 * math.pi
class GuideCircle(Guide):
CW = 1
CCW = -1
def __init__(self, rect, startAngle=0.0, span=360.0, dir=CCW, follows=None):
super(GuideCircle, self).__init__(follows)
self.radiusX = rect.width() / 2.0
... |
3303179 | import scipy.signal
import numpy as np
import math
class SoundEnvirenment:
"""
Emulates the envirenment. Method run(...)
gets samples to render with loadspeaker and returns measured
sample from a microphone.
"""
def __init__(self, ir, Fs=44100):
self.Fs = Fs
# self.Hspeaker = n... |
3303182 | from office365.runtime.client_value import ClientValue
class SiteCreationDefaultStorageQuota(ClientValue):
pass
|
3303209 | import pytest
@pytest.mark.django_db
def test_automatic_slug(post_factory):
post = post_factory(slug=None)
assert post.slug
|
3303234 | import pandas as pd
special_dict_r1 = {"&#39,s": "'", "´": "'", "->": ""}
special_dict_r2 = {
"(s)": "s",
"'": "'",
"lt;": "",
";lt": "",
"gt;": "",
";gt": "",
"\'": "'",
""": "",
"&": " and ",
"’": "'",
"é": "'",
"\n": " ",
"\t": " ",
"-l... |
3303237 | from analyzer.syntax_kind import SyntaxKind
class MethodStatementSyntax:
def __init__(self, declaration_keyword, identifier, parameter_list, export):
if declaration_keyword.kind == SyntaxKind.FunctionKeyword:
self.kind = SyntaxKind.FunctionStatement
else:
self.kind = Syntax... |
3303240 | from django.test import override_settings
from django.urls import reverse
class TestSettings:
@override_settings(COMPRESS_ENABLED=True)
def test_compression(self, django_app, volunteer):
response = django_app.get(reverse("core:index"), user=volunteer)
assert response.status_code == 200
|
3303275 | import mxnet as mx
def get_vgg16_rpn():
data = mx.symbol.Variable(name="data")
mean_face = mx.symbol.Variable(name="mean_face")
# confidence map
cls_label = mx.symbol.Variable(name="cls_label")
# projection regression
proj_weight = mx.symbol.Variable(name="proj_weight")
proj_label = mx.... |
3303295 | import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./https/server.crt', keyfile='./https/server.key', server_side=True)
httpd.serve_forever()
|
3303308 | class Solution:
def longestConsecutive(self, nums):
res, items = 0, set(nums)
for num in items:
if num - 1 not in items:
cur = 1
while num + 1 in items:
num, cur = num + 1, cur + 1
if cur > res: res = cur
retu... |
3303345 | from typing import Dict, Optional, Set
from ciphey.iface import Config, ParamSpec, registry
from .ausearch import AuSearch, Node
@registry.register
class Perfection(AuSearch):
@staticmethod
def getParams() -> Optional[Dict[str, ParamSpec]]:
return None
def findBestNode(self, nodes: Set[Node]) -... |
3303367 | hlp = {
# Main Menu
"Initial Setup": """
The initial setup required to proceed with the rest of the migration. This
should be configured first, before anything else. The information in this menu
allows the tool to connect to both Nexus and Artifactory, so that it can
properly configure and execute the migration... |
3303385 | from setuptools import setup
import nanorm
try:
long_description = open('README.md').read()
except Exception as e:
long_description = ''
setup(
name='nanorm',
py_modules=['nanorm', 'nanorm_test'],
version=nanorm.__VERSION__,
keywords='orm namo mini sample database sqlite nanorm nanoorm',
... |
3303389 | import numpy as np
color1 = np.array([19,163,255.])
color2 = np.array([19,18,37.])
color3 = np.array([52,2,1.])
color4 = np.array([.95,.95,.95])
color5 = np.array([.5,.15,.4])
color1/=255.
color2/=255.
color3/=255.
def clip(i,imax=1,imin=0):
return min(max(imin,i),imax)
def directmix(c1,c2,ratio):
return c... |
3303397 | from django.utils.functional import cached_property
from waldur_mastermind.booking.utils import TimePeriod, get_offering_bookings
from waldur_mastermind.google.backend import GoogleCalendar
class SyncBookingsError(Exception):
pass
class SyncBookings:
def __init__(self, offering):
self.offering = of... |
3303425 | from submission import Submission
class MathieuSubmission(Submission):
def run(self, s):
banks = [int(x) for x in s.split('\t')]
n = len(banks)
history = dict()
cycle=0
tpl_banks=tuple(banks)
while tpl_banks not in history.keys():
history[tpl_banks]=cycl... |
3303471 | import ctypes
import socket
import logging
logger = logging.getLogger(__name__)
class sockaddr(ctypes.Structure):
_fields_ = [
("sa_family", ctypes.c_short),
("_p1", ctypes.c_ushort),
("ipv4", ctypes.c_byte * 4),
("ipv6", ctypes.c_byte * 16),
("_p2", ctypes.c_ulong)
]
... |
3303495 | from typing import Optional
from refactor.tilde_essentials.evaluation import TestEvaluator
from refactor.tilde_essentials.split_criterion import SplitCriterionBuilder
from refactor.tilde_essentials.test_generation import TestGeneratorBuilder
from refactor.tilde_essentials.tree_node import TreeNode
class SplitInfo:
... |
3303569 | import setuptools
with open("README.md", encoding="utf-8") as f:
readme = f.read()
setuptools.setup(
name="tglogging",
version="0.0.4",
author="subinps",
description="A python package to stream your app logs to a telegram chat in realtime.",
long_description=readme,
long_description_conten... |
3303574 | from __future__ import absolute_import
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
import os
from .myconfigparser import MyConfigParser
from .loadcolormaps import loadcolormaps
from gputools import init_device
__CONFIGFILE__ = os.path.expanduser("~/.spimagine")
config... |
3303600 | import os
import re
import cv2
import torch
import numpy as np
import Polygon as plg
from PIL import Image
from collections import OrderedDict
from matplotlib import patches
from matplotlib import font_manager as fm
from matplotlib import pyplot as plt
def read_txt(txt_path):
txt_contents = []
f = open(txt_p... |
3303605 | from django.test import TestCase
from common.helpers.redirectors import InvalidArgumentsRedirector, DirtyUrlsRedirector, DeprecatedUrlsRedirector
class RedirectorTests(TestCase):
def test_InvalidArgumentsRedirector(self):
invariants = ['/my/projects?projectAwaitingApproval=Project%202', '/']
test... |
3303624 | import os
import math
import subprocess, time
import argparse
from argparse import RawTextHelpFormatter
from subprocess import call
global bed_file
global outdir
global outfilename
global temp_out
global testsamplename
global SAMTOOLS
global BCFTOOLS
global REF
global bam_list
glob_scores = dict() ... |
3303645 | import os
import dj_database_url
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:")
DATABASES = {
"default": dj_database_url.parse(DATABASE_URL),
}
INSTALLED_APPS = ("django_dbq",)
SECRET_KEY = "<KEY>"
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"handlers": {"conso... |
3303654 | import configparser
import json
from fast_arrow import Client, OptionOrder
print("----- running {}".format(__file__))
config = configparser.ConfigParser()
config.read('config.debug.ini')
#
# get auth_data (see https://github.com/westonplatter/fast_arrow_auth)
#
with open("fast_arrow_auth.json") as f:
auth_dat... |
3303677 | from __future__ import unicode_literals
import copy
from datetime import timedelta
import django
from django.test import TestCase
from django.utils.timezone import now
from batch.definition.definition import BatchDefinition
from batch.test import utils as batch_test_utils
from batch.models import Batch
from job.mode... |
3303743 | import FWCore.ParameterSet.Config as cms
# this is a minimum configuration of the Mixing module,
# to run it in the zero-pileup mode
#
from SimGeneral.MixingModule.mixObjects_cfi import theMixObjects
from SimGeneral.MixingModule.mixPoolSource_cfi import *
from SimGeneral.MixingModule.digitizersCosmics_cfi import *
mi... |
3303778 | import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class AdaptiveConcatPool2d(nn.Module):
def __init__(self, sz=None):
super().__init__()
sz = sz or (1, 1)
self.ap = nn.AdaptiveAvgPool2d(sz)
self.mp = nn.AdaptiveMaxPool2d(sz)
... |
3303822 | import argparse
import stf_path
from trex_stf_lib.trex_client import CTRexClient
from pprint import pprint
import csv
import math
# sample TRex stateful to chnage active-flows and get results
def minimal_stateful_test(server,csv_file,a_active_flows):
trex_client = CTRexClient(server)
trex_client.start_tre... |
3303849 | n = int(input())
ans = 0
for i in range(1,n+1):
temp = 0
for j in range(1,i+1):
temp += (j*(pow(10,i-j)))
ans+=temp
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.