id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1698621 | import factory
from colossus.apps.templates.models import EmailTemplate
class EmailTemplateFactory(factory.DjangoModelFactory):
name = factory.Sequence(lambda n: f'campaign_{n}')
class Meta:
model = EmailTemplate
|
1698663 | from .instagram import Instagram
from .instagram_story import InstagramStory
from .weibo import Weibo
from .twitter import Twitter
__all__ = ['Instagram', 'Weibo', 'Twitter', 'InstagramStory'] |
1698668 | from artemis.general.should_be_builtins import all_equal
__author__ = 'peter'
import numpy as np
def is_pareto_efficient_dumb(costs):
"""
:param costs: An (n_points, n_costs) array
:return: A (n_points, ) boolean array, indicating whether each point is Pareto efficient
"""
is_efficient = np.ones(... |
1698708 | from MicroTokenizer import dag_tokenizer
dag_tokenizer.graph_builder.build_graph("二十四口交换机")
dag_tokenizer.graph_builder.write_graphml("output.graphml")
|
1698717 | import pytest
from cryptotik import TheRock
from cryptotik.exceptions import APIError
from decimal import Decimal
import time
private = pytest.mark.skipif(
not pytest.config.getoption("--apikey"),
reason="needs --apikey option to run."
)
rock = TheRock(pytest.config.getoption("--apikey"),
pytest.... |
1698719 | from __future__ import with_statement # this is to work with python2.5
from pyps import workspace
from os import remove
import pypips
filename="partialeval03"
pypips.delete_workspace(filename)
with workspace(filename+".c", parents=[], deleteOnClose=False,name=filename) as w:
m=w['main']
m.partial_eval()
m.display()... |
1698728 | import Package._testcapi
if False:
from Package import EphemeralReference
select = EphemeralReference
select = 123
select = str
|
1698730 | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
choices = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1]
currentSum, currentFactor = 1, 1
for i in range(n):
currentFactor *= choices[i]
currentSum += currentFactor
return currentSum |
1698763 | from typing import NamedTuple
from kfp.components import create_component_from_func, OutputPath
def load_dataset_using_huggingface(
dataset_name: str,
dataset_dict_path: OutputPath('HuggingFaceDatasetDict'),
) -> NamedTuple('Outputs', [
('splits', list),
]):
from datasets import load_dataset
dat... |
1698808 | from flask import Flask, abort, request
import sys,os
sys.path.append('/opt/ngsildAdapter/module')
import json
import pickle
import datetime
import io
import requests
from consts import constant
from LogerHandler import Handler
import logging
class Rest_client:
def __init__(self,url,payload):
self.url=url
... |
1698810 | from packetbeat import BaseTest
import os
"""
Tests for reading the geoip files.
"""
class Test(BaseTest):
def test_geoip_config_disabled(self):
self.render_config_template(
http_ports=[8002],
http_real_ip_header="X-Forward-For",
http_send_all_headers=True,
... |
1698849 | from . import pairwise
from . import losses
from . import objects
from .losses import gmm
from . import phantoms
from . import utils
|
1698874 | def process_input(file_contents):
lines_stripped = [line.strip() for line in file_contents]
octos = [int(i) for lines in lines_stripped for i in lines]
return octos
def iterate_octos(flashes,octos):
flashed = set()
flashed_temp = flashed.copy()
octos = [octo + 1 for octo in octos]
... |
1698879 | import numpy as np
def _make_gaussian(x_pts, y_pts, mfd, x_offset=0, y_offset=0):
x0 = (x_pts[-1]+x_pts[0])/2 + x_offset
y0 = (y_pts[-1]+y_pts[0])/2 + y_offset
xx, yy = np.meshgrid(x_pts, y_pts)
sigma = mfd * 0.707 / 2.355
sigma_x = sigma
sigma_y = sigma
gaus_2d = np.exp(-((xx-x0)**2/(2*s... |
1698897 | import wx
import sys, os
kToolRunMode_Entry = 0
kToolRunMode_Master = 1
kToolRunMode_SblOta = 2
kBootSeqColor_Invalid = wx.Colour( 64, 64, 64 )
kBootSeqColor_Optional = wx.Colour( 166, 255, 255 )
kBootSeqColor_Active = wx.Colour( 147, 255, 174 )
kBootSeqColor_Failed = wx.Colour( 255, 0, 0 )
kConnectStage_Rom ... |
1698925 | from typing import Any, Callable
import httpx
class TransportHandler:
def __init__(self, transport: httpx.BaseTransport) -> None:
self.transport = transport
def __call__(self, request: httpx.Request) -> httpx.Response:
if not isinstance(request.stream, httpx.SyncByteStream): # pragma: nocov... |
1698930 | from models.base_model import BaseModel
from tests.unit.base_interface_test import BaseInterfaceTest
from marshmallow import Schema
class TestBaseModel(BaseInterfaceTest):
def setup(self):
self.object = BaseModel()
self.custom_404_msg = "Base not found"
self.schema = Schema
|
1699004 | from typing import Dict
from UE4Parse.BinaryReader import BinaryStream
class FStringTable:
TableNamespace: str
KeysToMetadata: Dict[str, Dict[str, str]]
def __init__(self, reader: BinaryStream):
self.TableNamespace = reader.readFString()
self.KeysToMetadata = {}
NumEntries = re... |
1699006 | def sort_priority(values, group):
def helper(x):
if x in group:
return 1, x
elif x == 200: # NOTE: 1
return 0, x
else:
return 2, x
values.sort(key=helper)
numbers = [8, 3, 1, 5, 4, 7, 6, 200]
group = {3, 5, 2, 7}
sort_priority(numbers, group)
print(n... |
1699022 | from sklearn.externals.joblib import dump
from sklearn.pipeline import _name_estimators, Pipeline as _Pipeline
from sklearn.utils.metaestimators import if_delegate_has_method
__all__ = ['make_pipeline', 'Pipeline']
def make_pipeline(*steps):
"""Construct a Pipeline from the given estimators. This is a shorthand ... |
1699054 | import tensorflow as tf
import numpy as np
from bregman.suite import *
k = 4
segment_size = 50 # out of 24,526
max_iterations = 100
chromo = tf.placeholder(tf.float32)
max_freqs = tf.argmax(chromo, 0)
def get_chromogram(audio_file):
F = Chromagram(audio_file, nfft=16384, wfft=8192, nhop=2205)
return F.X
d... |
1699126 | from django.test import TestCase
from councils.models import Council
from pollingstations.tests.factories import (
PollingStationFactory,
PollingDistrictFactory,
)
class TestPollingStationFactory(TestCase):
def test_polling_station_factory(self):
station = PollingStationFactory()
self.ass... |
1699146 | import unittest
import pymagsac
#ToDo: add real tests
class MainTest(unittest.TestCase):
def test_fundamental(self):
self.assertEqual(2, 2)
def test_homography(self):
self.assertEqual(2, 0)
if __name__ == '__main__':
unittest.main() |
1699162 | from raco.cpp_datalog_utils import emitCode
from raco.backends.cpp import CCAlgebra
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger(__name__)
if __name__ == "__main__":
query = sys.argv[1]
print query
name = sys.argv[2]
print name
plan = ""
if len(sys.argv) > ... |
1699203 | from notion.block.media import BreadcrumbBlock
from smoke_tests.conftest import assert_block_is_okay
def test_media_block(notion):
pass
# TODO: fix
# block = notion.root_page.children.add_new(MediaBlock)
# assert_block_is_okay(**locals(), type='media')
def test_breadcrumb_block(notion):
block = ... |
1699219 | from compat.functools import wraps as _wraps
from sys import exc_info as _exc_info
class _from(object):
def __init__(self, EXPR):
self.iterator = iter(EXPR)
def supergenerator(genfunct):
"""Implements PEP 380. Use as:
@supergenerator
def genfunct(*args):
try:
... |
1699232 | import envi.symstore.resolver as e_sym_resolv
import unittest
class SymResolverTests(unittest.TestCase):
def setUp(self):
self.symres = e_sym_resolv.SymbolResolver()
def test_sym(self):
fname, base, size, width = ('foo', 0x1234, 0x5678, 4)
fres = e_sym_resolv.FileSymbol(fname, base, s... |
1699255 | from django.contrib import admin
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.views.main import ChangeList
from django.core.paginator import Paginator
from django.template import Context, Template
from django.test import TransactionTestCase
from models import (Child, Par... |
1699281 | from django.conf import settings
from django.http import HttpResponseServerError
from django.template import loader
from django.template.context import RequestContext
from django.views.decorators.csrf import requires_csrf_token
@requires_csrf_token
def server_error(request, template_name='500.html', **param_dict):
... |
1699299 | import unittest
from abpytools import ChainCollection, SequenceAlignment
from . import read_sequence_from_file
class SequenceAlignmentTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.ab_collection_1 = ChainCollection.load_from_file(path='./tests/Data/sequence_alignment_seq_1.json',
... |
1699309 | from .codecs import PackGeneticBits
def create_dask_codec_plugin():
from dask.distributed import WorkerPlugin
class DaskCodecPlugin(WorkerPlugin):
def setup(self, worker):
from numcodecs.registry import register_codec
register_codec(PackGeneticBits)
return DaskCodecPlugin... |
1699325 | import asyncio
import apigpio_fork
import config as conf
from utils import topics, PubSub
from functools import partial
from coroutines import Base
@apigpio_fork.Debounce()
def on_input_forward_to_hub(gpio, level, tick, hub, topic, pi):
hub.publish(topics.TOPIC_BUTTON_PROXY, (gpio, level, tick, topic))
class Pig... |
1699340 | import json, os, csv
# DATE = "2018-05-10"
DATE=None
REVERTED_ONLY = True
JOURNAL_CSV = "/home/richard/tmp/doaj/history/journals.csv"
OUT_DIR = "/home/richard/tmp/doaj/history/workspace/"
def history_records_analyse(source, out_dir, reverted_only=False, date=None):
ids = set()
if date is not None:
... |
1699364 | import os
import sys
import argparse
import torch
import numpy as np
from random import shuffle
from collections import OrderedDict
from dataloaders.datasetGen import SplitGen, PermutedGen
from utils.utils import factory
import random
def run(args):
if not os.path.exists('outputs'):
os.mkdir('outputs')
... |
1699372 | import unittest
from CoolProp.CoolProp import PropsSI
import CoolProp
import numpy as np
def test_input_types():
for Fluid in ['Water']:
for Tvals in [0.5 * PropsSI(Fluid, 'Tmin') + 0.5 * PropsSI(Fluid, 'Tcrit'),
[PropsSI(Fluid, 'Tmin') + 1e-5, PropsSI(Fluid, 'Tcrit') - 1e-5],
... |
1699380 | import unittest
from coba.environments import SimulatedInteraction, LoggedInteraction
class SimulatedInteraction_Tests(unittest.TestCase):
def test_context_none(self):
interaction = SimulatedInteraction(None, (1,2,3), rewards=(4,5,6))
self.assertEqual(None, interaction.context)
def test_cont... |
1699399 | from runners.python import Submission
class XavierSubmission(Submission):
def run(self, s):
s = list(map(int, s.split(",")))
c_list = list(range(256))
cur_pos = 0
skip = 0
for length in s:
buffer = [c_list[(cur_pos + i) % 256] for i in range(length)]
buffer = buffer[::-1]
for i in range(length):
... |
1699403 | from securityheaders.models import SecurityHeader
from securityheaders.models.xpcdp import XPermittedCrossDomainPoliciesDirective
from securityheaders.models.annotations import *
@description('This header defines a cross-domain policy for clients such as Adobe Flash Player or Adobe Acrobat.')
@headername('x-permitted-... |
1699453 | import logging
from typing import Any, Dict, List, Optional
import torch
import torch.nn.functional as F
from overrides import overrides
import numpy as np
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import FeedForward
from allennlp.modules import TimeDistribute... |
1699530 | import flask_whooshalchemy as whooshalchemy
from dataviva import app
from models import Post
whooshalchemy.whoosh_index(app, Post)
|
1699531 | import numpy as np
import pytest
from scipy.stats import halfnorm, invgamma
from skopt.learning.gaussian_process.kernels import RBF, ConstantKernel
from bask.bayesgpr import BayesGPR
@pytest.fixture(params=[False, True])
def minimal_gp(request):
kernel = ConstantKernel(
constant_value=1 ** 2, constant_va... |
1699556 | import datetime
import databases
import pytest
import sqlalchemy as sa
from sqlalchemy import create_engine
import ormar
from tests.settings import DATABASE_URL
metadata = sa.MetaData()
db = databases.Database(DATABASE_URL)
engine = create_engine(DATABASE_URL)
class User(ormar.Model):
class Meta(ormar.ModelMet... |
1699557 | import django
from django.db import connection
from django.core.management import call_command
from .base import BaseCommand
def copy_tmp(tablename):
cursor = connection.cursor()
print('copying data from table ' + tablename)
cursor.execute("DROP TABLE IF EXISTS tmp_{t};".format(t=tablename))
cursor.e... |
1699562 | from typing import List, Optional
from pydantic import Field, BaseModel
from tottle.types.objects.alert import ProximityAlertTriggered
from tottle.types.objects.animation import Animation
from tottle.types.objects.audio import Audio
from tottle.types.objects.chat import Chat
from tottle.types.objects.contact import Co... |
1699586 | import subprocess
from distutils.core import setup, Extension
def pkgconfig(flag, package):
p = subprocess.Popen(['pkg-config', flag, package],
stdout=subprocess.PIPE)
return p.stdout.read().split()
mod = Extension('bulletphysics',
sources=['src/bulletphysics.cpp',
... |
1699600 | import pyparsing
from pyparsing import Word, WordStart, WordEnd, ZeroOrMore, Optional
class reference_patterns:
def __init__(self):
real_word_dashes = Word(pyparsing.alphas + "-")
punctuation = Word(".!?:,;-")
punctuation_no_dash = Word(".!?:,;")
punctuation_reference_letter = Word... |
1699658 | from os import path
from urllib.parse import urlparse
import logging
from scrapy.utils.misc import load_object
from .base_store import BaseStore
logger = logging.getLogger(__name__)
class FileStore(BaseStore):
'''Store class abstracting an input file.
It can handle file stored in the local file system or i... |
1699660 | import unittest
from frag.utils import parser
from frag.utils.parser import _get_c_of_mass_list
from rdkit import Chem
class ParserTest(unittest.TestCase):
water_data = """HETATM 2008 O HOH B 184 53.034 -39.489 96.872 1.00 67.70 O
HETATM 2010 O HOH B 186 39.366 -30.950 88.735 1.00 66.... |
1699667 | import pytest
from busy_beaver.apps.slack_integration.blocks import AppHome
from busy_beaver.common.wrappers.slack import SlackClient
from busy_beaver.config import SLACK_TOKEN
from busy_beaver.exceptions import SlackTooManyBlocks
MODULE_TO_TEST = "busy_beaver.common.wrappers.slack"
@pytest.fixture(scope="module")
... |
1699694 | squares = [i**2 for i in range(5)]
print(squares)
# [0, 1, 4, 9, 16]
squares = []
for i in range(5):
squares.append(i**2)
print(squares)
# [0, 1, 4, 9, 16]
odds = [i for i in range(10) if i % 2 == 1]
print(odds)
# [1, 3, 5, 7, 9]
odds = []
for i in range(10):
if i % 2 == 1:
odds.append(i)
print(odd... |
1699764 | import json
from django.core import management
from django.core.urlresolvers import reverse
from allegation.factories import OfficerFactory, OfficerAllegationFactory
from common.tests.core import SimpleTestCase
class CountViewTestCase(SimpleTestCase):
def test_count_by_num_complaints(self):
self.officer... |
1699783 | from django.core.cache import cache
import contextlib
import time
@contextlib.contextmanager
def lock(key, timeout=5000):
"""
A simple context manager that raises the passed exception
if a lock can't be acquired.
"""
lock_id = 'lock-transmission-{0}'.format(key)
acquire_lock = lambda: cache.a... |
1699851 | from dataclasses import dataclass
from typing import ClassVar, Dict, List, Optional
import resotolib.logger
from resotolib.baseresources import (
BaseAccount,
BaseDatabase,
BaseInstance,
BaseIPAddress,
BaseLoadBalancer,
BaseNetwork,
BaseRegion,
BaseResource,
BaseSnapshot,
BaseVo... |
1699916 | import KratosMultiphysics as KM
import KratosMultiphysics.ShallowWaterApplication as SW
from KratosMultiphysics.time_based_ascii_file_writer_utility import TimeBasedAsciiFileWriterUtility
def Factory(params, model):
if not isinstance(params, KM.Parameters):
raise Exception('expected input shall be ... |
1700005 | import os
from parslepy.base import Parselet
from nose.tools import assert_dict_equal
html = '<html><body><h1>hi</h1><a href="/">click</a></body></html>'
expected = {"title":"hi", "link":"/"}
dirname = os.path.dirname(os.path.abspath(__file__))
def test_parslepy_from_jsonstring():
s = '{ "title": "h1", "link": "... |
1700015 | import o3seespy as o3 # for testing only
def test_plain():
osi = o3.OpenSeesInstance(ndm=2)
ts = o3.time_series.Linear(osi, factor=1.0)
o3.pattern.Plain(osi, ts=ts, fact=1.0)
def test_uniform_excitation():
osi = o3.OpenSeesInstance(ndm=2)
ts = o3.time_series.Linear(osi, factor=1.0)
o3.patte... |
1700017 | def longest_increasing_subarray(a):
A = a + [float('-inf')]
best_s, best_n = 0, 1
s, n = 0, 1
for i in range(len(a)):
if A[i] <= A[i+1]:
n += 1
continue
if n > best_n:
best_s, best_n = s, n
s = i+1
n = 1
return best_s, best_s + best... |
1700056 | from __future__ import division
import scipy.linalg
import autograd.numpy as anp
from autograd.numpy.numpy_wrapper import wrap_namespace
from autograd.extend import defvjp, defvjp_argnums, defjvp, defjvp_argnums
wrap_namespace(scipy.linalg.__dict__, globals()) # populates module namespace
def _vjp_sqrtm(ans, A, dis... |
1700057 | import sys, string
def get_gff_hash(gffile):
hash = {}
fo = open(gffile)
for line in fo:
gf = GeneFeature(line)
if not hash.has_key(gf.seqid): hash[gf.seqid] = []
hash[gf.seqid].append(gf)
fo.close()
return hash
class GeneFeature():
def __init__(self, line):
columns = line.rstrip().spli... |
1700123 | from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings
MAX_LINES = 18
class ProgrammerHelpPlugin(WillPlugin):
@respond_to("^programmer help$")
def help(self, message):
"""programmer help: Advanced programmer-y h... |
1700144 | import tensorflow as tf
import os
import pdb
relu = tf.nn.relu
elu = tf.nn.elu
normal = tf.distributions.Normal
kldv = tf.distributions.kl_divergence
class Network(object):
def __init__(self, name):
self.name = name
self.eps = 1e-3
def dense(self, x, units, name='dense', reuse=None):
... |
1700243 | from teleport import Teleport
import logging
from contextlib import contextmanager
from subprocess import check_call
def _run_commands(commands):
for command in commands:
logging.debug("running command '%s'", " ".join(command))
check_call(command)
def allow_traffic_only_to(address, dns_servers=N... |
1700265 | import tensorflow as tf
from collections import namedtuple
from graph_module import GraphModule
from tensorflow.contrib.rnn.python.ops import rnn
EncoderOutput = namedtuple(
"EncoderOutput",
"outputs final_state attention_values attention_values_length")
class StackedBidirectionalEncoder(GraphModule):
... |
1700281 | from unittest import TestCase
from irlib.preprocessor import Preprocessor, my_nltk
class TestPreprocessor(TestCase):
def setUp(self):
pass
def test_term2ch(self):
p = Preprocessor()
charlist = p.term2ch('help')
self.assertEqual(charlist, ['h', 'e', 'l', 'p'])
de... |
1700284 | import string
import unittest
from ..util import PseudoStr, StrProxy, Object
from .. import tool_imports_for_tests
with tool_imports_for_tests():
from c_analyzer.common.info import (
UNKNOWN,
ID,
)
class IDTests(unittest.TestCase):
VALID_ARGS = (
'x/y/z/spam.c... |
1700327 | Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass
# Definition for singly-l... |
1700329 | import hazelcast
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
client = hazelcast.HazelcastClient()
# Get a Topic called "my-distributed-topic"
topic = client.get_reliable_topic("my-distributed-topic").blocking()
# Add a Listener to the Topic
topic.add_listener(lambda ... |
1700345 | import numpy as np
import pytest
from emukit.examples.fabolas import FabolasModel
@pytest.fixture
def model():
rng = np.random.RandomState(42)
x_init = rng.rand(5, 2)
s_min = 10
s_max = 10000
s = np.random.uniform(s_min, s_max, x_init.shape[0])
x_init = np.concatenate((x_init, s[:, None]), ax... |
1700381 | import argparse
from itertools import count
import numpy as np
import h5py
from traits.api import HasTraits, Range, Instance, Bool, Int, on_trait_change
from traitsui.api import View, Item, HGroup, RangeEditor
from tvtk.api import tvtk
from tvtk.pyface.scene_editor import SceneEditor
from tvtk.common import configure_i... |
1700389 | import logging
from dataclasses import dataclass, field
import click
from .click_common import command
from .miot_device import DeviceStatus as DeviceStatusContainer
from .miot_device import MiotDevice, MiotMapping
from .dreame_const import *
from random import randint
_LOGGER = logging.getLogger(__name__)
class D... |
1700396 | import os
from functools import wraps
from flask import request
from app.vendors.rest import response
def auth_required(f):
"""Decorate given function with authentication check."""
@wraps(f)
def decorated_function(*args, **kwargs):
user_key = request.headers.get("X-API-Key", None)
app_k... |
1700400 | from unittest import TextTestRunner, TestSuite
import JournalTest
import TransactionTest
import PostingTest
suites = [
JournalTest.suite(),
TransactionTest.suite(),
PostingTest.suite()
]
TextTestRunner().run(TestSuite(suites))
|
1700414 | try:
from rpython.rlib.rerased import new_erasing_pair # pylint: disable=unused-import
from rpython.rlib.rerased import erase_int # pylint: disable=unused-import
from rpython.rlib.rerased import unerase_int # pylint: disable=unused-import
except ImportError:
"NOT_RPYTHON"
def new_erasing_pair(na... |
1700479 | def create_dimension_financial_orgs(cursor):
cursor.execute('''CREATE TABLE dimension_financial_orgs
( financial_org_name text,
financial_org_permalink text,
created_at text,
number_of_employees real,
founded_year real,
founded_month real,
... |
1700495 | from pydantic import BaseModel # pylint: disable=no-name-in-module
class Migrate(BaseModel):
enabled: bool
|
1700518 | import torch
import torch.nn as nn
def get_network_for_size(size):
"""
Size is expected to be [channel, dim, dim]
"""
size = list(size) # In case the input is a tuple
if size[-2:] == [7, 7]:
net = ConvNet7x7
elif size[-2:] == [28, 28]:
net = ConvNet28x28
elif size[-2:] == ... |
1700530 | import re
import time
import logging
import datetime
import shutil
import tempfile
from django.db import transaction
from django.utils.encoding import smart_unicode
from jellybaby.models import Item, CodeRepository, CodeCommit
from jellybaby.providers import utils
try:
import git
except ImportError:
git = None... |
1700559 | pkgname = "python-babel"
pkgver = "2.9.1"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-pytz"]
depends = ["python-setuptools", "python-pytz"]
pkgdesc = "Tools for internationalizing Python applications"
maintainer = "q66 <<EMAIL>>"
license = "BSD-3-Clause"
url ... |
1700605 | from contextlib import contextmanager
# copied from https://stackoverflow.com/a/7039175/5692176 (and wrapped in a class)
class TerminalLoadingAnimation:
ANIMATION_CHARACTERS = ["|", "/", "-", "\\"]
def __init__(self, loading_title=None):
self._loading_title = loading_title or ""
self._next_ch... |
1700609 | import os
import socket
import getpass
folders = []
if socket.gethostname() == 'pmous008':
intermediate_folder = os.environ['HOME'] + "/projects/pcad"
slicer_dir = os.environ['HOME'] + "/sources/Slicer-4.8.1-linux-amd64"
elif socket.gethostname() == 'pirads-trainer':
intermediate_folder = os.environ['HOM... |
1700645 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
def scatter_nd_impl(data, indices, updates):
# type: (np.ndarray, np.nd... |
1700673 | import shutil
import subprocess
import sys
import pytest
from numpy.distutils import mingw32ccompiler
@pytest.mark.skipif(sys.platform != 'win32', reason='win32 only test')
def test_build_import():
'''Test the mingw32ccompiler.build_import_library, which builds a
`python.a` from the MSVC `python.l... |
1700679 | from org.transcrypt.stubs.browser import *
# write down any library you need for the client
# this uses Transcrypt to create the javascript library
|
1700684 | from dataclasses import dataclass
import pytest
from dataslots import DataslotsDescriptor, dataslots, DataDescriptor
class PositiveIntegerDS(DataslotsDescriptor):
def __get__(self, instance, owner):
return self.get_value(instance)
def __set__(self, instance, value):
if value < 0:
... |
1700694 | from os import getenv
from river.common.database_connection.db_connection import MSSQL, ORACLE, ORACLE11, POSTGRES
DATABASES = {
MSSQL: {
"host": getenv("TEST_MSSQL_HOST"),
"port": int(getenv("TEST_MSSQL_PORT", 1433)),
"database": getenv("TEST_MSSQL_DB"),
"login": getenv("TEST_MSSQ... |
1700702 | import os
import string
import numpy as np
from PIL import Image
import torch as th
from torchvision.transforms.functional import to_tensor
from . import utils, templates
class FontsDataset(th.utils.data.Dataset):
def __init__(self, root, chamfer, n_samples_per_curve, val=False):
self.root = root
... |
1700704 | import logging
from . import FinishAfter, CompositeExtension
from .training import TrackTheBest
from .predicates import OnLogRecord
logger = logging.getLogger(__name__)
class FinishIfNoImprovementAfter(FinishAfter):
"""Stop after improvements have ceased for a given period.
Parameters
----------
n... |
1700748 | from django import template
from markdown import markdown
register = template.Library()
@register.filter
def md2html(text):
return markdown(text)
@register.simple_tag
def update_param(request, clear_keys='', **kwargs):
items = []
keys_to_remove = [key.strip().lower() for key in clear_keys.split(',')]
... |
1700785 | from typing import List
from pydantic import BaseModel
class BaseGitaModel(BaseModel):
id: int
class Config:
orm_mode = True
class GitaTranslation(BaseGitaModel):
description: str
author_name: str
language: str
class GitaCommentary(BaseGitaModel):
description: str
author_name... |
1700830 | from ploy.common import gzip_string
import base64
import email
import os
class Template(object):
def __init__(self, path, pre_filter=None, post_filter=None):
self.path = path
self.template = email.message_from_file(open(path))
self.pre_filter = pre_filter
self.post_filter = post_fi... |
1700856 | import PortScanner as ps
def main():
# Initialize a Scanner object that will scan top 50 commonly used ports.
scanner = ps.PortScanner(target_ports=50)
host_name = 'google.com'
message = 'put whatever message you want here'
'''
output contains a dictionary of {port:status} pairs
in whic... |
1700868 | from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from .models import Submission, SubmissionComment, SubmissionTag, SubmissionType
class SubmissionCommentInline(admin.TabularInline):
model = SubmissionComment
@admin.register(Submission)
class SubmissionAdmin(admin.ModelAdm... |
1700909 | import secrets
import string
import uuid
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
def user_directory_path(instance, filename):
ext = filename.split(".")[-1]
return f"images/{instance.author.pk}/{uuid.uuid4().hex}.{ext}"
def image_sl... |
1700915 | from __future__ import annotations
import warnings
import numpy as np
import napari
import os
from ..arrays import *
from ..frame import *
from .._const import Const
from ..core import imread, lazy_imread
def copy_layer(layer):
args, kwargs, *_ = layer.as_layer_data_tuple()
# linear interpolation is valid onl... |
1700930 | from arm.logicnode.arm_nodes import *
class PickLocationNode(ArmLogicTreeNode):
"""Pick a location coordinates in the given NavMesh."""
bl_idname = 'LNPickLocationNode'
bl_label = 'Pick NavMesh Location'
arm_version = 1
def arm_init(self, context):
self.add_input('ArmNodeSocketObject', 'Na... |
1700949 | import ipaddress
import socket
def net_family(net):
if isinstance(ipaddress.ip_network(net, strict=False),
ipaddress.IPv6Network):
return socket.AF_INET6
return socket.AF_INET
def _flag6(net):
return '-6' if net_family(net) == socket.AF_INET6 else ''
class NetDev():
DEV_P... |
1700955 | from riemann import tx
from riemann.tx import shared
from riemann import utils as rutils
from btcspv import utils
from typing import List
from btcspv.types import RelayHeader, SPVProof
def validate_vin(vin: bytes) -> bool:
'''Checks that the vin is properly formatted'''
if vin[0] > 0xfc or vin[0] == 0:
... |
1700957 | from peon.src.project.file.function_def.function import FunctionLint
def test_class_constant():
assert FunctionLint.EMPTY_RETURNED_VALUE is True
assert FunctionLint.PYTHON_REFLECTION_EXPRESSIONS == ('type', 'isinstance')
assert FunctionLint.MUTABLE_TYPES == ('set', 'dict', 'list')
|
1700972 | from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.DelaunayMeshingApplication as KratosDelaunay
import KratosMultiphysics.ContactMechanicsApplication as ... |
1700999 | import torch
import torch.nn as nn
class RNNCell(nn.Module):
def __init__(self,n_input, n_hidden):
super(RNNCell,self).__init__()
self.linear1=nn.Linear(n_input+n_hidden, n_hidden)
self.out=nn.Linear(n_hidden, n_hidden)
def forward(self,x,h):
h=torch.cat((h,x), dim=1)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.