id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11469498 | from __future__ import (
annotations,
)
from functools import (
lru_cache,
)
from typing import (
TYPE_CHECKING,
Any,
Iterable,
NamedTuple,
Optional,
Type,
Union,
)
from ...exceptions import (
MinosImportException,
)
from ...importlib import (
import_module,
)
from .generic... |
11469590 | import rasa
rasa.train(
domain="domain.yml",
config="config.yml",
training_files="data",
)
|
11469610 | import getpass
name = input('Write your name: ')
print('Welcome to the Hangman Game', name)
# Enter a word, her input will be hidden
hangman = getpass.getpass('Type a word: ')
# You will have a maximum of 5 attempts
print('Your goal is to get the word typed right. You can make a maximum of 5 mistakes')
print('\n')
... |
11469620 | graph = {"A": set(["B", "C"]),
"B": set(["A", "D", "E"]),
"C": set(["A", "F", "G"]),
"D": set(["B"]),
"E": set(["B"]),
"F": set(["C"]),
"G": set(["C"])}
def bfs(graph, start_node):
explored, fronteir = set(), [start_node]
while fronteir:
node = f... |
11469642 | from pathlib import Path
from canvas_workflow_kit.utils import parse_class_from_python_source
from .base import WorkflowHelpersBaseTest
from canvas_workflow_kit import events
from canvas_workflow_kit.protocol import (ProtocolResult, STATUS_DUE)
from canvas_workflow_kit.recommendation import (HyperlinkRecommendation)
... |
11469646 | features = [
{"name": "rte", "ordered": True, "section": ["net route "]},
{"name": "domain", "ordered": True, "section": ["net route-domain "]},
]
|
11469714 | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
matrix = [[0 for _ in range(n+1)] for _ in range(m+1)]
matrix[0][1] = 1
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
return m... |
11469778 | from request import LoyalRequest
from typing import Literal, Dict
from interface import OTAFirmware, RestoreFirmware
MDSVBV = "MobileDeviceSoftwareVersionsByVersion"
class AppleInternalHandler:
def __init__(self) -> None:
self.restore_cache = {}
self.ota_cache = {}
self.HTTP = LoyalRe... |
11469803 | import torch
import numpy as np
import pandas as pd
from agents.bbb import BBBAgent
from common.mushroom_env import MushroomEnv
NB_STEPS = 20000
N_SEEDS = 20
for i in range(N_SEEDS):
env = MushroomEnv()
agent = BBBAgent(env,
None,
mean_prior=0,
std_prior=0.1,
logging=True... |
11469812 | Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographica... |
11469823 | import numpy as np
import py.test
import random
from weldnumpy import weldarray, erf as welderf
import scipy.special as ss
'''
TODO0: Decompose heavily repeated stuff, like the assert blocks and so on.
TODO: New tests:
- reduce ufuncs: at least the supported ones.
- use np.add.reduce syntax for the reduce ufu... |
11469844 | import os
import time
from uninas.methods.abstract import AbstractMethod
from uninas.training.trainer.abstract import AbstractTrainerFunctions
from uninas.optimization.pbt.response import PbtServerResponse
from uninas.training.callbacks.abstract import AbstractCallback
from uninas.utils.torch.misc import itemize
from u... |
11469866 | import numpy as np
from psychopy import visual, monitors
from .. import exp
import unittest
# some modules are only available in Python 2.6
try:
from collections import OrderedDict
except:
from exp import OrderedDict
exp.default_computer.recognized = True # so that tests can proceed
PATHS = exp.set_paths('',... |
11469912 | import numpy as np # モジュールnumpyをnpという名前で読み込み
import csv # モジュールcsvの読み込み
from scipy import optimize # scipy内のoptimizeモジュールを読み込み
filename = 'out2' # 出力ファイル名
writer = csv.writer(open(filename + '.csv', 'w', newline='')) # 出力するcsvファイルの生成
writer.writerow(['step', 'f(x)', 'x1', 'x2']) # csvファイルへのラベルの書き込み
def f(x): #... |
11469953 | import unittest
import numpy as np
import pandas as pd
import scipy.stats as st
from ..analysis import GroupLinearRegression
from ..analysis.exc import MinimumSizeError, NoDataError
from ..data import UnequalVectorLengthError, Vector
class MyTestCase(unittest.TestCase):
def test_linregress_four_groups(self):
... |
11470011 | import pytest
import dpnp
import numpy
def _getattr(ex, str_):
attrs = str_.split(".")
res = ex
for attr in attrs:
res = getattr(res, attr)
return res
@pytest.mark.parametrize("func_name",
['abs', ])
@pytest.mark.parametrize("type",
[numpy.f... |
11470013 | import pytorch_lightning as pl
class Optimization(pl.LightningModule):
def __init__(self):
super(Optimization, self).__init__()
self.counters = {
'iteration': 0,
}
|
11470038 | import gdsfactory as gf
def test_get_ports() -> None:
c = gf.components.mzi_phase_shifter_top_heater_metal(length_x=123)
p = c.get_ports_dict()
assert len(p) == 4, len(p)
p_dc = c.get_ports_dict(width=11.0)
p_dc_layer = c.get_ports_dict(layer=(49, 0))
assert len(p_dc) == 2, f"{len(p_dc)}"
... |
11470060 | del_items(0x80147A14)
SetType(0x80147A14, "void EA_cd_seek(int secnum)")
del_items(0x80147A1C)
SetType(0x80147A1C, "void MY_CdGetSector(unsigned long *src, unsigned long *dst, int size)")
del_items(0x80147A50)
SetType(0x80147A50, "void init_cdstream(int chunksize, unsigned char *buf, int bufsize)")
del_items(0x80147A60... |
11470070 | from tests.support.asserts import assert_error, assert_success
def get_element_css_value(session, element_id, prop):
return session.transport.send(
"GET",
"session/{session_id}/element/{element_id}/css/{prop}".format(
session_id=session.session_id,
element_id=element_id,
... |
11470074 | import os
from flask import Flask, flash, redirect, request, Response, url_for, session
from flask_admin import Admin
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.contrib.twitter import make_twitter_blueprint, twitter
from flask_login import current_user, login_required, logout_user
... |
11470089 | from collections import defaultdict
from types import SimpleNamespace
class NestedNamespace(SimpleNamespace):
def __init__(self, dictionary, **kwargs):
super().__init__(**kwargs)
for key, value in dictionary.items():
if isinstance(value, dict):
self.__setattr__(key, Ne... |
11470100 | import sys
from importlib import import_module
import numpy as np
import pandas as pd
import pandas._testing as tm
import pytest
from numpy.testing import assert_array_equal
from pandas.testing import assert_frame_equal
from pandas.testing import assert_series_equal
from hcrystalball.exceptions import InsufficientDat... |
11470127 | import random
import torch
from torch import nn
import numpy as np
from .amr_graph import read_file
from .vocabs import PAD, UNK, DUM, NIL, END, CLS
# Returns cp_seq as a list of lemma + '_' and mp_seq is a list of the lemmas
# plus the dictionaries to convert the tokens to an index
# This represents the potent... |
11470242 | import basix
import numpy
import pytest
def xtest_create_simple():
# Creates Lagrange P1 element on triangle
# Point evaluation of polynomial set
degree = 1
points = numpy.array([[0, 0], [1, 0], [0, 1]], dtype=numpy.float64)
matrix = numpy.identity(points.shape[0])
# Create element from spac... |
11470252 | import os.path as osp
# data locations
prefix = './data'
train_name = 'deepfashion_train'
test_name = 'deepfashion_test'
knn = 5
knn_method = 'faiss'
train_data = dict(
feat_path=osp.join(prefix, 'features', '{}.bin'.format(train_name)),
label_path=osp.join(prefix, 'labels', '{}.meta'.format(train_name)),
... |
11470269 | from django.conf.urls import include, url
from localshop.apps.dashboard import views
app_name = 'dashboard'
repository_urls = [
# Package urls
url(r'^packages/add/$',
views.PackageAddView.as_view(),
name='package_add'),
url(r'^packages/(?P<name>[-._\w]+)/', include([
url(r'^$',
... |
11470293 | from plenum.test.testable import spyable
from sovrin_client.agent.walleted_agent import WalletedAgent
from sovrin_client.agent.runnable_agent import RunnableAgent
# @spyable(
# methods=[WalletedAgent._handlePing, WalletedAgent._handlePong])
class TestWalletedAgent(WalletedAgent, RunnableAgent):
pass
|
11470305 | from logging import getLogger
from shapely.geometry import Point, Polygon, shape, box, LineString
from shapely import speedups
from geopy import Nominatim
from pogeo import get_distance
if speedups.available:
speedups.enable()
class FailedQuery(Exception):
"""Raised when no location is found."""
class Lan... |
11470307 | from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.nn.layers.conv2Dnormed import *
from ceecnet.nn.layers.attention import *
from ceecnet.nn.pooling.psp_pooling import *
from ceecnet.nn.layers.scale import *
from ceecnet.nn.layers.combine import *
# CEEC units
from ceecnet.nn.units.ceecnet i... |
11470346 | from contextlib import contextmanager
from datetime import timedelta
from uuid import uuid4
from django.conf import settings
from django.db.models.deletion import ProtectedError
from django.test import SimpleTestCase, TestCase
from django.utils import timezone
from nose.tools import assert_in
from corehq.motech.cons... |
11470375 | import os
from pathlib import Path
import shutil
from unittest.mock import MagicMock
import pytest
from volttron.platform.vip.agent import Agent
from volttron.platform.web import PlatformWebService
from volttrontesting.utils.utils import AgentMock
from volttrontesting.utils.web_utils import get_test_web_env
@pytest... |
11470461 | import sys
import inspect
from types import FunctionType
def magic():
s = ''
f_locals = sys._getframe(1).f_locals
for var, value in inspect.getmembers(f_locals['self']):
if not (var.startswith('__') and var.endswith('__')) \
and var not in f_locals:
s += var + ' = self.' + v... |
11470486 | import os
import shutil
from pipscc import pipscc
pipscc(["pipscc","-c" , "basics0.c", "-o" , "/tmp/bb.o" ]).run()
pipscc(["pipscc","/tmp/bb.o", "-o" , "a.out"]).run()
os.remove("a.out")
os.remove("/tmp/bb.o")
|
11470494 | import os
import logging
import taco.logger.consts as logger_consts
LOGS_BASE_DIR_PATH = r'./Output/Logs/'
class KwargsLogger(object):
def __init__(self, logger=None, log_level=logging.DEBUG):
self._logger = logger
self.set_level(log_level)
def _format_message(self, message, **kwrags):
... |
11470535 | import numpy as np
from sciencebeam_gym.utils.bounding_box import BoundingBox
from sciencebeam_gym.utils.visualize_bounding_box import draw_bounding_box
class TestDrawBoundingBox:
def test_should_not_fail_with_float_bounding_box_values(self):
image_array = np.zeros((200, 200, 3), dtype='uint8')
d... |
11470542 | import time
from django.core.exceptions import ValidationError
from django.conf import settings
class AntiSpam(object):
def __init__(self):
self.spammed = 0
self.info = {}
def check_spam(self, json_message):
message_length = len(json_message)
info_key = int(round(time.time() * 100))
self.info[info_key]... |
11470566 | import torch
import numpy as np
class ProcessForce(object):
"""Truncate a time series of force readings with a window size.
Args:
window_size (int): Length of the history window that is
used to truncate the force readings
"""
def __init__(self, window_size, key='force', tanh=False... |
11470711 | import numpy as np
def tetra4_cell(elemList, nodeList):
nodeiRow = []
for i in range(len(elemList[:, 0])):
nodeiRow.append((4, int(np.argwhere(nodeList[:, 1] == elemList[i, 3])),
int(np.argwhere(nodeList[:, 1] == elemList[i, 4])),
int(np.argwhere(n... |
11470766 | import os
import struct
from twisted.trial import unittest
from twisted.internet.defer import inlineCallbacks
from twistar.registry import Registry
from floranet.models.device import Device
from floranet.models.application import Application
from floranet.appserver.azure_iot_mqtt import AzureIotMqtt
from floranet.da... |
11470788 | import logging
logger = logging.getLogger('peachy')
from peachyprinter.domain.layer_generator import LayerGenerator
from peachyprinter.domain.commands import LateralDraw, Layer, LateralMove
from math import pi, sin, cos, sqrt
class HalfVaseTestGenerator(LayerGenerator):
name = "Half Vase With A Twist"
def __... |
11470822 | from builtins import object
from django import forms
from pykeg.core import models
class NotificationSettingsForm(forms.ModelForm):
class Meta(object):
model = models.NotificationSettings
exclude = ["user", "backend"]
|
11470833 | from copy import deepcopy
from anasymod.templates.templ import JinjaTempl
from anasymod.generators.gen_api import SVAPI, ModuleInst
from anasymod.sim_ctrl.datatypes import DigitalSignal
class ModuleRegMapSimCtrl(JinjaTempl):
def __init__(self, scfg):
super().__init__(trim_blocks=True, lstrip_block... |
11470853 | from tkinter import Toplevel
from tkinter import Label
from tkinter import Frame
from tkinter import Button
from tkinter import GROOVE
from tkinter import NSEW
from tkinter import PhotoImage
from tkinter import Tk
import util.funcoes as funcoes
class SetLanguage():
def __init__(self, master, design, idioma, inter... |
11470865 | from sys import argv
#Define constants
POSITION_MARGIN_OF_ERROR = 50
DISTANCE_MARGIN_OF_ERROR = 50
#Open the files
bwaFile = open(argv[1], 'r')
igenomicsFile = open(argv[2], 'r')
def printDivider():
print("-----------------------------------------------------")
def alignmentsDictFromFile(file):
dct = {}
for line... |
11470882 | from djangobench.utils import run_benchmark
def setup():
global Book
from model_save_new.models import Book
def benchmark():
global Book
for i in range(0, 30):
b = Book(id=i, title='Foo')
b.save()
run_benchmark(
benchmark,
setup=setup,
meta={
'description': 'A sim... |
11470898 | import filestack.models
from filestack import utils
class ImageTransformationMixin:
"""
All transformations and related/dependent tasks live here. They can
be directly called by Transformation or Filelink objects.
"""
def resize(self, width=None, height=None, fit=None, align=None):
return ... |
11470922 | from pybullet_planning import INF
from copy import deepcopy
class LadderGraphEdge(object):
def __init__(self, idx=None, cost=-INF):
self.idx = idx # the id of the destination vert
self.cost = cost
# TODO: we ignore the timing constraint here
def __repr__(self):
return 'E idx{0}... |
11470941 | import csv
import datetime
from io import BytesIO, StringIO
import json
from urllib.parse import quote_plus
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import Http404, HttpResponse
from django.shortcuts import reverse
from django.template.loader import get_template
fr... |
11470945 | import logging
import os
import parsl
import pytest
import time
logger = logging.getLogger(__name__)
@parsl.python_app
def this_app():
return 5
@pytest.mark.local
def test_row_counts():
from parsl.tests.configs.htex_local_alternate import fresh_config
import sqlalchemy
if os.path.exists("monitoring... |
11471034 | num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
Output:
4321
|
11471135 | import gzip
import numpy
import os
import pandas
import random
from grocsvs import step
from grocsvs import utilities
from grocsvs import structuralvariants
from grocsvs.stages import cluster_svs
MAX_BARCODES = 200
class BarcodesFromGraphsStep(step.StepChunk):
"""
Collect barcodes supporting each candidate... |
11471140 | from django.test import TestCase
from rest_framework.exceptions import ValidationError
from rest_framework.fields import SkipField
from django_enumfield.contrib.drf import EnumField, NamedEnumField
from django_enumfield.tests.models import BeerState, LampState
class DRFTestCase(TestCase):
def test_enum_field(sel... |
11471143 | from datetime import datetime, timedelta
from openspaces import models
def get_ignored_users():
"""
Check app config table to get list of ignored twitter ids
"""
config_obj = models.OutgoingConfig.objects.latest("id")
ignore_list = [tw_id for tw_id in config_obj.ignore_users]
return ignore_lis... |
11471173 | import argparse
import os
import torch
import tqdm
from torch.utils.data import DataLoader
from datasets.qm9_property import TARGET_NAMES
from utils import misc as utils_misc
from utils.transforms import get_edge_transform
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_pat... |
11471197 | import numpy as np
#################################################################
# Implements the simulator class for MDPs
#################################################################
class MDPSimulator():
def __init__(self, model):
"""
Implements the multi-agent simulator:
This... |
11471258 | import numpy as np
import pandas as pd
import xgboost as xgb
import datetime
import operator
from sklearn.cross_validation import train_test_split
from collections import Counter
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from pylab import plot, show, subplot, specgram, imshow, savefig
RS = 1235... |
11471271 | from typing import Any, Dict, List, Type, TypeVar
import attr
from ..models.debug_info_connections import DebugInfoConnections
from ..models.debug_info_messages import DebugInfoMessages
from ..models.debug_info_recip_key_to_connection_id import DebugInfoRecipKeyToConnectionId
T = TypeVar("T", bound="DebugInfo")
@a... |
11471322 | from aston.trace.trace import Trace, Chromatogram, decompress
__all__ = ["Trace", "Chromatogram", "decompress"]
|
11471349 | pkgname = "unicode-cldr-common"
pkgver = "40.0"
pkgrel = 0
pkgdesc = "Common data from Unicode CLDR"
maintainer = "q66 <<EMAIL>>"
license = "Unicode-DFS-2016"
url = "https://cldr.unicode.org"
source = f"https://github.com/unicode-org/cldr/releases/download/release-{pkgver[:-2]}/cldr-common-{pkgver}.zip"
sha256 = "8d03c... |
11471350 | pkgname = "ruby"
pkgver = "3.1.0"
pkgrel = 0
build_style = "gnu_configure"
configure_args = [
"--enable-shared", "--disable-rpath", "--disable-install-doc",
"ac_cv_func_isnan=yes", "ac_cv_func_isinf=yes"
]
make_cmd = "gmake"
make_build_args = ["all", "capi"]
make_install_env = {"MAKE": "gmake"}
hostmakedepends ... |
11471376 | from boa3.builtin import CreateNewEvent
Event = CreateNewEvent([('a',)])
def Main():
Event()
|
11471384 | def payout_response():
return {
"id": "a6ee1bf1-ffcd-4bda-a7ab-99c1d5cd0472",
"external_id": "payout-1595405117",
"amount": 50000,
"merchant_name": "Xendit&#x27;s Intern",
"status": "PENDING",
"expiration_timestamp": "2020-07-23T08:05:19.815Z",
"cr... |
11471400 | try:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
except ImportError:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from libs.lib import newIcon, labelValidator
BB = QDialogButtonBox
class AdjustWindowLevelDialog(QDialog):
def __init__(self, text... |
11471456 | import os
import sys
import colorsys
sys.path.insert(0, './')
import glob
import string
import numpy as np
import pyvista as pv
import tensorflow as tf
from utils import helpers, tf_utils
def rotate_boxes(boxes, centers, theta):
pts_out = np.zeros((boxes.shape[0], 8, 3), np.float32)
for i, (b, c, r) in enumerat... |
11471464 | import sys
sys.path.append("..")
import numpy as np
from env.grid_world import GridWorld
from utils.plots import plot_gridworld
###########################################################
# Plot a grid world with no solution #
###########################################################
# specify ... |
11471490 | import sys
import pickle
import subprocess
import os
import re
import datetime
import time
#src/python/runGeoShapeBenches.py -compare -reindex -ant
reTotHits = re.compile('totHits=(\d+)$')
nightly = '-nightly' in sys.argv
compareRun = '-compare' in sys.argv
if nightly and compareRun:
raise RuntimeError('cannot ru... |
11471571 | import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
import sys
import datetime
import yaml
from vsmlib.benchmarks.sequence_labeling import load_data
import argparse
import vsmlib
from scipy.stats.stats import spearmanr
import os
import random
import math
def read... |
11471608 | import thorpy
def run():
application = thorpy.Application((800, 600), "ThorPy Overview")
element = thorpy.Element("Element")
thorpy.makeup.add_basic_help(element,"Element:\nMost simple graphical element.")
clickable = thorpy.Clickable("Clickable")
thorpy.makeup.add_basic_help(clickable,"Clickable... |
11471627 | import numpy as np
import scipy.linalg as la
import pdb
from nltk import ngrams
import difflib
import pickle
from time import time
import os
import torch
import urllib.request
from tqdm import tqdm
from scipy.spatial.distance import pdist, squareform
import scipy
from numpy import dot
from numpy.linalg import norm
imp... |
11471674 | from functools import cached_property
from wagtail.core.models import Page
from django.apps import apps
from strawberry import Schema
from strawberry.django.views import GraphQLView as BaseGraphQLView
from .schema import get_schema_from_models
def get_schema() -> Schema:
all_models = apps.get_models()
pa... |
11471689 | from .BaseDoc import BaseDoc
from .CPF import CPF
from .CNPJ import CNPJ
from .CNH import CNH
from .CNS import CNS
from .PIS import PIS
from .TituloEleitoral import TituloEleitoral
from .Certidao import Certidao
from .RENAVAM import RENAVAM
from .generic import validate_docs
|
11471713 | from eclcli.common import command
from eclcli.common import utils
from ..networkclient.common import utils as to_obj
class ListFICInterface(command.Lister):
def get_parser(self, prog_name):
parser = super(ListFICInterface, self).get_parser(prog_name)
return parser
def take_action(self, parsed... |
11471717 | from django.db import connection
from django.conf import settings
from django.core.management import call_command
from django.test import TransactionTestCase
from django_tenants.utils import get_public_schema_name
class BaseTestCase(TransactionTestCase):
"""
Base test case that comes packed with overloaded I... |
11471753 | import cv2
import numpy as np
def visualize_detection(img, bboxes_and_landmarks, save_path=None, to_bgr=False):
"""Visualize detection results.
Args:
img (Numpy array): Input image. CHW, BGR, [0, 255], uint8.
"""
img = np.copy(img)
if to_bgr:
img = cv2.cvtColor(img, cv2.COLOR_RGB2... |
11471775 | from typing import Union
from discord import Color
from discord.ext.commands import Cog, Context, command
from nagatoro.converters import Role, User, Member
from nagatoro.objects import Embed
from nagatoro.utils import t
class Utility(Cog):
"""Utility commands"""
def __init__(self, bot):
self.bot =... |
11471780 | import os
import yaml
def get_env():
env = None
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env_dir = os.path.join(base_dir, 'environments')
print(env_dir)
for fn in os.listdir(env_dir):
if fn.endswith('.yml'):
with open(os.path.join(env_dir, fn),... |
11471806 | from lib.parsers import parsers
class Message:
def __init__(self, header, length, id, rw, is_queued, params, direction='in'):
self.header = header
self.length = length
self.id = id
self.rw = rw
self.is_queued = is_queued
self.raw_params = []
self.params = []... |
11471828 | import json
def return_json_file_content(file_name: str):
"""
Load data from a json file
:param file_name: name of the file
:return: the data content extracted from the file
"""
with open(file_name) as json_file:
data = json.load(json_file)
return data |
11471851 | def test():
assert (
"for doc in nlp.pipe(TEXTS)" in __solution__
), "Verwendest du nlp.pipe, um die Texte zu verarbeiten?"
assert (
"TRAINING_DATA.append" in __solution__
), "Verwendest du die Methode append, um das Beispiel zu TRAINING_DATA hinzuzufügen?"
assert (
len(TRAIN... |
11471868 | from collections import namedtuple
from ..common.asap import _process_asap_token
from .backend import WSGIBackend
Request = namedtuple('Request', ['environ', 'start_response'])
class ASAPMiddleware(object):
def __init__(self, handler, settings):
self._next = handler
self._backend = WSGIBackend(se... |
11471887 | import uuid
def is_production():
""" Determines if app is running on the production server via uuid comparison.
HOW TO USE:
Open a terminal
> python
> import uuid
> uuid.getnode()
12345678987654321 <-- Copy whatever is returned and replace 111111111 with this.
Ensure .gitignore excl... |
11471948 | from kivy.animation import Animation
from functools import partial
from .base import Animator
__all__ = (
"RotateInAnimator",
"RotateInDownLeftAnimator",
"RotateInDownRightAnimator",
"RotateInUpLeftAnimator",
"RotateInUpRightAnimator",
)
# rotate in
class RotateInAnimator(Animator):
def start... |
11471957 | class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
res = [[0] * len(colsum) for _ in range(2)]
for j, sm in enumerate(colsum):
if sm == 2:
if upper == 0 or lower == 0:
return []
... |
11471962 | import sys
import argparse
import os
from os import listdir
from os.path import isfile, isdir, join
import numpy as np
import pandas as pd
import multiprocessing
import sys
sys.path.insert(0, "./")
import deepAccNet
import torch.optim as optim
import os
import matplotlib.pyplot as plt
import seaborn as sns
from t... |
11471985 | clsidx_2_labels = {
0: "frontal",
1: "profile45",
2: "profile75",
3: "upward",
4: "downward",
}
|
11471999 | import glob
import re
from html.parser import HTMLParser
from time import sleep
from urllib.parse import unquote_plus
from urllib.request import urlopen
def show_blob_content(description, key):
config_files = glob.glob('/var/lib/waagent/ExtensionsConfig*.xml')
if len(config_files) == 0:
raise Exceptio... |
11472013 | URANIUM_PY = """
from uranium import current_build
@current_build.task
def main(build):
current_build.history["test"] = True
"""
def test_current_build_in_ubuild(tmpdir, build):
""" current_build shoud be valid in the ubuild.py """
script = tmpdir.join("ubuild.py")
script.write(URANIUM_PY)
build.... |
11472016 | import abc
from typing import Optional
import torch
import numpy as np
import math
from duorat.utils import registry
def maybe_mask(attn: torch.Tensor, attn_mask: Optional[torch.Tensor]) -> None:
if attn_mask is not None:
assert all(
a == 1 or b == 1 or a == b
for a, b in zip(att... |
11472049 | import os, subprocess, time, signal
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import sys
from plark_game import classes
from gym_plark.envs.plark_env import PlarkEnv
import logging
logger = logging.getLogger(__name__)
# logger.setLevel(logging.ERROR)
class Pla... |
11472063 | import sys
import os
from pathlib import Path, WindowsPath
import importlib
from functools import wraps, reduce
import base64
import shutil
import inspect
from collections.abc import Iterable
from contextlib import contextmanager
from ploomber.exceptions import (CallbackSignatureError, CallbackCheckAborted,
... |
11472072 | from sklearn.cluster import AgglomerativeClustering as skAgglomerative
import numpy as np
from .base import Clustering
from ..similarity.pairwise import pairwise_similarity
class AgglomerativeClustering(Clustering):
"""Hierarchical Agglomerative Clustering.
Parameters
----------
n_clusters : int
... |
11472075 | import pytest
from setup_py_upgrade import main
def test_basic(tmpdir):
tmpdir.join('setup.py').write(
'from setuptools import setup\n'
'setup(name="foo")\n',
)
main((str(tmpdir),))
setup_py = tmpdir.join('setup.py').read()
setup_cfg = tmpdir.join('setup.cfg').read()
assert se... |
11472080 | from __future__ import absolute_import
input_name = '../examples/diffusion/time_advection_diffusion.py'
output_name_trunk = 'test_time_advection_diffusion'
from tests_basic import TestInputEvolutionary
class Test(TestInputEvolutionary):
pass
|
11472101 | import datetime
import os
import shutil
import tempfile
import unittest
from catkin_pkg.package_version import _replace_version
from catkin_pkg.package_version import bump_version
from catkin_pkg.package_version import update_changelog_sections
from catkin_pkg.package_version import update_versions
import mock
from ... |
11472111 | import os
import requests
headers = {
"Cookie": "arccount62298=c; arccount62019=c",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66"
}
while 1:
dicname = input()
try:
os.mkdir("./py/newimage/"+di... |
11472112 | from subprocess import call
from string import Template
jobs_spec= []
with open("jobs_info_both.txt") as f:
keys=[]
for i,line in enumerate(f.readlines()):
if i==0:
keys= line[:-1].split(",")
else:
if not line.startswith("#"):
values= line[:-1].split(",")
print(i,keys,values,le... |
11472149 | from __future__ import absolute_import, division, print_function
import os,sys
from cctbx.examples.merging import test_levenberg_sparse as test
import libtbx.load_env
# test script assumes that you get the data files directly from the author (NKS) and
# install them in the directory "xscale_reserve" at the same dir-le... |
11472170 | from bs4 import BeautifulSoup
import requests
from .content.document import ScribdTextualDocument
from .content.document import ScribdImageDocument
from .content.book import ScribdBook
from .content.audiobook import ScribdAudioBook
from .pdf_converter import ConvertToPDF
class Downloader:
"""
A helper class... |
11472210 | import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "" # Your Email
receiver_email = "" # Email of Receiver
password = "" # Your Password
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = send... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.