id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11411860 | from fastapi import status
from .mark import override_panels, override_settings
from .testclient import TestClient
@override_panels(["debug_toolbar.panels.timer.TimerPanel"])
def test_render_panel(client: TestClient) -> None:
store_id = client.get_store_id("/async")
response = client.render_panel(store_id=st... |
11411875 | src = Split('''
aos_init.c
''')
component = aos_component('kernel_init', src)
component.add_global_includes('include')
|
11411881 | import argparse
from functools import partial
import datetime
import time
import math
import sys
import os
import os.path
import numpy as np
from tqdm import tqdm
import gc
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.multiprocessing as mp
# noinspection PyPep8Naming
from torch.nn.p... |
11411891 | from importlib import import_module
import requests
from utils import rotation_utils as rot_utils
import torch
import random
import logging
logger = logging.getLogger(f"utils/util.py")
def get_object_from_path(path):
"""
The function returns the callable function from the path.
:param path: Path to the ... |
11411892 | class Graph(object):
def __init__(self, value):
self.adjacecy_list = defaultdict(set)
def add_edge(self, start, destination):
self.adjacency_list[start].add(destination)
self.adjacency_list[destination].add(start)
def edges(self, node):
return self.adjacency_list(node)
... |
11411917 | class PageType:
def __init__(self):
pass
Invalid = -1
DefaultView = 0
NormalView = 1
DialogView = 2
View = 3
DisplayForm = 4
DisplayFormDialog = 5
EditForm = 6
EditFormDialog = 7
NewForm = 8
NewFormDialog = 9
SolutionForm = 10
PAGE_MAXITEMS = 11
|
11411934 | from typing import Iterable
from django.core.files import File
from contests.models import Submission, Language
from contests.auth.core import get_me
from .core import get_contest_submissions, get_submission_by_id, submit_solution
def submission_language_resolver(root: Submission, _info) -> Language:
return roo... |
11411970 | import boto3
from moto import mock_s3
from Output.export_final import lambda_handler
@mock_s3
def test_export_final():
manifest_content = b'{"source": "tech now mindy kaling at sxsw", "category": 1, "category-metadata": {"confidence": 1.0, "human-annotated": "yes", "type": "groundtruth/text-classification"}}'
... |
11411986 | from __future__ import absolute_import
import unittest
import os
import subprocess as SP
import shutil
import shlex
import tempfile
from six import string_types
from os.path import join as p
import pytest
from .TestUtilities import xfail_without_db
@pytest.mark.inttest
class ExampleRunnerTest(unittest.TestCase):
... |
11411996 | from collections import OrderedDict
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import torchvision.models as models
'''
# --------------------------------------------
# Advanced nn.Sequential
# https://github.com/xinntao/BasicSR
# --------------------------------------------
'... |
11412020 | from time import sleep
from pitop.protoplus import ADCProbe
temp_sensor = ADCProbe()
while True:
print(temp_sensor.read_value(1))
sleep(0.5)
|
11412060 | from .fileobjs import FileobjsSource
from urllib.parse import urlparse
from .base import SupportsToFileobjsSource
from contextlib import contextmanager
from ..delimited import sniff_compression_from_url
from ..processing_instructions import ProcessingInstructions
from ...url.resolver import UrlResolver
from ..records_f... |
11412062 | n,d=map(int,input().split())
arr=list(map(int,input().split()))
num=d%n # Remove excess number of rotations
for _ in range(num): # Do operations in range num
x=arr.pop(0)
arr.append(x)
print(*arr) # Unpack the list |
11412063 | from __future__ import absolute_import, division, print_function, unicode_literals
from echomesh.util.settings.SettingsValues import SettingsValues
from echomesh.util.TestCase import TestCase
class SettingsValuesTest(TestCase):
def add_client(self, values):
def get(*names):
if names == ('c',):... |
11412079 | import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import time
import h5py
import sys
IM_SHAPE = (64, 64, 3)
class TrainingDatasetLoader(object):
def __init__(self, data_path):
print("Opening: ", format(data_path))
sys.stdout.flush()
self.cac... |
11412083 | from .consts import *
# ================================================
# Exceptions
# ================================================
class SenderNotScoreOwnerError(Exception):
pass
class SenderNotAuthorized(Exception):
pass
class NotAFunctionError(Exception):
pass
def only_admin(func):
if ... |
11412127 | import torch
from torch import nn
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss
from transformers.models.roberta.modeling_roberta import (
RobertaPreTrainedModel,
RobertaModel
)
from transformers.file_utils import(
add_start_docstrings,
add_code_sample_docstrings,
)
from transformers.model... |
11412145 | import logging
from typing import List
from sqlalchemy import Table # type: ignore
from sqlalchemy.dialects import mysql # type: ignore
from sqlalchemy.dialects.mysql import insert # type: ignore
from sqlalchemy.engine import Engine # type: ignore
from doltpy.sql.helpers import clean_types
from doltpy.sql.sync.db... |
11412156 | from typing import Optional, List, Dict, Any
import os
from collections import OrderedDict
import sqlite3
RAPID_UPLOAD_TABLE = "rapid_upload"
CREATE_RAPID_UPLOAD_TABLE = f"""
CREATE TABLE IF NOT EXISTS {RAPID_UPLOAD_TABLE}
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NULL,
localpath TEXT NUL... |
11412160 | WHITELIST = 'abcdefghijklmnopqrstuvwxyz1234567890?.,'
def in_white_list(_word):
valid_word = False
for char in _word:
if char in WHITELIST:
valid_word = True
break
if valid_word is False:
return False
return True
|
11412162 | import os, sys
sys.path.insert(1,'/home/roman/Dropbox/florence')
import numpy as np
from math import sqrt
from numpy import einsum
from Florence.Tensor import Voigt, trace, makezero, makezero3d
from Florence.LegendreTransform import LegendreTransform
from Florence import *
from Florence.FiniteElements.ElementalMatrices... |
11412165 | import math
class LearningRateScheduler:
"""
Parameters:
wr_epochs (int): epochs defining one warm restart cycle
min_learning_rate (float): minimum learning rate to use in warm restarts
max_learning_rate (float): maximum (initial) learning rate to use in warm restarts
... |
11412183 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
from six.moves import zip
from six.moves import cPickle
import numpy as np
TRANSLATE = {
"-lsb-" : "[",
"-rsb-" : "]",
"-lrb-" : "(",
"-rrb-" : ")",
"-lcb-" ... |
11412212 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
import dict
import models
import time
import numpy as np
import torch.nn.init as init
import ma... |
11412222 | from direct.fsm.StatePush import StateVar
from direct.showbase.PythonUtil import getSetterName
from otp.level.Entity import Entity
class EntityStateVarSet(Entity):
def __init__(self, entType):
self._entType = entType
self._attribNames = []
for attrib in self._entType.attribs:
n... |
11412313 | import os
import cv2
from tkFileDialog import askdirectory
from tkMessageBox import askyesno
WINDOW_NAME = 'Simple Bounding Box Labeling Tool'
FPS = 24
SUPPOTED_FORMATS = ['jpg', 'jpeg', 'png']
DEFAULT_COLOR = {'Object': (255, 0, 0)}
COLOR_GRAY = (192, 192, 192)
BAR_HEIGHT = 16
KEY_UP = 65362
KEY_DOWN = 65364
KEY_LEF... |
11412336 | import torch
from src.complex import CPLX
def concat(axis=-1, *args):
x_r = torch.cat([j.r for j in args], axis=axis)
x_i = torch.cat([j.i for j in args], axis=axis)
return CPLX(x_r, x_i)
def loss(labels, predictions, loss_function, use_magnitude=True):
if isinstance(labels, CPLX):
retur... |
11412387 | import FWCore.ParameterSet.Config as cms
# Calo geometry service model
#ECAL conditions
from RecoLocalCalo.EcalRecProducers.getEcalConditions_frontier_cff import *
#ECAL reconstruction
from RecoLocalCalo.EcalRecProducers.ecalWeightUncalibRecHit_cfi import *
from RecoLocalCalo.EcalRecProducers.ecalRecHit_cfi import *
f... |
11412418 | from __future__ import division
from pycircuit.circuit import Circuit, defaultepar
from pycircuit.utilities.param import Parameter
class myC(Circuit):
"""Capacitor
>>> c = SubCircuit()
>>> n1=c.add_node('1')
>>> c['C'] = C(n1, gnd, c=1e-12)
>>> c.G(np.zeros(2))
array([[ 0., 0.],
[ 0... |
11412444 | import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from qutip import *
from plot_helpers import *
from model import load
train_end = 2
expo_start = 1.9732
expo_good_end = 4
def heisenberg_plot(type, samples=10, iter=0):
if not os.path.exists('plots/{}_heisenberg'.... |
11412462 | try:
from . import generic as g
except BaseException:
import generic as g
class ReprTest(g.unittest.TestCase):
def test_repr(self):
m = g.trimesh.creation.icosphere()
r = str(m)
assert 'trimesh.Trimesh' in r
assert 'vertices' in r
assert 'faces' in r
s = m... |
11412468 | from capreolus import constants
from . import Tokenizer
@Tokenizer.register
class PunktTokenizer(Tokenizer):
module_name = "punkt"
_tokenizer = None
def tokenize(self, txt):
if self._tokenizer is None:
import nltk
nltk_dir = constants["CACHE_BASE_PATH"] / "nltk"
... |
11412483 | import csv
from pathlib import Path
from pkg_resources import resource_filename
from .jpn_indices import JpnIndex
from .links import Link
from .queries import Query
from .sentences_base import SentenceBase
from .sentences_cc0 import SentenceCC0
from .sentences_detailed import SentenceDetailed
from .sentences_in_lists... |
11412512 | import cv2, math, numpy as np
# Path to source video:
output_path = '/home/stephen/Desktop/1.csv'
cap = cv2.VideoCapture('/home/stephen/Desktop/source_vids/ss3_id_110.MP4')
# Mouse callback function
global click_list
positions, click_list = [], []
def callback(event, x, y, flags, param):
if event == 1: click_list... |
11412527 | import sqlite3
from task_module import WorkClass, ExamClass, StudentClass, CertificationClass
class SQLiteClass:
def __init__(self):
self.dbname = "pract4.db"
conn = sqlite3.connect(self.dbname)
c = conn.cursor()
# Студент
c.execute(
"CREATE TABLE IF NOT EXIST... |
11412551 | import pytest
from django.core.exceptions import ValidationError
from django.db import IntegrityError, models
from django.db.transaction import atomic
from friendly_states.core import AttributeState
from friendly_states.django import StateField, DjangoState
from friendly_states.exceptions import DjangoStateAttrNameWar... |
11412597 | import pyjd # dummy in pyjs
from pyjamas.ui.Button import Button
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Label import Label
from pyjamas.ui.Grid import Grid
from pyjamas.ui.CellFormatter import CellFormatter
from pyjamas.ui.RowFormatter import RowFormatter
from pyjamas.ui.HTMLTable import HTMLTable
... |
11412602 | import torch
def total_variance(x):
dx = torch.mean(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:]))
dy = torch.mean(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :]))
return dx + dy
def label_matching(pred, label):
onehot_label = torch.eye(pred.shape[-1])[label]
onehot_label = onehot_label.to(pred.device... |
11412630 | import asyncio
import logging
import tempfile
from pathlib import Path
from typing import Awaitable, Optional
import aiodocker
import networkx as nx
from aiodocker.volumes import DockerVolume
from aiopg.sa.result import RowProxy
from servicelib.logging_utils import log_decorator
from .exceptions import SidecarExcepti... |
11412642 | import pytest
from buildtrigger.customhandler import CustomBuildTrigger
from buildtrigger.triggerutil import (
InvalidPayloadException,
SkipRequestException,
TriggerStartException,
)
from endpoints.building import PreparedBuild
from util.morecollections import AttrDict
@pytest.mark.parametrize(
"payl... |
11412700 | import sys
import os
sys.path.insert(0, os.path.abspath('.'))
import math
from lib.dobot import Dobot
bot = Dobot('/dev/tty.SLAB_USBtoUART')
print('Homing')
#bot.home()
print('Unlock the arm and place it on the middle of the paper')
input("Press enter to continue...")
center = bot.get_pose()
print('Center:', cente... |
11412706 | from __future__ import absolute_import
from graphviz import Digraph
import subprocess
import os
import signal
pid = None
def show(executor, port=9997):
print("Generating graph figure")
dot = Digraph()
dot.format = 'png'
for node in executor.topo_order:
dot.node(str(node.id), node.name)
... |
11412747 | def reverse_string(original_string):
return original_string[::-1]
original_string = str(input("Enter a string to be reversed > "))
print(reverse_string(original_string))
|
11412758 | from chainercv.links.model.senet.se_resnet import SEResNet # NOQA
from chainercv.links.model.senet.se_resnet import SEResNet101 # NOQA
from chainercv.links.model.senet.se_resnet import SEResNet152 # NOQA
from chainercv.links.model.senet.se_resnet import SEResNet50 # NOQA
from chainercv.links.model.senet.se_resnext ... |
11412816 | import json
import time
from threading import Thread, Event
from basetestcase import BaseTestCase
from couchbase_helper.document import DesignDocument, View
from couchbase_helper.documentgenerator import DocumentGenerator
from membase.api.rest_client import RestConnection
from membase.helper.rebalance_helper import Reb... |
11412885 | from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.db import transaction
class Command(BaseCommand):
help = "创建超级管理员和管理员角色"
def add_arguments(self, parser):
parser.add_argument('action', nargs='?', help='action ?')
def superus... |
11412958 | import os
import shutil
import subprocess
import tempfile
def d():
""" debug via running shell; need to run py.test with -s """
subprocess.call(["zsh", "-i"])
def g(a):
subprocess.check_call(["git"] + a)
def init_repo():
g(["init", "."])
def add_file(filename):
g(["add", "-v", filename])
def c... |
11413016 | import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
def cyclegan_generator_resnet(image, num=9, is_train=True, reuse=False, batch_size=None, name='generator'):
b_init = tf.constant_initializer(value=0.0)
w_init = tf.truncated_normal_initializer(stddev=0.01)
g_init = tf.random... |
11413075 | from django.urls import path, register_converter
from rest_framework.urlpatterns import format_suffix_patterns
from .views import (
series_view,
items_list,
item_data
)
from .converters import ItemNum
register_converter(ItemNum, 'vorc')
urlpatterns = [
path('series/', series_view, name='... |
11413133 | import os
import os.path as osp
from typing import Optional
ENV_PYG_HOME = 'PYG_HOME'
DEFAULT_CACHE_DIR = osp.join('~', '.cache', 'pyg')
_home_dir: Optional[str] = None
def get_home_dir() -> str:
r"""Get the cache directory used for storing all PyG-related data.
If :meth:`set_home_dir` is not called, the p... |
11413137 | import csv
import util
from util import csv_head_key
def export_from_spreadsheet(input_fname, input_ext, output_fname="temp/references.bib", exclude_keys=[]):
bibtex = []
reader = util.read_spreadsheet(input_fname, input_ext)
cnt = 0
for row in reader:
if cnt == 0:
cnt... |
11413157 | import os
import sys
import argparse
path_to_slim = 'models/research/slim/'
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), path_to_slim)))
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
from nets import ne... |
11413167 | import os
import base64
from collections import defaultdict
from netaddr import IPAddress, IPNetwork
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models import User
from core.models.slice import Slice, ControllerSlice
from core.models... |
11413180 | import os
import importlib.util
import logging
import pandas as pd
from datetime import date
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.models import BaseOperator
def get_function(func_module_directory, func):
file_name, func_name = func.split(".")
source_file = os.path.jo... |
11413188 | import logging
from .utils.utils import register_logger
# setup library logging
logger = logging.getLogger(__name__)
register_logger(logger)
|
11413195 | from datetime import datetime
from app import app
from app import db
from flask import Blueprint
from flask import render_template
from flask import redirect
from flask import url_for
from flask import request
from flask_login import login_required
from flask_login import current_user
from app.models.comment import ... |
11413225 | import base64
import json
import os
import sys
os.chdir("files")
def hex_to_b64(hex_string):
hex_string = base64.b64encode(bytearray.fromhex(hex_string))
return hex_string.decode('utf-8')
def mfilter(cmd):
if not ("createAccount" in cmd.keys()):
return True
if cmd["createAccount"]["accountN... |
11413268 | from styleaug import StyleAugmentor
import torch
from torchvision.transforms import ToTensor, ToPILImage
from PIL import Image
import matplotlib.pyplot as plt
# PyTorch Tensor <-> PIL Image transforms:
toTensor = ToTensor()
toPIL = ToPILImage()
# load image:
im = Image.open('mug.png')
im_torch = toTensor(im).unsque... |
11413292 | from func import set_discovery_issuer
from func import set_webfinger_resource
from jwkest import BadSignature
from oic.exception import IssuerMismatch
from oic.exception import PyoidcError
from otest.func import set_op_args
from otest.func import set_request_args
from oidctest.op.oper import AccessToken
from oidctest... |
11413365 | from openprocurement.api.models import IsoDateTimeType, ValidationError, Value, Period, ListType
from openprocurement.tender.core.procedure.models.base import ModelType, PostBusinessOrganization
from openprocurement.tender.core.procedure.models.base import BaseAward
from openprocurement.tender.core.procedure.models.doc... |
11413379 | from typing import Dict
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.common import FromParams
class HighOrderLayer(torch.nn.Module, FromParams):
''' High order interaction for span pairs '''
def __init... |
11413381 | from armulator.armv6.opcodes.abstract_opcodes.lsl_register import LslRegister
from armulator.armv6.opcodes.opcode import Opcode
class LslRegisterT1(LslRegister, Opcode):
def __init__(self, instruction, setflags, m, d, n):
Opcode.__init__(self, instruction)
LslRegister.__init__(self, setflags, m, d... |
11413409 | from collections import namedtuple
import numpy.testing as nptest
import pytest
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
from matplotlib.offsetbox import (
AnchoredOffsetbox, DrawingArea, _g... |
11413414 | from securityheaders.models import Keyword
class CSPKeyword(Keyword):
SELF = "'self'"
NONE = "'none'"
UNSAFE_INLINE = "'unsafe-inline'"
UNSAFE_EVAL = "'unsafe-eval'"
STRICT_DYNAMIC = "'strict-dynamic'"
STAR = "*"
@staticmethod
def isKeyword(keyword):
""" Checks whether a given... |
11413468 | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from core.models import (
Actor,
Action,
ActionDef,
ActionUnit,
BaseBomMaterial,
BomMaterial,
BillOfMaterials,
DefaultValues,
ExperimentTemplate,
ExperimentType,
ExperimentActionS... |
11413532 | import setuptools
from polyphony import __version__
setuptools.setup(
name='polyphony',
version=__version__,
packages=setuptools.find_packages(),
author="<NAME>",
author_email="<EMAIL>",
description="Python based High Level Synthesis compiler",
long_description=open('README.rst').read(),
... |
11413563 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
move_pos = 0
last_pos = len(arr) - 1
for i in range(last_pos + 1):
# Only check [0, lastPos - movePos]
if i > last_po... |
11413641 | class Solution:
# @param {TreeNode} root
# @return {boolean}
def isBalanced(self, root):
self.compute_height(root)
def get_balance(node):
if not node:
return True
if node.left:
l = node.left.height
else:
l =... |
11413674 | from the_pile.utils import *
import random
import os
from tqdm import tqdm
import shutil
import zstandard
import io
import parse
import sys
f = sys.argv[1]
fout = 'tmp'
def readf(f):
with open(f, 'rb') as fh:
cctx = zstandard.ZstdDecompressor()
reader = io.BufferedReader(cctx.stream_reader(fh))... |
11413699 | import pytest
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
from whatlies.language import (
FasttextLanguage,
SpacyLanguage,
GensimLanguage,
... |
11413758 | import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import numpy as np
import time
def graph_report(reports, symbols, relative, days, graph_type, ref_currency):
plt.clf()
plt.close()
if len(symbols) < 10:
plt.figure()
else:
plt.figure(figsize=(10, 6)... |
11413761 | import os
import math
import pathlib
import sys
import numpy as np
import pandas as pd
from datetime import datetime
from openpyxl import Workbook, load_workbook
import parser_april20_backward
import parser_may20_forward
def read_data(path):
try:
data = pd.read_html(path, decimal=',', thousands='.')
... |
11413782 | import random
from django.urls import reverse
from faker import Faker
from rest_framework import status
from openbook_common.tests.models import OpenbookAPITestCase
import logging
import json
from openbook_common.tests.helpers import make_user, make_authentication_headers_for_user, \
make_community
logger = log... |
11413827 | import fmmgen.generator as gen
import fmmgen.expansions as exp
from fmmgen.utils import q, Nterms
import sympy as sp
x, y, z, R = sp.symbols('x y z R')
symbols = (x, y, z)
def test_L_shift_0_order_monopole_source():
order = 0
source = 0
array_length = Nterms(order) - Nterms(source - 1)
L = sp.Mat... |
11413846 | from google.cloud.datastore_v1.proto import datastore_pb2
from google.cloud.datastore_v1.proto import datastore_pb2_grpc
import grpc
import unittest
class TestGRPCConnect(unittest.TestCase):
def test_connect(self):
# when zipped grpc needs to load a resource that it tries to get from disk
# that re... |
11413911 | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import ray
import json
import click
import tensorflow as tf
from ucate.application import workflows
@click.group(chain=True)
@click.pass_context
def cli(context):
gpus = tf.config.experimental.list_physical_devices("GPU")
context.obj = {"n_gpu": len(gpus)}
... |
11413917 | import pytest
import salt.renderers.nacl as nacl
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {nacl: {}}
def test__decrypt_object():
"""
test _decrypt_object
"""
secret = "Use more salt."
crypted = "NACL[MRN3cc+fmdxyQbz6WMF+jq1hKdU5X5... |
11413943 | from bkcharts import Dot, output_file, show, defaults
from bokeh.layouts import gridplot
from bokeh.sampledata.autompg import autompg as df
df['neg_mpg'] = 0 - df['mpg']
defaults.plot_width = 450
defaults.plot_height = 350
dot_plot = Dot(df, label='cyl', title="label='cyl'")
dot_plot2 = Dot(df, label='cyl', title="... |
11413945 | from DataHandler import DataHandler, DataManager
import logging
import json
import requests
import random
from config import config
import time
import threading
from cachetools import cached, TTLCache
logger = logging.getLogger(__name__)
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(seque... |
11413957 | import re
from basic.scanner import Scanner
from basic.parser import Parser
from basic.analyzer import BasicAnalyzer
from basic import productions as prod
import sys
TOKENS = [
(re.compile(r"^LET"), "LET"),
(re.compile(r"^PRINT"), "PRINT"),
(re.compile(r"^GOTO"), "GOTO"),
(re.compile(r"^[A-Z_][A-Z0-9_]*"), "NAME"... |
11413973 | import smtplib, sys, os
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
try:
conffile = sys.argv[1]
topublish = sys.argv[2]
except IndexError:
print >> sys.stderr, "Please provide a config file and a readdy-to-pu... |
11413984 | import maya.cmds as mc
import glTools.utils.base
import glTools.utils.shape
def softBody(geometry,prefix=''):
'''
'''
# Check prefix
if not prefix: prefix = geometry
# Check geometry
geometryType = mc.objectType(geometry)
if geometryType == 'transform':
geometryTransform = geometry
geometryShapes = glToo... |
11413987 | from datetime import datetime
from config import db, ma
from marshmallow import fields
class Person(db.Model):
__tablename__ = "person"
person_id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String(32))
fname = db.Column(db.String(32))
timestamp = db.Column(
db.DateTime, ... |
11413995 | import pytest
from app import process_user_agent
@pytest.mark.parametrize(
"input, expected",
[
(
"Mozilla/5.0 (iPad; U; CPU like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405",
"non-notify-user-agent",
),
("NOTIFY-API-PYTHON-CLIENT/3.... |
11414018 | import random
from axelrod import Player
class Defector(Player):
"""A player who only ever defects."""
name = 'Defector'
def strategy(self, opponent):
return 'D'
class TrickyDefector(Player):
"""A defector that is trying to be tricky."""
name = "<NAME>"
def strategy(self, oppone... |
11414023 | from Server import create_app
from config.dev import DevConfig
if __name__ == '__main__':
app = create_app(DevConfig)
app.run(**DevConfig.RUN_SETTING) |
11414026 | import sys
predicates = {}
counter = 0
def processAtom(atom):
global predicates
global counter
terms = atom.split()
for term in terms:
# print ("term : " , term)
if term.startswith("<") and term.endswith(">") and not term.startswith("?"):
if term not in predicates:
... |
11414118 | import sys
def main():
a = open(sys.argv[1])
b = open(sys.argv[2])
c = open(sys.argv[3])
for al, bl, cl in zip(a, b, c):
al, bl, cl = al.strip(), bl.strip(), cl.strip()
if al != '' and bl != '' and cl != '':
print('\t'.join([al, bl, cl]))
if __name__ == '__main__':
main... |
11414135 | import asyncio
import logging.config
from pathlib import Path
from symphony.bdk.core.activity.command import CommandActivity, CommandContext
from symphony.bdk.core.config.loader import BdkConfigLoader
from symphony.bdk.core.service.message.message_service import MessageService
from symphony.bdk.core.symphony_bdk impor... |
11414231 | from typing import Dict
from botocore.paginate import Paginator
class DescribeBudgets(Paginator):
def paginate(self, AccountId: str, PaginationConfig: Dict = None) -> Dict:
pass
class DescribeNotificationsForBudget(Paginator):
def paginate(self, AccountId: str, BudgetName: str, PaginationConfig: Dic... |
11414267 | from pycoin.encoding import hash160_sec_to_bitcoin_address
from coloredcoinlib import (ColorDataBuilderManager,
AidedColorDataBuilder,
FullScanColorDataBuilder, DataStoreConnection,
ColorDataStore, ColorMetaStore, ColorMap,
... |
11414269 | class Markup(object):
"""
individual instance of markup, found as a list within NonterminalSymbol
note:nonterminals do not have markup associated by default,
add it using nonterminal.add_Markup
"""
def __init__(self, tag, tagset):
"""
create new markup belonging to tagset with g... |
11414310 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import numpy as np
tf.set_random_seed(1)
# 参数设置
BATCH_SIZE = 256
TIME_STEP = 28
INPUT_SIZE = 28
LR = 0.001
NUM_UNITS = 128
ITERATIONS=50000 # 迭代次数
N_CLASSES=10 ... |
11414313 | import pytest
from pre_commit_dbt.unify_column_description import main
TESTS = ( # type: ignore
(
"""
version: 2
models:
- name: same_col_desc_1
columns:
- name: test1
description: test
- name: test2
description: test
- name: same_col_desc_2
columns:
- name:... |
11414319 | import abc
class setting:
'''
SettingModule: Abstract Class
Entries:
'''
setting_name = None
setting_description = None
dataset = None
method = None
result = None
evaluate = None
def __init__(self, sName=None, sDescription=None):
self.setting_name = sName... |
11414331 | import Configuration
from Classes.ByteStream import ByteStream
from Classes.Utility import Utility
class PiranhaMessage(ByteStream):
def __init__(self, messageData):
super().__init__(messageData)
self.messageBuffer = messageData
self.fields = {}
def decode(self, fields):
if Co... |
11414381 | from common.endpoints import BaseEndPoints
from common.servicer import BaseServicer
class PredictorServicer(BaseServicer):
pass
class PredictorEndPoints(BaseEndPoints):
async def predict(self):
result = self.engine.single_predict()
return {'result': result}
|
11414415 | from setuptools import setup, find_packages
setup(
name = 'japanese-numbers-python',
version = '0.2.1',
packages = find_packages(
'.',
exclude = [
'*.tests', '*.tests.*', 'tests.*', 'tests',
]
),
package_dir = {
'' : '.'
},
author = 'Takumakanari',
author_email = '<EMAIL>',
main... |
11414454 | from typing import Any, Optional, Type, Union
from pypika import Query
from tortoise import Model, fields
from tortoise.backends.odbc.executor import ODBCExecutor
from tortoise.exceptions import UnSupportedError
from tortoise.fields import BooleanField
def to_db_bool(
self: BooleanField, value: Optional[Union[b... |
11414456 | import datetime
import logging
import unittest
from typing import List
import mock
from ceph_salt.salt_event import SaltEventProcessor, EventListener, CephSaltEvent, \
SaltEvent, JobRetEvent
# pylint: disable=unused-argument
logger = logging.getLogger(__name__)
class SaltEventStream:
_events = []
_h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.