id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
478217 | from bitmovin.utils import Serializable
class AutoRestartConfiguration(Serializable):
def __init__(self, segments_written_timeout: float = None, bytes_written_timeout: float = None,
frames_written_timeout: float = None, hls_manifests_update_timeout: float = None,
dash_manifests_u... |
478239 | import argparse
import sys
from .__init__ import __version__
from .svafotate_main import add_annotation
from .pickle_source import add_pickle_source
from .custom_annotations import add_custom_annotation
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
... |
478250 | class Solution:
def removeInvalidParentheses(self, s):
r = []
self.remove(s, r, 0, 0, "()")
return r
def remove(self, s, r, li, lj, c):
cnt = 0
for i, e in enumerate(s[li:], start=li):
cnt += (1, -1, 0)[c.find(e)]
if cnt < 0:
for j... |
478261 | import autolens as al
import pytest
@pytest.fixture(name="dataset_dict")
def make_dataset_dict():
return {
"name": "name",
"positions": [[1, 2]],
"positions_noise_map": [1],
"fluxes": [2],
"fluxes_noise_map": [3],
}
@pytest.fixture(name="dataset")
def make_dataset():
... |
478266 | from amitools.vamos.atypes import Library, LibFlags, NodeType, ExecLibrary
from amitools.vamos.loader import SegList
from amitools.vamos.machine.regs import *
from amitools.vamos.machine.opcodes import op_jmp
class LibFuncs(object):
LVO_Open = 1
LVO_Close = 2
LVO_Expunge = 3
def __init__(self, machi... |
478275 | import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_notification(config, notification):
if "email_notification" not in config:
return
if config["email_notification"]["ssl"]:
smtp = smtplib.SMTP_SSL(config["email_notificatio... |
478279 | import sys, time
import socket
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtCore import QCoreApplication
from threading import Thread
from socketserver import ThreadingMixIn
from demoServer import *
conn=None
class Window(QDialog):
def __init__(... |
478293 | import pytest
from pydantic import ValidationError
from botx.models.buttons import Button, ButtonOptions
class CustomButton(Button):
"""Button without custom behaviour."""
def test_label_will_be_set_to_command_if_none():
assert CustomButton(command="/cmd").label == "/cmd"
def test_label_can_be_set_if_pas... |
478319 | from datetime import datetime
LEVELS = ['trace', 'debug', 'info', 'warn', 'severe']
class Logger():
__slots__ = ['logger', 'level']
# def __init__(self, logger='', level='debug'):
def __init__(self, logger='', level='debug'):
self.level = LEVELS.index(level)
self.logger = logger
def... |
478342 | from django import template
from landing.models import AboutUs, Data, Visualization
register = template.Library()
@register.assignment_tag
def get_aboutus_tag():
return AboutUs.objects.first()
@register.assignment_tag
def get_datalist_tag():
return Data.objects.all().order_by('-added')
@register.assignme... |
478346 | import numpy as np
def segment_list_equal(s1: np.ndarray, s2: np.ndarray) -> bool:
if len(s1) != len(s2):
return False
set1 = {frozenset(tuple(c) for c in s) for s in s1}
set2 = {frozenset(tuple(c) for c in s) for s in s2}
return set1 == set2
|
478354 | import pytest
from elliptic.Kernel.DSL import DSLBuildError, DSLMeta
class TestDSL:
def test_root(self, dsl, mocker):
mocker.patch('elliptic.Kernel.TreeBuilder.TreeBuild.build')
assert not dsl.building
assert not dsl.built
with dsl.root() as root:
assert dsl.building... |
478373 | import random
import slacker
from slackbot import settings
from slackbot.bot import listen_to, respond_to
from slackbot.dispatcher import Message
from ..botmessage import botsend, botwebapi
from .plusplus_model import Plusplus
PLUS_MESSAGE = (
"leveled up!",
"ใฌใใซใไธใใใพใใ!",
"ใใฃใใญ",
"(โีเจ ี)โใฆใงใผใค",
)
... |
478395 | from django.test import TestCase
from .test_template_tags import render_template
class BaseTest(TestCase):
"""Test the IconRenderer."""
def test_icons(self):
self.assertEqual(
render_template('{% icon "" %}'),
"<i></i>",
)
self.assertEqual(
render_... |
478451 | import math
import pandas as pd
from causallearn.utils.ScoreUtils import *
def local_score_BIC(Data, i, PAi, parameters=None):
'''
Calculate the *negative* local score with BIC for the linear Gaussian continue data case
Parameters
----------
Data: ndarray, (sample, features)
i: current inde... |
478469 | from .ignore import ignore # noqa
from .copy import copy # noqa
from .compile_scss import compile_scss # noqa
from .render_html import render_html_factory # noqa
|
478537 | import typing as t
from abc import ABCMeta, abstractmethod
if t.TYPE_CHECKING:
from typing_extensions import Protocol
class SessionLike(Protocol):
@t.overload
def get(self, key):
# type: (str) -> t.Any
pass
@t.overload
def get(self, key, default): # py... |
478538 | import sys
import logging
from logging import FileHandler,StreamHandler
import os
import gzip
import subprocess
import argparse
from grsnp import worker_optimizer as worker_opt
import pdb
from celery import group
import celeryconfiguration_optimizer
from time import sleep
import atexit
# connection information for the... |
478558 | from django.db import models
SOURCE = "source"
def SINK(arg):
print(arg)
assert arg == SOURCE
def SINK_F(arg):
print(arg)
assert arg != SOURCE
# ==============================================================================
# Inheritance
#
# If base class defines a field, there can be
# 1. flow w... |
478563 | from setuptools import setup
def parse_requirements(filename):
lines = (line.strip() for line in open(filename))
return [line for line in lines if line and not line.startswith('#')]
setup(name='VideoGPT', version='1.0',
description='PyTorch package for VideoGPT',
url='http://github.com/wilson1yan/... |
478564 | from django.urls import path
from .models import site
urlpatterns = [
path('admin/', site.urls),
]
|
478580 | from setuptools import setup, find_packages
import numpy as np
from get_version import get_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="Scribe",
__version__ = get_version(__file__),
install_requires=['cvxopt>=1.2.3', 'pandas>=0.23.0', 'numpy>=1.14', 'scipy>=1.0... |
478699 | import brownie
MAX_UINT256 = 2 ** 256 - 1
WEEK = 7 * 86400
def test_kick(chain, accounts, gauge_v4_1, mirrored_voting_escrow, voting_escrow, token, mock_lp_token):
alice, bob = accounts[:2]
chain.sleep(2 * WEEK + 5)
mirrored_voting_escrow.set_mirror_whitelist(accounts[0], True, {"from": accounts[0]})
... |
478709 | from datar.base.verbs import complete_cases, proportions
import pytest
from pandas import DataFrame
from datar.base import *
from datar.tibble import tibble
from .conftest import assert_iterable_equal
def test_rowcolnames():
df = DataFrame(dict(x=[1,2,3]))
assert colnames(df) == ['x']
assert rownames(df) ... |
478740 | from polyphony import testbench
from polyphony import pipelined
def pipe07(xs, ys):
for i in pipelined(range(len(xs))):
v = xs[i]
if v < 0:
z = (v - 8) >> 4
else:
z = (v + 8) >> 4
ys[i] = z
for i in pipelined(range(len(ys))):
v = ys[i]
#... |
478742 | class Solution:
def print2largest(self,A,N):
A.sort(reverse=True)
for i in range(1,N):
if A[i]!=A[i-1]:
return A[i]
return -1
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
ob=Solution()
print(ob.print2largest(a,... |
478746 | from fuel.streams import AbstractDataStream
from fuel.iterator import DataIterator
import numpy as np
import theano
class IMAGENET(AbstractDataStream):
"""
A fuel DataStream for imagenet data
from fuel:
A data stream is an iterable stream of examples/minibatches. It shares
similarities with Python ... |
478748 | from pyramid.config import Configurator
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include('ramses')
return config.make_wsgi_app()
|
478764 | from django.apps import AppConfig
class PolymorphicTestsConfig(AppConfig):
name = 'ralph.lib.polymorphic.tests'
label = 'polymorphic_tests'
|
478787 | from modules.OverTheShellbag import converter as cv
class TypeList:
# key "sig" will convert list type -> ConverTypeForPython()
# List : ['00', '10', '1f', '20', '2e', '2f', '31', '32', '35', '71', '74', '78', 'b1']
# '31': 1801, '35': 420, '1f': 39, '00': 13,
# '2f': 8, '2e': 7, '74':... |
478796 | import torch
from skimage.morphology import disk
@torch.no_grad()
def binary_dilation(im: torch.Tensor, kernel: torch.Tensor):
assert len(im.shape) == 4
assert len(kernel.shape) == 2
kernel = kernel.unsqueeze(0).unsqueeze(0)
padding = kernel.shape[-1]//2
assert kernel.shape[-1] % 2 != 0
if tor... |
478798 | from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from resources.... |
478800 | class A:
def __init__(self, x):
self.x = x
def __add__(self, y):
return self.x + y
def __len__(self):
return 10
def __iter__(self):
return iter(range(10))
def __str__(self):
return "bla"
a = A(3)
assert a + 1 == 4
assert len(a) == 10
i = 0
for j in a:... |
478819 | import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
import magma as m
import json
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "top"
IO = ... |
478832 | import numpy as np
def make_epsilon_greedy_policy(Q, epsilon, nA):
"""
Creates an epsilon-greedy policy based on a given Q-function and epsilon.
Args:
Q: A dictionary that maps from state -> action-values.
Each value is a numpy array of length nA (see below)
epsilon: The probab... |
478855 | from http import HTTPStatus
from typing import Dict, Tuple
from flask import jsonify, request, abort
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
from db.access.files import FilesDAO
from db.schema import Matches, Files
from .blueprint import api
from .constants import ValidationErr... |
478881 | from django.db import models
class Ambiguous(models.Model):
name = models.CharField(max_length=20)
|
478992 | import re
import random
import sys
import traceback
import ast
import operator
import time
import json
from simpleeval import SimpleEval, DEFAULT_OPERATORS, DEFAULT_FUNCTIONS, DEFAULT_NAMES
from . import euphutils
from . import logger
log = logger.Logger()
# functions and operators that can be used in ${math} syntax... |
479038 | import threading
import boto3
class Boto3Profile(object):
"""Store parameters for creating a boto3 profile"""
session_cache = dict()
lock = threading.Lock()
def __init__(self, profile_name, region_name):
self.profile_name = profile_name
self.region_name = region_name
def update(... |
479070 | from .nodes import *
class Type:
def __str__(self):
return '%s(size=%d)' % (self.__class__.__name__, self.size)
def __repr__(self):
return self.__str__()
@property
def raw(self):
return self
class IntType(Type):
def __init__(self):
self.size = 1
self.suf... |
479082 | import logging
import random
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import ImproperlyConfigured
from django.db import models, transaction
from django.utils import timezone
from django.utils.module_lo... |
479105 | import logging
import re
import warnings
import numpy as np
import pandas as pd
idl2np_dtype = {1: np.byte, 2: np.int16, 3: np.int32, 4: np.float32,
5: np.float64}
idl2struct = {4: 'f', 5:'d'}
archtype2struct={'sparc': None, 'bigend': '>', 'litend': '<',
'alpha': None, 'ppc': None, 'x86': No... |
479119 | whitelist = ["ะะะ ะะะ", "ะะะ ะก", "ะะะ ะะ", "ะะะะฅะ", "ะะะะขะฌะ", "ะะะะะะ"]
def analyze(s, pref):
if s in whitelist:
return False, [f"{pref:<6} {s} - LOSING"]
results = []
for word in whitelist:
if word.startswith(s):
result = analyze(s + word[len(s)], f"{pref:<6} --{word:<6}-->")
... |
479146 | from ..factory import Type
class passportElementsWithErrors(Type):
elements = None # type: "vector<PassportElement>"
errors = None # type: "vector<passportElementError>"
|
479167 | class Cheat:
def __init__(self, name: str):
self.name = name
self.is_running = False
def set_is_running(self, is_running: bool):
self.is_running = is_running |
479174 | from gb_utils.greenberry_lex import GreenBerryLex
from symbols import *
from debug_cp import *
import inspect
MATH_OPS = ["+", "-", "*", "/"]
BOOLS = [S.TRUE, S.FALSE]
BOOL_OPS = [S.GREATER, S.LESS]
EOS = [S.NL, S.EOF]
def greenberry_lex_test(x, expected):
KWDs = [
getattr(S, i)
for i in [
... |
479192 | from .frame import Frame
from .parser import Parser
from .settings import *
class Traverser:
def __init__(self, frames, mapping):
self.frames = frames
self.mapping = mapping
# Finds node within XP, for which negation may produce a reasonable goal with the returned operator
# Returns: (fram... |
479194 | import logging
import re
from plane import replace
from plane.pattern import EMAIL, TELEPHONE
from tqdm import tqdm
from dbpunctuator.utils import (
CURRENCY,
CURRENCY_TOKEN,
EMAIL_TOKEN,
NUMBER,
NUMBER_TOKEN,
TELEPHONE_TOKEN,
URL,
URL_TOKEN,
)
tqdm.pandas()
logger = logging.getLogger... |
479214 | import logging
import os
import platform
import numpy as np
import pybullet as p
import yaml
import igibson
from igibson.action_primitives.action_primitive_set_base import ActionPrimitiveError
from igibson.action_primitives.starter_semantic_action_primitives import StarterSemanticActionPrimitives
from igibson.objects... |
479242 | import rdkit
from rdkit.Chem import rdMolTransforms
from rdkit.Chem import TorsionFingerprints
import numpy as np
import networkx as nx
import random
atomTypes = ['H', 'C', 'B', 'N', 'O', 'F', 'Si', 'P', 'S', 'Cl', 'Br', 'I']
formalCharge = [-1, -2, 1, 2, 0]
degree = [0, 1, 2, 3, 4, 5, 6]
num_Hs = [0, 1, 2, 3, 4]
loca... |
479251 | class TwoSum:
def __init__(self):
self.nums = {}
def add(self, number):
self.nums[number] = self.nums.get(number, 0) + 1
def find(self, value):
for num in self.nums:
if value - num in self.nums and (num != value - num or self.nums[num] > 1):
return True... |
479254 | from __future__ import absolute_import
import pytest
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core.context import Context
from aws_xray_sdk.ext.flask_sqlalchemy.query import XRayFlaskSqlAlchemy
from flask import Flask
from ...util import find_subsegment_by_annotation
app = Flask(__name__)
app.con... |
479283 | from typing import Dict, Tuple, Union
from pyswip import Functor, Atom, Variable
from problog.logic import (
Term,
Constant,
list2term,
term2list,
Var,
is_list,
Clause,
And,
Or,
)
from problog.parser import PrologParser
from problog.program import ExtendedPrologFactory
PySwipObjec... |
479293 | from maps.fixedkeymap import FixedKeyMap
from maps.frozenmap import FrozenMap
from maps.nameddict import NamedDict
from maps.namedfixedkeymap import NamedFixedKeyMapMeta
from maps.namedfrozenmap import NamedFrozenMapMeta
def namedfrozen(typename, fields, defaults={}):
'''Creates a new class that inherits from :cla... |
479295 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from builtins import str # pylint: disable=redefined-builtin
import unittest
import cleverbot
class CleverbotTest(unittest.TestCase):
def test_replay(self):
cbc = cleverbot.Cleverbot("cleverbot-p... |
479316 | from mock import ANY
from raptiformica.actions.mesh import ensure_ipv6_enabled
from tests.testcase import TestCase
class TestEnsureIPv6Enabled(TestCase):
def setUp(self):
self.log = self.set_up_patch('raptiformica.actions.mesh.log')
self.run_command_print_ready = self.set_up_patch(
'r... |
479343 | from datasets.MOT.dataset import MultipleObjectTrackingDataset_MemoryMapped, \
MultipleObjectTrackingDatasetSequence_MemoryMapped, MultipleObjectTrackingDatasetFrame_MemoryMapped
from miscellanies.viewer.qt5_viewer import Qt5Viewer
from datasets.base.common.viewer.qt5_viewer import draw_object
from PyQt5.QtGui impo... |
479394 | from .base import ObjectBase
from .list import ObjectList
from .order_line import OrderLine
class Shipment(ObjectBase):
@property
def resource(self):
return self._get_property("resource")
@property
def id(self):
return self._get_property("id")
@property
def order_id(self):
... |
479408 | from shovel import task
import subprocess
@task
def rst():
"""Convert markdown readme to reStructuredText"""
subprocess.call(['pandoc', '--from=markdown', '--to=rst', '--output=README', 'README.md'])
|
479417 | from .base import Render
class RenderOutput(Render):
def __init__(self, string_to_format):
self.string_to_format = string_to_format
def render(self, **kwargs):
print(self._format(f"{self.string_to_format}%s" % "{reset}", **kwargs))
|
479437 | from squid import *
import time
rgb = Squid(18, 23, 24)
rgb.set_color(RED)
time.sleep(2)
rgb.set_color(GREEN)
time.sleep(2)
rgb.set_color(BLUE)
time.sleep(2)
rgb.set_color(WHITE)
time.sleep(2)
rgb.set_color(WHITE, 300)
time.sleep(2) |
479446 | import os
import time
from transformers.pipelines import pipeline
import pytest
from answer import create_app
# initialize testing environment
hg_comp = pipeline('question-answering',
model="distilbert-base-uncased-distilled-squad",
tokenizer="distilbert-base-uncased-distille... |
479529 | import numpy as np
SKY_BETA160_C05_D1 = np.array(
[[0.39344519, 0.39292569, 0.39240611, 0.39188644, 0.3913667 ,
0.39084688, 0.39032699, 0.38980703, 0.389287 , 0.38876691,
0.38824676, 0.38772654, 0.38720627, 0.38668595, 0.38616558,
0.38564515, 0.38512468, 0.38460417, 0.38408362, 0.38356304,
... |
479564 | import json
import os
import requests
import dotenv
# This zone ID may change if/when our account changes
# Run `list_cloudflare_zones` (below) to get a full list
ZONE_ID = "198bb61a3679d0e1545e838a8f0c25b9"
def list_cloudflare_zones():
url = "https://api.cloudflare.com/client/v4/zones"
headers = {
... |
479578 | import unittest
from nlgeval.pycocoevalcap.meteor.meteor import Meteor
class TestMeteor(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.m = Meteor()
def test_compute_score(self):
s = self.m.compute_score({0: ["test"]}, {0: ["test"]})
self.assertEqual(s, (1.0, [1.0]))
... |
479613 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import Model as M
import hrnet
class HRNET(M.Model):
def initialize(self, num_pts):
self.backbone = hrnet.ResNet()
self.lastconv = M.ConvLayer(1, num_pts)
def forward(self, x):
x = self.backbone(x)
x = self.lastconv(x)... |
479620 | from namespace_class import *
try:
p = Private1()
error = 1
except:
error = 0
if (error):
raise RuntimeError, "Private1 is private"
try:
p = Private2()
error = 1
except:
error = 0
if (error):
raise RuntimeError, "Private2 is private"
EulerT3D.toFrame(1, 1, 1)
b = BooT_i()
b = BooT_... |
479623 | import os
import shutil
import unittest
import bilby
from bilby.bilby_mcmc.sampler import Bilby_MCMC, BilbyMCMCSampler, _initialize_global_variables
from bilby.bilby_mcmc.utils import ConvergenceInputs
from bilby.core.sampler.base_sampler import SamplerError
import numpy as np
import pandas as pd
class TestBilbyMCMC... |
479626 | from pythonwarrior.abilities.base import AbilityBase
class Pivot(AbilityBase):
ROTATION_DIRECTIONS = ['forward', 'right', 'backward', 'left']
def description(self):
return "Rotate 'left', 'right', or 'backward' (default)"
def perform(self, direction='backward'):
self.verify_direction(dir... |
479628 | import os
import argparse
import molbart.util as util
from molbart.models.pre_train import BARTModel, UnifiedModel
from molbart.decoder import DecodeSampler
# Default training hyperparameters
DEFAULT_BATCH_SIZE = 128
DEFAULT_ACC_BATCHES = 1
DEFAULT_MASK_PROB = 0.10
DEFAULT_MASK_SCHEME = "span"
DEFAULT_LR = 1.0
DEFAU... |
479649 | import os
import time
import client.api
import client.models
from mamba import description, before, after, it
from expects import *
from expects.matchers import Matcher
from common import Config, Service
from common.helper import (make_dynamic_results_config,
check_modules_exists,
... |
479650 | import math
import textwrap
str1=''.join(input().strip().split())
rows=math.floor(math.sqrt(len(str1)))
col=rows
if rows*col<len(str1):
col+=1
if rows*col<len(str1):
rows+=1
l1=textwrap.wrap(str1,col)
for i in range(0,col):
for j in range(0,rows):
if (i+1)+(j)*col>len(str1):
continue
print(l1[j][i],end='')... |
479684 | from numpy import atleast_2d, ndarray, float32, float64, float128
class PythonDSP(object):
"""A FAUST DSP wrapper.
This class is more low-level than the FAUST class. It can be viewed as an
abstraction that sits directly on top of the FAUST DSP struct.
"""
def __init__(self, C, ffi, fs):
... |
479703 | import re
from discord import MessageType
from utils.settings import settings
from utils.globals import gc, get_color
import utils
async def calc_mutations(msg):
try: # if the message is a file, extract the discord url from it
json = str(msg.attachments[0]).split("'")
for string in json:
... |
479718 | from functools import update_wrapper
from typing import Callable, Sequence, Tuple, Union
import jax.numpy as np
from jax import ops, random
# define a type alias for Jax Pytrees
Pytree = Union[tuple, list]
Bijector_Info = Tuple[str, tuple]
class ForwardFunction:
"""Return the output and log_det of the forward b... |
479726 | from data_mapper.properties import Property
from data_mapper.properties.compound_list import CompoundListProperty as L
from data_mapper.shortcuts import V, P
from data_mapper.tests.test_utils import PropertyTestCase
class CompoundListPropertyTests(PropertyTestCase):
def test__simple(self):
self.prop_test(... |
479781 | import pandas as pd
def collectPitch(df):
pitch_types = ['FT','FS','CH','FF','SL','CU','FC','SI','KC','EP','KN','FO']
pitch = df.sample(n=1)
pitch_label_df = pitch[pitch_types]
pitch_data = pitch.drop(pitch_types,axis=1).values.tolist()
return pitch_data, pitch_label_df.style.hi... |
479783 | import logging
from flask import request
from flask_restplus import Resource
from biolink.ontology.ontology_manager import get_ontology
from biolink.datamodel.serializers import compact_association_set, association_results
from ontobio.golr.golr_associations import search_associations, GolrFields
from ontobio.ontol_fa... |
479792 | from setuptools import setup, find_packages
setup(
name = 'docformer',
packages = find_packages(where="src"),
package_dir = {"": "src", "docformer": "src/docformer"},
version = '0.1.0',
license='MIT',
description = 'DocFormer: End-to-End Transformer for Document Understanding',
author = '<NAME>, <NAME>',... |
479793 | import sys
sys.path.append('../')
import argparse
import os
import torch
from elmoformanylangs import Embedder
from pytorch_transformers import BertModel, BertTokenizer
from tqdm import tqdm
import numpy as np
from data_util import io_helper
"""
Creates static vectors for vocabulary
"""
def get_elmo(model, sen... |
479868 | from django.db import models
# Create your models here.
from kala.models import Kala
from taghaza.models import Taghaza
class Sefaresh(models.Model):
taghaza = models.ForeignKey(Taghaza, on_delete=models.DO_NOTHING , verbose_name="ุดู
ุงุฑู ุชูุงุถุง")
kala = models.ForeignKey(Kala, on_delete=models.DO_NOTHING, verb... |
479889 | from typing import KeysView, Generator
SERVICES_FOR_GROUP = {
"all": "tad_harvester tad_timelord_launcher tad_timelord tad_farmer tad_full_node tad_wallet".split(),
"node": "tad_full_node".split(),
"harvester": "tad_harvester".split(),
"farmer": "tad_harvester tad_farmer tad_full_node tad_wallet".split... |
479908 | from flask import request, jsonify
from app import db, jwt
from app.auth import bp
from app.models import Users, RevokedTokenModel
from app.schemas import UsersDeserializingSchema
from app.errors.handlers import bad_request, error_response
from flask_jwt_extended import (
create_access_token,
create_refresh_t... |
479920 | from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from .views import ArticleViewSet, AuthorViewSet
router = DefaultRouter()
router.register(r'articles', ArticleViewSet)
router.register(r'authors', AuthorViewSet)
urlpatterns = [
url('', include(router.urls)),
]
|
479926 | from __future__ import with_statement
import logging
from logging.config import fileConfig
from alembic import context
from sqlalchemy import create_engine
from falcon_web_demo.persistence import get_url
config = context.config
fileConfig(config.config_file_name)
kwargs = {'as_dictionary': True}
pref = 'loggingPref... |
479934 | import re
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
stopwords_en = set(stopwords.words('english'))
def normalize_text(string):
""" Text normalization from
https://github.com/yoonkim/CNN_sentence/blob/23e0e1f735570/process_data.py
as specified in Yao's paper.
"""
st... |
479961 | from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessRemoveParticipantsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="{{group_jid}}" id="{{id}}">
<remove type="success" participant="{{jid}}"></remove... |
479964 | from __future__ import print_function
import sys
import platform
import textwrap
from subprocess import check_output
from setuptools import setup, find_packages
def check_install():
"""
Try to detect the two most common installation errors:
1. Installing on macOS using a Homebrew version of Python
2... |
480059 | import supriya.synthdefs
import supriya.ugens
__all__ = []
def _build_link_audio_synthdef(channel_count):
r"""
SynthDef("system_link_audio_" ++ i, {
arg out=0, in=16, vol=1, level=1, lag=0.05, doneAction=2;
var env = EnvGate(doneAction:doneAction, curve:'sin') * Lag.kr(vol * level, lag);
... |
480066 | from Voicelab.pipeline.Node import Node
import numpy as np
import seaborn as sns
import os
import parselmouth
from parselmouth.praat import call
import matplotlib.pyplot as plt
from Voicelab.toolkits.Voicelab.VoicelabNode import VoicelabNode
#from Voicelab.VoicelabWizard.SpectrumPlotWindow import SpectrumPlotWindow
#... |
480088 | import asyncio
from typing import Any, Awaitable, Callable, Dict, List, Set, Type
from loguru import logger
from rich.console import Console
from rich.logging import RichHandler
from rich.status import Status
from avilla.core.launch import LaunchComponent, resolve_requirements
from avilla.core.service import Service,... |
480090 | from recordthresher.record_maker import PmhRecordMaker
from recordthresher.util import parseland_parse
class OstiRecordMaker(PmhRecordMaker):
@staticmethod
def _is_specialized_record_maker(pmh_record):
return pmh_record and pmh_record.pmh_id and pmh_record.pmh_id.startswith('oai:osti.gov:')
@clas... |
480096 | from app import db
class Rules(db.Model):
__tablename__ = "rules"
id = db.Column(db.Integer, primary_key=True)
workload_name = db.Column(db.String(120), unique=True, nullable=False)
key_name = db.Column(db.String(20))
score = db.Column(db.DECIMAL(20, 2))
infos = db.relationship('Information', ... |
480194 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def data_block_heatmaps(blocks):
"""
Plots a heat map of a bunch of data blocks
"""
num_blocks = len(blocks)
if hasattr(blocks, 'keys'):
block_names = list(blocks.keys())
else:
# block_names = ['block {}'.... |
480204 | import datetime
from optuna.study import StudySummary, StudyDirection
from optuna.trial import FrozenTrial, TrialState
from optuna.distributions import distribution_to_json, json_to_distribution
def serialize_datetime(obj):
if isinstance(obj, datetime.datetime):
return {"__datetime__": True, "as_str": ob... |
480236 | from Crypto.Util.number import long_to_bytes
N = 56469405750402193641449232753975279624388972985036568323092258873756801156079913882719631252209538683205353844069168609565141017503581101845476197667784484712057287713526027533597905495298848547839093455328128973319016710733533781180094847568951833393705432945294907000... |
480237 | from io import BufferedIOBase
from ps1_argonaut.BaseDataClasses import BaseDataClass
from ps1_argonaut.configuration import Configuration
class ScriptData(BaseDataClass):
def __init__(self, data: bytes):
self.data = data
@property
def size(self):
return len(self.data)
@classmethod
... |
480248 | from .searcher import Searcher
class SimulatedAnnealing(Searcher):
def __init__(self, population, params, generation_size=32, stabilization_limit=10):
self.population = population
Searcher.__init__(self, self.population, generation_size, stabilization_limit)
self.params = None
self... |
480249 | import sys
import time
import pandas as pd
from selenium import webdriver
from selenium.common.exceptions import WebDriverException, NoSuchElementException
from selenium.webdriver.common.keys import Keys
def ciceksepeti_scraper():
def initialize():
def preference(scrape_input, question):
... |
480250 | import string
def encode(str):
s = string.ascii_letters + " "
dic = {}
enc = ""
for i in range(len(s)):
dic[s[i]] = s[(i + 3) % len(s)]
for ch in str:
enc += dic[ch]
return enc
def decode(str):
s = string.ascii_letters + " "
dic = {}
dec = ""
for i in range(len(s)):
dic[s[i]] = s[(i - 3) % len(s)]
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.