id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
471320 | import pandas as pd
# TODO: populate with classes to load
class_register = []
exclude_register = []
|
471333 | import subprocess
def run_bash_command(bashCommand):
print(bashCommand)
try:
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
return output
except:
print("couldn't run bash command, try running it manually") |
471338 | from indy import ledger
import json
import pytest
@pytest.mark.asyncio
async def test_build_pool_restart_request_work_for_start_action():
identifier = "Th7MpTaRZVRYnPiabds81Y"
expected_response = {
"identifier": identifier,
"operation": {
"type": "118",
"action": "sta... |
471359 | from peewee import *
database = MySQLDatabase('wefe_board', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'host': '10.**.**.**', 'port': 3306, 'user': 'wefe', 'password': '<PASSWORD>'})
class UnknownField(object):
def __init__(self, *_, **__): pass
class BaseModel(Model):
class Me... |
471361 | import sys
from torch.utils.data import DataLoader
from beta_rec.datasets.movielens import Movielens_100k
from beta_rec.datasets.seq_data_utils import (
SeqDataset,
collate_fn,
create_seq_db,
dataset_to_seq_target_format,
reindex_items,
)
sys.path.append("../")
if __name__ == "__main__":
ml... |
471395 | n = int(input())
login = []
logout = []
for i in range(n):
data = input().split()
login.append(data[0])
logout.append(data[1])
# print(login)
# print(logout)
user_num = 0
user_hot = 0
start_time = ''
end_time = ''
for hour in range(0, 24):
for minute in range(60):
time_now = f'{hour:02}:{minute... |
471461 | import thulac
import sys
import csv
import os
sys.path.append("..")
from Model.neo4j_models import Neo4j_Handle
thuFactory = thulac.thulac()
print('--init thulac()--')
#预加载Neo4j图数据库
neo4jconn = Neo4j_Handle()
neo4jconn.connectDB()
print('--Neo4j connecting--')
domain_ner_dict = {}
filePath = os.getcwd()
with open(... |
471479 | import RPi.GPIO
import sys
import random
sys.path.append("../../")
from gfxlcd.driver.ili9325.gpio import GPIO as ILIGPIO
from gfxlcd.driver.ili9325.ili9325 import ILI9325
RPi.GPIO.setmode(RPi.GPIO.BCM)
def hole(o, x, y):
o.draw_pixel(x+1, y)
o.draw_pixel(x+2, y)
o.draw_pixel(x+3, y)
o.draw_pixel(x+1,... |
471530 | import spacy
nlp = spacy.load("de_core_news_sm")
text = "Apple: Modell IPhone SE kommt im Sommer"
# Verarbeite den Text
doc = ____
# Iteriere über die Entitäten
for ____ in ____.____:
# Drucke Text und Label der Entität
print(____.____, ____.____)
# Erstelle eine Span für "IPhone SE"
iphone_se = ____
# Dr... |
471546 | from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import torch
from tests import utils
class TestQuantizedConv2dBigStrideSmallKernel(utils.TorchGlowTestCase):
# These tests should be run on NNPI card manually, or else
# buck test will only run them on emulato... |
471560 | import os
import sys
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import numpy as np
from keras.layers import Input
from keras.models import Model
sys.path.append(".") # To find local version of the library
from pix2pose_model import ae_model as ae
#find the last weight in each folder and convert it to the inference wei... |
471565 | from stix_shifter_utils.modules.base.stix_transmission.base_query_connector import BaseQueryConnector
import re
import json
from stix_shifter_utils.utils.error_response import ErrorResponder
from stix_shifter_utils.utils import logger
class UnexpectedResponseException(Exception):
pass
class QueryConnector(BaseQ... |
471582 | from collections import namedtuple
import math
from dydx3.constants import COLLATERAL_ASSET
from dydx3.constants import COLLATERAL_ASSET_ID_BY_NETWORK_ID
from dydx3.starkex.constants import CONDITIONAL_TRANSFER_FEE_ASSET_ID
from dydx3.starkex.constants import CONDITIONAL_TRANSFER_FIELD_BIT_LENGTHS
from dydx3.starkex.c... |
471674 | def get_max_possible(coins, amount=0, turn=True):
if not coins:
return amount
if turn:
alt_1 = get_max_possible(coins[1:], amount + coins[0], False)
alt_2 = get_max_possible(coins[:-1], amount + coins[-1], False)
return max(alt_1, alt_2)
first, last = coins[0], coins[-1]
... |
471724 | import aiohttp
# Working aiohttp get_url
# Now with closing sessions!
# <NAME>
async def get_url(url, headers: dict = None):
headers = headers or {"user-agent" : "GAF Bot"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
status = re... |
471729 | SURVEY_LIST_GET = {
'tags': ['기숙사'],
'description': '설문조사 리스트 불러오기(학생 학년에 따라 필터링됨)',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str',
'required': True
}
],
'responses': {
... |
471735 | import abc
import os
import boto3
class AssumeRoleInterface(abc.ABC):
@abc.abstractmethod
def get_client(self, service):
pass
@abc.abstractmethod
def _new_assumed_role_session(self, session, account, role_name):
pass
class AssumeRole(AssumeRoleInterface):
def __new__(cls, *args... |
471768 | import os
import re
import time
import json
import socket
import shutil
from .app import *
def check_hostname(hostname):
return True if re.match(r'([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+)', hostname) else False
def convert_hostnames(file_path):
with open(file_path, 'r+') as json_file:
data = jso... |
471778 | from Proxy import validateData
from Proxy import fetchData
from Proxy import parseData
from Core.Logger import log
import time
import threading
import queue
import configparser
import logging
# 代理信息键值字段
PROXY_ID = 'id'
PROXY_IP = 'ip'
PROXY_PORT = 'port'
PROXY_ADDRESS = 'address'
PROXY_PROTOCOL = 'proto... |
471779 | from __future__ import print_function
import os
import sys
os.environ['NPY_DISTUTILS_APPEND_FLAGS'] = '1'
# Check if we have numpy:
try:
from numpy.distutils.misc_util import Configuration
import numpy.distutils.core
from numpy.distutils.core import setup
except:
raise ImportError('pyOptSparse requir... |
471803 | from django import urls
from pghistory.tests import views
urlpatterns = [
urls.path('test-view', views.MyPostView.as_view(), name='test_view')
]
|
471804 | import unittest
from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.label import has_epic
from allure_commons_test.label import has_feature
from test.example_runner import run_docstring_example
class TestBDDLabel(unittest.TestCase):
def test_method_label(... |
471814 | import importlib
import os
import json
import numpy as np
import math
import sys
import pandas as pd
import datetime
import logging
import time
import torch
# ===================================== Common Functions =====================================
def check_input(imgs, targets):
import cv2 as cv
import nu... |
471816 | import torch
from torchvision.models import resnet18
import numpy as np
import pandas as pd
import os
def logic_learning(i2c_net, dataloader, device, optimizer, criterion, epoch, n_epochs, train=False):
running_loss = 0.0
c_correct = 0
c_total = 0
preds = []
total_step = len(dataloader)
for ba... |
471863 | import sys
path = sys.argv[1]
key = int(sys.argv[2])
buffer = bytearray(open(path, "rb").read())
for i in range(len(buffer)):
buffer[i] = buffer[i] ^ key
print(buffer.decode())
|
471893 | import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.CSCFakeDBGains = cms.ESSource("CSCFakeDBGains")
process.prefer("CSCFakeDBGains")
process.CSCFakeDBPedestals = cms.ESSource("CSCFakeDBPedestals")
process.prefer("CSCFakeDBPedestals")
... |
471900 | import pymysql
import time
HOST = "database-1.cluster-cti5mc0i9dvk.ap-northeast-2.rds.amazonaws.com"
USER = "the_red"
PASSWORD = "<PASSWORD>"
DB = "the_red"
connection = pymysql.connect(host=HOST,
user=USER,
password=PASSWORD,
dat... |
471920 | import inspect
import re
import collectd_haproxy.plugin
import collectd_haproxy.connection
import collectd_haproxy.metrics
import collectd_haproxy.compat
modules_to_test = (
collectd_haproxy.plugin,
collectd_haproxy.connection,
collectd_haproxy.metrics,
collectd_haproxy.compat,
)
def test_docstring... |
472031 | try:
from .GnuProlog import GNUProlog
except Exception:
pass
try:
from .SWIProlog import SWIProlog
except Exception:
pass
try:
from .XSBProlog import XSBProlog
except Exception:
pass
from .prologsolver import Prolog
|
472032 | import pyomo.environ as pe
import logging
import warnings
import math
logger = logging.getLogger(__name__)
pyo = pe
def _copy_v_pts_without_inf(v_pts):
new_pts = list()
for pt in v_pts:
if pt > -math.inf and pt < math.inf:
new_pts.append(pt)
return new_pts
def _get_bnds_list(v):
... |
472047 | from microscopes.kernels.slice import theta
from microscopes.irm.model import initialize, bind
from microscopes.common.relation.dataview import numpy_dataview
from microscopes.common.rng import rng
from microscopes.models import bbnc
from microscopes.irm.definition import model_definition
from microscopes.common.testu... |
472055 | from pathlib import Path
import re
import yaml
repo_dir = Path(__file__).parent.parent.parent.parent
resources_dir = repo_dir / 'resources'
# excel_path = resources_dir / 'Semio2Brain Database.xlsx'
semiology_dict_path = resources_dir / 'semiology_dictionary.yaml'
with open(semiology_dict_path) as f:
SemioDict = ... |
472058 | import os
import socket
if True:
sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sd.bind(('127.0.0.1', 1024))
sd.listen(10)
for i in range(3):
if os.fork () == 0:
while True:
cd, _ = sd.accept()
... |
472069 | from __future__ import print_function
import sys
import os
os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=C0413
import unittest
import logging
import torch
import copy # pylint: disable=C0411
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir + "/..... |
472070 | import cv2
import numpy as np
from transform import four_point_transform
import argparse
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
# What if ROI doesnt contain any lane?
# we can assume that lane is at the rightmost
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "pa... |
472073 | import sys, os.path
nodo_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '\\AST\\')
sys.path.append(nodo_dir)
c3d_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '\\C3D\\')
sys.path.append(c3d_dir)
entorno_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '... |
472074 | import argparse
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from rlo import experiment_result
from rlo import plotting
from rlo import utils
def plot_empirical_predicted_values(
outfile, title_suffix, events, probabilities=[10, 50, 90]
):
# import json # deter... |
472091 | import gin
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.keras.layers import Input, Concatenate, Dense
from reaver.models.base.layers import Squeeze, Variable, RunningStatsNorm
from reaver.envs.base import Spec
@gin.configurable
def build_mlp(
obs_spec: Spec,
act_spec: Spec,
laye... |
472094 | from .sankey_definition import ProcessGroup, Waypoint, Bundle, Elsewhere
from .ordering import new_node_indices, Ordering
def elsewhere_bundles(sankey_definition, add_elsewhere_waypoints=True):
"""Find new bundles and waypoints needed, so that every process group has a
bundle to Elsewhere and a bundle from El... |
472109 | from textwrap import dedent
import attr
import xsimlab as xs
from xsimlab.formatting import (
add_attribute_section,
maybe_truncate,
pretty_print,
repr_process,
repr_model,
var_details,
wrap_indent,
)
from xsimlab.process import get_process_obj
def test_maybe_truncate():
assert maybe... |
472114 | import pandas as pd
import numpy as np
import json
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.family": "CMU Serif"
})
def compute():
group = pd.read_csv('../data/2021-02-12to2021-02-26_deduped.csv').groupby("ENTITY_NAME")
data = group.size().reset_index().values.tolist()
x = list(map... |
472136 | import openmdao.api as om
from pycycle.maps.ncp01 import NCP01
import numpy as np
class StallCalcs(om.ExplicitComponent):
"""Component to compute the stall margins at constant speed (SMN) and constant flow (SMW)"""
def setup(self):
self.add_input('PR_SMN', val=1.0, units=None, desc='SMN pressure r... |
472215 | import matplotlib.pyplot as plt
import numpy as np
from math import sin
t = np.arange(-6.0, 6.0, 0.1)
sinData = np.array([sin(xi) for xi in t])
linearData = np.array([xi for xi in t])
deltaData = np.array([xi - sin(xi) for xi in t])
plt.axhline(0, color="black")
plt.axvline(0, color="black")
plt.plot(t, sinData, lab... |
472220 | import pytest
import sys
import os
present_dir = os.path.dirname(os.path.realpath(__file__))
root_dir = os.path.abspath(os.path.join(present_dir, '..', '..'))
sys.path.insert(0, root_dir)
from behave_webdriver.transformers import FormatTransformer
|
472231 | import numpy
import afnumpy
import numbers
class int64(numpy.int64):
def __new__(cls, x=0):
if isinstance(x, afnumpy.ndarray):
return x.astype(cls)
elif isinstance(x, numbers.Number):
return numpy.int64(x)
else:
return afnumpy.array(x).astype(cls)
class... |
472280 | import os
import sys
import argparse
import binascii
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
f = open(args.echo, 'rb')
ft = f.read()
ft_head = ft[:64]
str_num = ord(ft_head[44])
#ft_body = ft[64 + 52 * str_num:]
print "FILE LEN = ", len(ft)
for i in range(str_num):
... |
472294 | from django.conf import settings
from posthog.redis import get_client
def reload_plugins_on_workers():
get_client().publish(settings.PLUGINS_RELOAD_PUBSUB_CHANNEL, "reload!")
|
472299 | from keras.utils import to_categorical
from keras.models import model_from_json
from music21 import corpus, chord, note, pitch, interval
from config import maxChorales
import os.path
import numpy as np
def getChoralesIterator():
iterator = corpus.chorales.Iterator()
if maxChorales > iterator.highestNumber:
... |
472307 | from __future__ import print_function
import os
import re
import sys
import site
import shutil
from six import add_metaclass
from distutils.sysconfig import get_python_lib
from setuptools import setup, find_packages, Extension
from setuptools.command.install import install as install_default
def get_version():
v ... |
472342 | import logging
import os
import time
DEBUG = False
API_URL_PREFIX = "/anuvaad-etl/document-processor"
HOST = '0.0.0.0'
PORT = 5001
#BASE_DIR = '/opt/share/nginx/upload'
#download_folder = '/opt/share/nginx/upload'
BASE_DIR = 'upload'
download_folder = 'upload'
TASK_STAT = 'BLOCK-SEGMENTER'
ENABLE_CO... |
472359 | def logging_finish(self):
from .results import result_todf
# save the results
self = result_todf(self)
return self
|
472389 | from django.core.management.base import BaseCommand, CommandError
import logging
from django.core.mail import send_mail
from vital.models import VLAB_User
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Command to email common notifications to all relevant users"
def add_arguments(... |
472393 | from datetime import datetime
from functools import wraps
def dynamic(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for key, value in fn.__annotations__.items():
try:
kwargs[key] = value()
except TypeError:
pass
return fn(*arg... |
472426 | import enum
import functools
import json
from electrum_gui.common.basic import exceptions
from electrum_gui.common.basic.functional import json_encoders
@enum.unique
class Version(enum.IntEnum):
V1 = 1 # Legacy
V2 = 2 # Unify return values and exceptions
V3 = 3 # Single kwarg params as a json str
SU... |
472428 | import wx
APP_ID = u'TestJumpListApp'
def set_app_id():
import ctypes
try:
SetAppID = ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID
except AttributeError:
return
SetAppID(APP_ID)
def main():
set_app_id()
app = wx.App()
import cgui
assert cgui.SetUpJum... |
472434 | import os
import json
import urllib.request
from .rpsls import RPSLS
from .rpsls_dto import get_rpsls_dto_json
def get_pick_predicted(user_name):
queried_url = _get_queried_url(user_name)
response = _get_response_from_predictor(queried_url)
predicted_pick = RPSLS[response['prediction'].lower()]
return... |
472464 | import time
from tqdm import tqdm
import torch
import numpy as np
# assignments: V x D
# D: num_clusterings, V: num_total_set
# W: num_candidates, P: num_clustering_pairs, C: num_centroids
class EfficientMI:
""" this implementation requires the users to use the same ncentroids for all clusterings """
# N... |
472468 | from django.conf import settings
from django.contrib.auth.models import Permission
from django.urls import reverse, resolve
from django.utils.encoding import force_text as force_unicode
from garb.tests.models import *
from garb.tests.urls import *
from garb.templatetags.garb_menu import get_menu, Menu, ItemLink, ItemLi... |
472472 | import abc
import pickle
from os import path
import numpy as np
class Data(object):
data = None
heavy_hitters = None
heavy_hitter_freq = None
def __init__(self, n_bits):
self.n_bits = n_bits
self.heavy_size = 128
self.heavy_hitters = [0] * self.heavy_size
self.heavy_hitter_freq = [... |
472487 | import codecs
import imageio
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
import tweepy
import locale
import emoji
import sys
import re
import string
import os
def get_user_tweets(api, userna... |
472565 | import pygame as pg
class Platform(object):
def __init__(self, x, y, image, type_id):
self.image = image
self.rect = pg.Rect(x, y, 32, 32)
# 22 - question block
# 23 - brick block
self.typeID = type_id
self.type = 'Platform'
self.shaking = False
s... |
472575 | import torch.nn as nn
import torch.nn.functional as F
from .binary_functions import IRNetSign, RANetActSign, RANetWSign
import torch
import math
class BaseBinaryConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, groups=1, bias... |
472592 | from datetime import date
from decimal import Decimal
from controls.models import FinancialYear, ModuleSettings, Period
from django.conf import settings
from django.contrib.auth import get_user_model
from django.shortcuts import reverse
from django.test import TestCase
from nominals.models import Nominal, NominalTrans... |
472608 | import time
from base64 import b64encode
from .. import exceptions, const, config
from ..utils import misc
from ..models import deploy as models
from . import base
class Deploy(base.SoapService):
def _get_zip_content(self, input_file) -> str:
if isinstance(input_file, str):
input_file = open(i... |
472631 | import tensorflow as tf
from .bbox import *
from .Label import LabelEncoder
from .compute_IoU import visualize_detections
"""Preprocessing data
Preprocessing the images involves two steps:
Resizing the image: Images are resized such that the shortest size is equal to 224 px for resnet,
Applying augmentation: Random s... |
472661 | import unittest
from programy.config.brain.brain import BrainDynamicsConfiguration
from programy.dynamic.maps.map import DynamicMap
class MockDynamicMap(DynamicMap):
def __init__(self, config):
DynamicMap.__init__(self, config)
def map_value(self, client_context, input_value):
raise NotImpl... |
472696 | from trapper.data.data_adapters import DataAdapter, DataAdapterForQuestionAnswering
from trapper.data.data_collator import DataCollator, InputBatch, InputBatchTensor
from trapper.data.data_processors import DataProcessor, SquadDataProcessor
from trapper.data.data_processors.data_processor import IndexedInstance
from tr... |
472754 | from textwrap import dedent
from nuitka.plugins.PluginBase import NuitkaPluginBase
class NuitkaPluginFixBuild(NuitkaPluginBase):
plugin_name = "fix-build"
@staticmethod
def onModuleSourceCode(module_name, source_code):
if module_name == "torch.utils.data._typing":
source_c... |
472775 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .rnn import LSTM
class Embeddings(nn.Module):
def __init__(self, num_embeddings, embedding_dim, embed_weight=None, pad_idx=0, unk_idx=None, dropout=0.0, word_dropout=0.0):
super(Embeddings, self).__init__()
self.pad_idx = pad_... |
472779 | from .model import Model
from .vae import VAE
from .vi import VI
from .ml import ML
from .gan import GAN
__all__ = [
'Model',
'ML',
'VAE',
'VI',
'GAN',
]
|
472781 | import signal
import time
from leek_demo.app import app
@app.task(autoretry_for=(Exception,), retry_kwargs={'max_retries': 3})
def critical_task():
"""Will always fail/retry until max_retries"""
raise Exception("I'm a looser")
@app.task(autoretry_for=(Exception,), retry_kwargs={'max_retries': 3}, expires=... |
472851 | import urllib
import os
import time
import errno
import weakref
import base64
import json
import socket
#ASYNC
import asyncio
import aiohttp
from aiohttp import web
from urllib.parse import unquote
"""
HTTP Server interface
"""
def _get_viewer(ref):
#Get from weak reference, if deleted raise exception
lv = ... |
472853 | from core import *
from cameras import *
from geometry import *
from material import *
from helpers import *
import pygame
import random
class TestUpdatingTexture(Base):
def initialize(self):
self.setWindowTitle('Updating Textures')
self.setWindowSize(800,800)
self.renderer = Render... |
472859 | import numpy as np
import PIL.Image
import cv2
import math
import skimage.draw
import matplotlib.pyplot as plt
import pickle
import torch.nn.functional as F
import torch
# lighting functions
import lighting
# show image in Jupyter Notebook (work inside loop)
from io import BytesIO
from IPython.display import display,... |
472863 | from datetime import datetime
import pytz
class Entity(dict):
"""Common functionality for racing entities"""
def __init__(self, provider, property_cache, *args, **kwargs):
super(Entity, self).__init__(*args, **kwargs)
self.provider = provider
self.property_cache = dict(**property_c... |
472873 | r"""Command-line tool to start a debug proxy.
usage: python -m naoth.utils.DebugProxy host [port] [--target TARGET] [--print]
"""
import argparse
from . import DebugProxy
if __name__ == '__main__':
prog = 'python -m naoth.utils.DebugProxy'
description = 'A simple command line tool to start a naoth debug pro... |
472874 | import torch
from basic_nn import BasicNet
from spock.args import *
from spock.builder import ConfigArgBuilder
from spock.config import spock_config
@spock_config
class ModelConfig:
save_path: SavePathOptArg
n_features: IntArg
dropout: ListArg[float]
hidden_sizes: TupleArg[int]
activation: Choice... |
472883 | from unittest.mock import patch
import datasets
from datasets import Dataset
def test_enable_disable_progress_bar():
dset = Dataset.from_dict({"col_1": [3, 2, 0, 1]})
with patch("tqdm.auto.tqdm") as mock_tqdm:
datasets.disable_progress_bar()
dset.map(lambda x: {"col_2": x["col_1"] + 1})
... |
472924 | from keras_secure_image.secure_image import encrypt_directory, decrypt_img, transform_img, transform, rot, \
perform_rotation
|
472928 | from sock import *
from data import *
from shellcode import *
from pattern import *
try:
# Try to import the ipython interactive shell
from IPython import embed as ipython # drop to interactive shell
except ImportError as e:
import sys
sys.stderr.write('Warning: IPython embed could not be imported')
|
472930 | from typing import List, TYPE_CHECKING
if TYPE_CHECKING:
from interface import Interface
class Link:
def __init__(self, interfaces: List["Interface"]) -> None:
self.interfaces = sorted(interfaces)
def __eq__(self, other) -> bool:
return all(
int1 == int2 for int1, int2 in zip... |
472988 | import os
from click import UsageError
from click.testing import CliRunner
import numpy as np
import pytest
import rasterio
from rasterio.enums import Compression
from rio_color.scripts.cli import color, atmos, check_jobs
def equal(r1, r2):
with rasterio.open(r1) as src1:
with rasterio.open(r2) as src2:... |
473008 | import torch
import torch.optim as optim
from torch.autograd import Variable
import torch.nn as nn
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
from network import *
from dataset import *
from util import *
import time
import scipy.io
import os
import matplotlib.pyplot as plt
import... |
473071 | import logging
import json
from json.decoder import JSONDecodeError
from shutil import copyfile
import sqlite3
from .util import get_data_path, show_error
from .enums import ItemType
DATABASE_VERSION = 1
# decode item types stored in json.
# this is still required for migrating json data to sqlite
def decode_item... |
473076 | from django.forms import ModelForm, Select
from .models import CheckinSchedule
class CheckinScheduleForm(ModelForm):
class Meta:
model = CheckinSchedule
fields = ["timezone", "time_string"]
|
473096 | import matplotlib.pyplot as plt
from pandas import read_csv
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import numpy as np
from test_labels_loader import load_test_labels
def minmax_rescale(probability):
scaler = MinMaxScaler(feature_range=(0.000000001, 0.999999999))
return scaler.fit_trans... |
473119 | from .utils import efficientnet
from .EfficientNet import EfficientNet
from .pruning import *
from .early_exit import * |
473131 | import array_utils
import numpy
import pytest
def test_0_compile_pymod_test_mod(pmgen_py_compile):
pmgen_py_compile(__name__)
ndims_to_test = [1, 2, 3, 4]
# for loop, values
@pytest.mark.parametrize("ndim", ndims_to_test)
@pytest.mark.parametrize("nim_test_proc_name", [
"int32FindMaxForLoopValues... |
473155 | from soap.common.formatting import underline
from soap.expression.operators import FIXPOINT_OP
from soap.expression.arithmetic import QuaternaryArithExpr
class FixExprIsNotForLoopException(Exception):
"""FixExpr object is not a for loop. """
class FixExpr(QuaternaryArithExpr):
"""Fixpoint expression."""
... |
473159 | from models.notification import UserActivityNotification
from config.app import celery_app, app as flask_app
from tasks.notification import user_activity_digest
from models.user_activity_log import UserActivityLog
from models.user import User, Role
from utils.custom_exception import InvalidUsage
import json
import arro... |
473160 | from unittest import TestCase, skip
from pytezos import ContractInterface
code = """
parameter unit;
storage address;
code { DROP ;
SENDER ;
NIL operation ;
PAIR }
"""
initial = '<KEY>'
source = 'KT1WhouvVKZFH94VXj9pa8v4szvfrBwXoBUj'
sender = '<KEY>'
@skip
class SenderContractTest(TestCase):
... |
473167 | from .test import BaseTest
try:
# python3
from urllib.request import Request, urlopen, HTTPError
except ImportError:
# fall back to python2
from urllib2 import Request, urlopen, HTTPError
class Test_Format_Conneg(BaseTest):
label = 'Negotiated format'
level = 1
category = 7
versions = [... |
473221 | from pyps import workspace
with workspace("duplicate.c","duplicate/duplicate.c", preprocessor_file_name_conflict_handling=True) as w:
print ":".join([f.name for f in w.fun])
|
473223 | from pycocotools.coco import COCO
import sys, os
from dataset.image_base import *
class MuPoTS(Image_base):
def __init__(self,train_flag=True, split='val', **kwargs):
super(MuPoTS,self).__init__(train_flag)
self.data_folder = os.path.join(self.data_folder,'MultiPersonTestSet/')
self.split ... |
473252 | from typing import Sequence, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.systems.base_system import BaseSystem
class EMixSystem(BaseSystem):
'''Implements the i-Mix algorithm on embedded inputs defined in https://arxiv.org/abs/2010.08887.
Because there aren't predefine... |
473291 | import re
from regparser.layer.layer import Layer
from regparser.tree import struct
from regparser.tree.priority_stack import PriorityStack
from regparser.tree.xml_parser import tree_utils
class HeaderStack(PriorityStack):
"""Used to determine Table Headers -- indeed, they are complicated
enough to warrant t... |
473311 | class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
sizes = []
visited = [[False for value in row] for row in grid]
for i in range(len(grid)):
for j in range(len(grid[i])):
if visited[... |
473321 | import random
from collections import defaultdict
import numpy as np
from amplification.tasks.core import idk, uniform, Task, sequences
def matches(patterns, xs):
return np.all((patterns[:,np.newaxis,:] == SumTask.wild) |
(patterns[:,np.newaxis,:] == xs[np.newaxis, :, :]), axis=2)
class SumTas... |
473328 | import numpy as np
from mspasspy.ccore.utility import MsPASSError, AtomicType, ErrorSeverity, ProcessingStatus
from mspasspy.ccore.seismic import Seismogram, TimeSeries, TimeSeriesEnsemble, SeismogramEnsemble
def info(data, alg_id, alg_name, target=None):
"""
This helper function is used to log operations in ... |
473365 | from setuptools import setup
setup(
name='GaMMA',
version='1.0.0',
packages=['gamma'],
install_requires=[
'scikit-learn',
],
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.