id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9925389 | import torch
from utils import get_args, timing, set_random_seed, get_device, get_dataset
from models import get_augmenter
from simple_estimator import SimPLEEstimator
from ablation_estimator import AblationEstimator
from trainer import Trainer
# for type hint
from typing import Optional, Type
from argparse import Na... |
9925414 | from . import mon # noqa
from .install import install # noqa
from .uninstall import uninstall # noqa
from ceph_deploy.util import pkg_managers
# Allow to set some information about this distro
#
distro = None
release = None
codename = None
def choose_init(module):
"""
Select a init system
Returns the n... |
9925466 | import os
import sys
import json
import cv2
import numpy as np
from hausdorff_dist import hausdorff_distance
def check_bbox_inside_with_roi(bbox, mask):
#check if four point of bbox all in roi area
is_inside = True
x_tl = bbox[1]
y_tl = bbox[2]
x_br = bbox[3]
y_br = bbox[4]
for x in [x_tl... |
9925492 | import PlayChess
import pytest
from .config import db_pass, db_user
@pytest.fixture
def client():
PlayChess.app.config['TESTING'] = True
client = PlayChess.app.test_client()
yield client
def login(client):
client.post('/login', data={
"username": db_user,
"password": <PASSWORD>,
... |
9925493 | numeros = input('').split(' ')
maior = int(numeros[0])
for x in numeros:
if int(x) > maior:
maior = int(x)
#Deve ser usada a versão 3.8 ou superior do python para funcionar a notação de f-string
print(f'{maior} eh o maior')
|
9925513 | import numpy as np
import torch
def k_reciprocal_neigh( initial_rank, i, k1):
forward_k_neigh_index = initial_rank[i,:k1+1]
backward_k_neigh_index = initial_rank[forward_k_neigh_index,:k1+1]
fi = np.where(backward_k_neigh_index==i)[0]
return forward_k_neigh_index[fi]
def pairwise_distance(query_featur... |
9925518 | import subprocess
theme = input('Enter theme ([l]ight/[d]ark): ')
if theme == 'l':
allowlight = '1'
command = ['reg.exe', 'add', 'HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize', \
'/v', 'AppsUseLightTheme', '/t', 'REG_DWORD', '/d', allowlight, '/f']
subprocess.run(comm... |
9925524 | import logging
from libgen_uploader import LibgenUploader
from returns.pipeline import is_successful
def main(args):
u = LibgenUploader(metadata_source=args.metadata_source, show_upload_progress=True)
if args.scitech:
result = u.upload_scitech(
file_path=args.file, metadata_query=args.me... |
9925538 | from .strategy.strategyTemplate import StrategyTemplate
from .push_engine.base_engine import BaseEngine as PushBaseEngine
from .push_engine.quotation_engine import DefaultQuotationEngine
from .log_handler.default_handler import DefaultLogHandler
from .main_engine import MainEngine |
9925566 | import os
import sys
import unittest
import bpy
import tests.test_utils as tutils
@tutils.refresh_state
def render_image(file, var, node_list=[], node_args=None):
node_groups = bpy.data.node_groups
if tutils.is_blendernc_in_nodetree(node_groups):
node_groups.remove(node_groups["BlenderNC"])
bpy... |
9925592 | import FWCore.ParameterSet.Config as cms
#------------------------------------------------
#AlCaReco filtering for HCAL Zmuu for HO:
#------------------------------------------------
from Calibration.HcalAlCaRecoProducers.alcazmumu_cfi import *
from Calibration.HcalAlCaRecoProducers.isoMuonHLT_cfi import *
seqALCARECO... |
9925601 | from jnpr.junos.utils.config import Config
from jnpr.junos import Device
dev = Device( user='netconf', host='172.16.0.1', password='<PASSWORD>' )
dev.open()
pod_number = "1"
set_cfg = """
set interfaces lo0.0 family inet address 10.255.255.{0}/32
set security zones security-zone trust interfaces lo0.0
set security... |
9925610 | from bisect import bisect_left
class Solution:
def searchInsert(self, A, target):
return bisect_left(A, target)
|
9925615 | pkgname = "tzutils"
pkgver = "2021e"
pkgrel = 0
build_style = "makefile"
make_build_args = ["TZDIR=/usr/share/zoneinfo", "KSHELL=/bin/sh"]
checkdepends = ["groff", "perl"]
pkgdesc = "Time zone and daylight-saving time utilities"
maintainer = "q66 <<EMAIL>>"
license = "custom:none AND BSD-3-Clause"
url = "http://www.ian... |
9925626 | import random
import copy
from collections import defaultdict
from utils import split_dataset_model_names, merge_dataset_model_name
def categorize_data_view(data, add_vid=False, align=False):
if not align:
return {k: categorize_data(v, add_vid) for k, v in data.items()}
else:
views, _ = match... |
9925636 | from django.core.management.base import BaseCommand
from apps.accounts.models import User
class Command(BaseCommand):
help = "My shiny new management command."
def handle(self, *args, **options):
valid_users = User.objects.raw(
"""
SELECT u.id, u.email, u.id_hp from fos_user a... |
9925652 | import tensorflow as tf
def swap_xy(boxes):
return tf.stack([boxes[:, 1], boxes[:, 0], boxes[:, 3], boxes[:, 2]],
axis=-1)
def convert_to_xywh(boxes):
return tf.concat(
[(boxes[..., :2] + boxes[..., 2:]) / 2.0,
boxes[..., 2:] - boxes[..., :2]],
axis=-1,
)
d... |
9925672 | import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import cv2
import numpy as np
import torch
from torch.autograd import Variable
import glob
import json
from PIL import Image as PILImage
import importlib
from torchvision.transforms import functional as F
import pickle
from argparse import ArgumentParser
from et... |
9925675 | from flask import Flask, render_template, session, request, jsonify
from flask_login import LoginManager, UserMixin, current_user, login_user, \
logout_user
from flask_session import Session
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION... |
9925678 | def Maximum_Sum(mat,n,k):
if k > n:
return 0
stripSum = [[0 for i in range(n)] for j in range(n-k+1)]
for j in range(n):
sum = 0
for i in range(k):
sum += mat[i][j]
stripSum[0][j] = sum
for i in range(1, n-k+1):
sum += (mat[i+k-1]... |
9925699 | class ContentType:
DOCUMENT = "local:document"
STRUCTURAL_FLAT = "local:structural-flat"
STREAM = "local:stream"
STRUCTURAL = "local:structural"
FLAT = "local:flat"
TEXT = "local:text"
RICHTEXTFIELD = "local:RichTextField"
class XliffElements:
TEXT = "#text"
GROUP = "group"
DAT... |
9925738 | from utils import (get_log_lines, is_vshard_bootstrapped,
run_command_and_get_output)
def test_bootstrap(cartridge_cmd, project_with_vshard_replicasets):
project = project_with_vshard_replicasets.project
instances = project_with_vshard_replicasets.instances
# bootstrap vshard
cmd =... |
9925778 | class JustMonika:
__cj = [
"j",
"𝔍",
"𝕵",
"𝕁",
"Ĵ",
"ɟ",
"ʄ",
"ᴊ",
]
__cu = [
"Ù",
"Ű",
"ű",
"Ų",
"𝓾",
"𝖀",
"𝕌",
]
__cs = [
"Ṧ",
"Ṡ",
"Ş",
"Ṣ... |
9925782 | import os
import shutil
# define the name of the directory to be created
def create_dir(path='.efsync'):
try:
os.mkdir(path)
except OSError:
# print("Creation of the directory %s failed" % path)
return False
else:
# print("Successfully created the directory %s " % path)
... |
9925815 | from botocore.client import BaseClient
import boto3
import os
import json
import pickle
from botocore.exceptions import ClientError
access_key = 'AWS_ACCESS_KEY_ID'
access_value = os.getenv(access_key)
secret_key = 'AWS_SECRET_ACCESS_KEY'
secret_value = os.getenv(secret_key)
bucket_name = "ibmqo"
class S3client:
... |
9925852 | import pytest
from selenium.webdriver.common.keys import Keys
from stere.fields import Input
input_before_str = 'before'
input_after_str = 'after'
@pytest.fixture(scope='session')
def dummy_input():
class Dummy(Input):
def before(self):
global input_before_str
input_before_str ... |
9925875 | import numpy as np
import os
from mult import read_mult
def downloadData():
data_url = 'https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/cdl'
for filename in ('mult.dat', 'cf-train-1-users.dat', 'cf-test-1-users.dat', 'raw-data.csv'):
if not os.path.exists(filename):
os.system(... |
9925903 | import argparse
import collections
import editdistance
import json
import numpy as np
import re
import sklearn
from fuzzywuzzy import fuzz
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from stop_word... |
9925967 | import setuptools
with open('README.rst', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='kenning',
version='0.0.1',
packages=setuptools.find_packages(),
long_description=long_description,
include_package_data=True,
description="Kenning - a framework for implementing and t... |
9925981 | import scapy.all as scapy
from tabulate import tabulate
import socket
from datetime import datetime
import requests
from operator import itemgetter
hosts = dict()
# DISCOVER HOSTS ON NETWORK USING ARPING FUNCTION
print(
"\n\n----- Discovery hosts on network using arping() function ---------------------"
)
ans, u... |
9926032 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
###################################################
def GetConditionName():
return "Bard"
def GetSpellCasterConditionName():
return "Bard Spellcasting"
print "Registering " + GetSpellCasterConditionName()
classEnu... |
9926100 | from .dashboard import DashboardView
from .models import *
from .modelselection import *
from .person import PersonView
from .setup import SetupView
from .dataset import DatasetView
from .config import ConfigView
from .webhook import WebhookView
from .datasetAnalytics import DatasetAnalyticsView |
9926132 | from bokeh.plotting import figure, output_file, show
output_file("bounds.html")
p = figure(plot_width=400, plot_height=400)
p.circle([1,2,3,4,5], [2,5,8,2,7], size=10)
p.xaxis.axis_label = "Lot Number"
p.xaxis.axis_label_text_color = "#aa6666"
p.xaxis.axis_label_standoff = 30
p.yaxis.axis_label = "Bin Count"
p.yaxi... |
9926158 | import pronoun_detect_2 as pd2
import json
import os
import urllib.request
import etri
import argparse
import socket
import struct
from urllib.parse import quote
import urllib.request
import re
NER_dic = {'PERSON': 0, 'TIME': 1, 'LOCATION' : 2, 'ORGANIZATION' : 3, 'EVENT': 4, 'ETC' : 5}
description = "[--input_path]... |
9926193 | import unittest
from inselect.lib.persist_user_template import (validated_specification,
InvalidSpecificationError)
class TestValidateUserTemplate(unittest.TestCase):
"""Tests the validation of user templates
"""
def _invalid_specification(self, specificati... |
9926202 | import os
import json
from collections import defaultdict
import numpy as np
from .base import BaseParser
class MMDETParser(BaseParser):
"""Class of parser for mmdetection bbox result format.
Args:
anno_path (str): Path of annotation file.
imgid2filename (dict): Mapping relations between im... |
9926234 | from benchlingapi.models import schema
def test_field_schema():
s = schema.FieldSchema()
d = s.load({"isMulti": True, "textValue": None, "type": "dropdown", "value": []})
print(s.dump(d))
|
9926239 | import getpass
import os
APPLICATION_NAME = "Conbench"
class Config:
APPLICATION_NAME = os.environ.get("APPLICATION_NAME", APPLICATION_NAME)
DB_HOST = os.environ.get("DB_HOST", "localhost")
DB_NAME = os.environ.get("DB_NAME", f"{APPLICATION_NAME.lower()}_prod")
DB_PASSWORD = os.environ.get("DB_PASSWO... |
9926276 | import functools
import types
from collections import OrderedDict
from sklearn_import.externals.funcsigs import _NonUserDefinedCallables, _get_user_defined_method, \
_POSITIONAL_ONLY, _VAR_POSITIONAL, _VAR_KEYWORD, Signature
def signature(obj):
'''Get a signature object for the passed callable.'''
if no... |
9926347 | import pytest
from usim.py import Environment
from .utility import via_usimpy, UnfinishedTest
class TestTests:
"""Test propagation of test exceptions/signals"""
@pytest.mark.xfail(strict=True)
@via_usimpy
def test_failure(self, env: Environment):
"""Test failure in a top-level activity"""
... |
9926349 | from urllib import quote_plus
from celery.schedules import crontab
class HardCoded(object):
"""Constants used throughout the application.
All hard coded settings/data that are not actual/official configuration options for Flask, Celery, or their
extensions goes here.
"""
ADMINS = ['<EMAIL>']
... |
9926356 | import numpy as np
from scipy.interpolate import interp1d
from .base import Prior
from ..utils import logger
class Interped(Prior):
def __init__(self, xx, yy, minimum=np.nan, maximum=np.nan, name=None,
latex_label=None, unit=None, boundary=None):
"""Creates an interpolated prior functio... |
9926394 | from setuptools import setup
with open('README.rst') as f:
readme = f.read()
setup(
name="pytest-interactive",
version='0.1.4',
description='A pytest plugin for console based interactive test selection'
' just after the collection phase',
long_description=readme,
licens... |
9926409 | import random
def run_ransac(data, estimate, is_inlier, sample_size, goal_inliers, max_iterations, stop_at_goal=True, random_seed=None):
best_ic = 0
best_model = None
random.seed(random_seed)
# random.sample cannot deal with "data" being a numpy array
data = list(data)
for i in range(max_iterat... |
9926506 | import wandb
from tqdm import tqdm
from attack_helpers import *
import sys
sys.path.append("..") # Adds higher directory to python modules path.
from utils.utils import load_unk_model
from advertorch.attacks import LinfPGDAttack, L2PGDAttack
kwargs_PGD_attack = {'Linf': LinfPGDAttack, 'L2': L2PGDAttack}
class Test_ge... |
9926526 | class ProvincialClass():
def __init__(self):
print("here")
class HiddenClass():
def __init__(self):
print("here")
def imported_func():
print("here")
|
9926558 | from argparse import ArgumentParser, HelpFormatter
from os import environ, getcwd
from pathlib import Path
from shutil import rmtree
from snowddl.app.base import BaseApp
from snowddl.blueprint import ObjectType
from snowddl.config import SnowDDLConfig
from snowddl.converter import default_converter_sequence
from snowd... |
9926606 | import numpy as np
from typing import Dict, Tuple
import torch
from torch.utils.data import Dataset
from torch.autograd import Variable
import random
class SegmentationBatchHandler:
def __init__(self, training, num_tta):
self._training = training
self._num_tta = num_tta
if self._training:... |
9926644 | import os
import shutil
import time
import pytest
from pathlib import Path
from ipvc import IPVC
from helpers import NAMESPACE, REPO, REPO2, get_environment, write_file
def test_init_and_ls():
cwd = Path('/current/working/dir')
ipvc = get_environment(cwd, mkdirs=False)
repos = ipvc.repo.ls()
assert l... |
9926662 | import json
from .oauth import OAuth2Test
class ScistarterOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.scistarter.SciStarterOAuth2'
user_data_url = 'https://scistarter.com/api/user_info'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
... |
9926693 | import pscheduler
from json import dumps
import unittest
class TestSpecIsValid(pscheduler.TestSpecIsValidUnitTest):
name="throughput"
def test_basic(self):
# minimal
test_input = {
"dest": "127.0.1.1"
}
self.assert_cmd(dumps(test_input))
# al... |
9926698 | from ..lib.transformer import Transformer
from ..lib.instruction import Instruction
import utils
class Email(Transformer):
def can_handle_character(self, character):
return utils.is_character_common(character)
def can_handle_contact(self, contact, clock):
return contact.has('email')
def ... |
9926701 | from typing import TYPE_CHECKING
import dask.dataframe as dd
from dask_sql.datacontainer import ColumnContainer, DataContainer
from dask_sql.physical.rel.base import BaseRelPlugin
if TYPE_CHECKING:
import dask_sql
from dask_sql.java import org
class LogicalUnionPlugin(BaseRelPlugin):
"""
LogicalUni... |
9926710 | from math import cos, pi, tanh
from functools import partial
def anneal_linear(start, end, proportion):
return start + proportion * (end - start)
def anneal_cos(start, end, proportion):
cos_val = cos(pi * proportion) + 1
return end + (start - end) / 2 * cos_val
def anneal_cospow(start, end, proportio... |
9926712 | import os
import sys
import numpy as np
from flare.otf_parser import OtfAnalysis
from flare.env import AtomicEnvironment
from flare.predict import predict_on_structure
from ase.io import read
def test_parse_header():
os.system("cp test_files/sample_slab_otf.out .")
header_dict = OtfAnalysis("sample_slab_otf... |
9926757 | import sys
#sys.path.insert(0,'../src/build/lib.linux-i686-2.4')
import cdms
import spanlib
import vcs
import MV
import Numeric
import cdutil
import genutil
cdms.axis.latitude_aliases.append('Y')
cdms.axis.longitude_aliases.append('X')
cdms.axis.time_aliases.append('T')
f=cdms.open('../example/data2.cdf')
s=f('ssta'... |
9926817 | from typing import Callable, Dict, List, Set, Optional
from ctypes import c_int8 as i8, c_int16 as i16, c_int32 as i32, c_int64 as i64
from ctypes import c_uint8 as u8, c_uint16 as u16, c_uint32 as u32, c_uint64 as u64
import sys
from tempfile import NamedTemporaryFile
if __name__ == "__main__":
if True:
t... |
9926828 | from lol_dto.classes.game.lol_game import (
LolGame,
LolGameTeams,
LolPickBan,
LolGamePause,
)
from lol_dto.classes.game.lol_game_team import LolGameTeam, LolGameTeamEndOfGameStats
from lol_dto.classes.game.lol_game_player import (
LolGamePlayer,
LolGamePlayerRune,
LolGamePlayerItem,
Lol... |
9926841 | from flask.views import MethodView
from flask.json import jsonify, dumps
from flask import request
from sqlalchemy import func
from app import app, db
from app.wordseer import wordseer
from app.models import *
from app.helpers.application_view import register_rest_view
class DocumentsView(MethodView):
... |
9926873 | from datetime import timedelta, datetime
from typing import List
import jwt
from starlette.requests import Request
from fastapi import HTTPException, Security, Depends
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from boucanpy.core import logger, abort
from boucanpy.core.to... |
9926959 | class Solution:
def canCross(self, stones: List[int]) -> bool:
fail = set()
stone_set = set(stones)
stack = []
stack.append((0,0))
while stack:
cur_pos, jump = stack.pop()
for j in (jump-1, jump, jump+1):
pos = cur_pos+j
... |
9926976 | import hashlib
from lazydocs import MarkdownGenerator
def test_import2md() -> None:
generator = MarkdownGenerator()
markdown = generator.import2md(MarkdownGenerator.import2md)
# Remove whitespaces: fix changes between py version 3.6 3.7 in signature method
md_hash = hashlib.md5(markdown.replace(" ", ... |
9927011 | from pathlib import Path
def hugo_in_docker_or_local():
"""Checks if there's a `docker-compose.yml` in local directory. If so, prefer that
to a local hugo installation.
"""
if Path("docker-compose.yml").exists():
hugo = "docker-compose run hugo"
else:
hugo = ""
return " ".join... |
9927031 | import configparser
import logging
from pathlib import Path
log = logging.getLogger()
def get_config():
config = configparser.ConfigParser()
file_path = Path('config/config.ini')
if file_path.exists():
config.read_file(open(file_path, 'r'))
else:
log.critical(f'Could not find the con... |
9927032 | import unittest
from unittest.mock import patch, MagicMock
from mypy_boto3_builder.import_helpers.import_record import ImportRecord
from mypy_boto3_builder.import_helpers.import_string import ImportString
class ImportRecordTestCase(unittest.TestCase):
def test_str(self) -> None:
source_mock = MagicMock()... |
9927074 | from datetime import timedelta
from typing import Dict, Optional, List
import pytest
from pytest import fixture
from resotocore.error import NoSuchTemplateError
from resotocore.query.model import Template
from resotocore.query.template_expander import render_template, TemplateExpanderBase, TemplateExpander
from resot... |
9927083 | from pygtail import Pygtail
import sys
from output_module import ExportData
from socket import gethostname
"""
Collects log information and uploads it as a metric.
Uses the pygtail library which is installed via pip
"""
def parse_logs():
data = ExportData("logs")
reason = ""
peer = ""
for line in P... |
9927084 | import sympy.physics.mechanics as _me
import sympy as _sm
import math as m
import numpy as _np
x, y = _me.dynamicsymbols('x y')
a, b, r = _sm.symbols('a b r', real=True)
eqn = _sm.Matrix([[0]])
eqn[0] = a*x**3+b*y**2-r
eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]]))
eqn[eqn.shape[0]-1] = a*_sm.sin(x)**2+b*_sm.co... |
9927118 | import FIAT
import finat
import numpy as np
from gem.interpreter import evaluate
from fiat_mapping import MyMapping
def test_morley():
ref_cell = FIAT.ufc_simplex(2)
ref_element = finat.Morley(ref_cell, 2)
ref_pts = finat.point_set.PointSet(ref_cell.make_points(2, 0, 4))
phys_cell = FIAT.ufc_simplex(... |
9927155 | import os
import geopandas as gpd
import pandas as pd
import pytest
import trackintel as ti
from geopandas.testing import assert_geodataframe_equal
from pandas.testing import assert_frame_equal, assert_index_equal
from shapely.geometry import Point, Polygon, MultiPoint
from trackintel.io.from_geopandas import (
_t... |
9927208 | import sys
global _GLAvailable,_GLModule,_BackendStatus,_GLBackend
_GLAvailable = None
_GLModule = None
_BackendStatus = dict()
_GLBackend = None
_BackendString = None
_PIP_String = 'pip' if sys.version_info[0] < 3 else 'pip3'
#compatibility with MacOS X 11.x
try:
import OpenGL.GL # this fails in <=2020 versions... |
9927241 | from polyphony import testbench
def list24(x):
data0 = [x]
data1 = [x, x]
data2 = [x, x, x]
data3 = [x, x, x, x]
if x == 0:
d = data0
elif x == 1:
d = data1
elif x == 2:
d = data2
else:
d = data3
return len(d)
@testbench
def test():
assert 1 == l... |
9927262 | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import database_exists, create_database
# For other databases read http://docs.sqlalchemy.org/en/latest/core/engines.html
# http://docs.... |
9927281 | import tensorflow as tf
def crop_quarters(feature_tensor):
N, fH, fW, fC = feature_tensor.shape.as_list()
quarters_list = []
quarter_size = [N, round(fH / 2), round(fW / 2), fC]
quarters_list.append(tf.slice(feature_tensor, [0, 0, 0, 0], quarter_size))
quarters_list.append(tf.slice(feature_tensor, [0, round... |
9927297 | import six
import time
from six.moves.queue import Empty
def urlpathjoin(*parts):
"""Join multiple paths into a single url
>>> urlpathjoin('https://storage.scrapinghub.com:8002/', 'jobs', '1/2/3')
'https://storage.scrapinghub.com:8002/jobs/1/2/3'
>>> urlpathjoin('https://storage.scrapinghub.com:8002'... |
9927303 | import unittest
import numpy as np
import matplotlib.pyplot as plt
from mpltern.ternary import TernaryAxes
from mpltern.ternary.datasets import get_spiral
from pyrolite.util.plot.axes import (
replace_with_ternary_axis,
axes_to_ternary,
get_axes_index,
get_ordered_axes,
get_twins,
sha... |
9927352 | from __future__ import print_function
from __future__ import absolute_import
from . import _, config
# GUI (Screens)
from Screens.MessageBox import MessageBox
#from Tools.Notifications import AddPopup
# Plugin
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDescriptor
from boxbranding ... |
9927387 | import pandas as pd
def generate_auxiliary(gold_key_file_name, train_file_name, train_file_final_name):
sense_data = pd.read_csv("./wordnet/index.sense.gloss",sep="\t",header=None).values
print(len(sense_data))
print(sense_data[1])
d = dict()
for i in range(len(sense_data)):
s = sense_d... |
9927408 | import random
import numpy as np
import torch
from torch.utils.data.dataloader import default_collate, DataLoader
from torch.utils.data.sampler import Sampler
__all__ = ['Text2MelDataLoader', 'SSRNDataLoader']
class Text2MelDataLoader(DataLoader):
def __init__(self, text2mel_dataset, batch_size, mode='train', n... |
9927426 | import pickle
aconf_dict = {
"Va_1s": "Va\n" \
+ "Iz= 0 Norb= 0 Ion= 0 Config= 1s0\n" \
+ "n 1\n" \
+ "Kappa -1\n" \
+ "Occup 0\n" \
+ "Valen 1\n",
"Em_1s": "Em\n" \
+ "Iz= 0 Norb= 0 Ion= 0 Config= 1s0\n" \
+ "n 1\n" \
+ "Kapp... |
9927430 | import datetime
import time
import pytest
import requests
from google.transit import gtfs_realtime_pb2 as gtfs
ONE_DAY_IN_SECONDS = 60 * 60 * 24
TIME_1 = datetime.datetime.utcfromtimestamp(time.time() - ONE_DAY_IN_SECONDS)
TIME_2 = datetime.datetime.utcfromtimestamp(time.time() + ONE_DAY_IN_SECONDS)
ALERT_SMALL_JSON... |
9927432 | import json
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import absl.flags as flags
from absl import app
import tools.geom_utils as g
import tools.image_utils as i_util
FLAGS = flags.FLAGS
class Perspective3d(nn.Module):
def __init__(self, camK, z_range=1, R=None, t=None, s=None, ... |
9927436 | import argparse
import asyncio
import inspect
import logging
import sys
from ..constants import DEFAULT_INI_PATH, DEFAULT_INI_SECTION
from . import helpers, interact, misc, rest_api, restlet, soap_api
__all__ = ("main",)
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDef... |
9927455 | from __future__ import absolute_import
from functools import reduce
def get_value(d, *keys):
return reduce(lambda a, b: a[b], keys, d)
def first_item(l):
"""Returns first item in the list or None if empty."""
return l[0] if len(l) > 0 else None
class cache(object):
'''Computes attribute value and c... |
9927461 | import time
from anubis.lms.autograde import bulk_autograde
from anubis.models import db
from anubis.utils.data import with_context
from anubis.utils.testing.db import clear_database
from anubis.utils.testing.seed import create_assignment, create_course, create_students, init_submissions
def do_seed() -> str:
cl... |
9927463 | description = 'alias for the current sample changer'
group = 'lowlevel'
devices = dict(
SampleChanger = device('nicos.devices.generic.DeviceAlias'),
)
|
9927534 | import inspect
import warnings
from functools import partial
from typing import Callable, Union
import logging
from logging import handlers as logging_handlers
from .color_provider import ColorFormatter
from .utils import ensure_dir, get_logger_config, get_color_config
from .exceptions import InvalidOption, Duplicat... |
9927540 | import pytest
import ibis.expr.datatypes as dt
pa = pytest.importorskip('pyarrow')
@pytest.mark.parametrize(
('datatype', 'expected'),
[
(pa.int8(), dt.int8),
(pa.int16(), dt.int16),
(pa.int32(), dt.int32),
(pa.int64(), dt.int64),
(pa.uint8(), dt.uint8),
(pa.u... |
9927577 | import sqlite3
import hashlib
from flask import Flask, request
app = Flask(__name__)
def connect():
conn = sqlite3.connect(':memory:', check_same_thread=False)
c = conn.cursor()
c.execute("CREATE TABLE users (username TEXT, password TEXT, rank TEXT)")
c.execute("INSERT INTO users VALUES ('admin', '<... |
9927615 | load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
load("//ocaml:providers.bzl",
"CompilationModeSettingProvider",
"OcamlNsResolverProvider")
load("//ocaml/_functions:utils.bzl",
"capitalize_initial_char",
"normalize_module_label",
"get_fs_prefix",
"get_opamroot",
... |
9927616 | from __future__ import absolute_import, unicode_literals
from datetime import datetime, timedelta
from threading import Lock
from six.moves.queue import Queue, Empty
from .errors import ClientUnavailableError
class Connection(object):
def __init__(self, connection):
self.connection = connection
... |
9927697 | import pytest
from simple_settings.strategies.json_file import SettingsLoadStrategyJson
class TestJsonStrategy:
@pytest.fixture
def strategy_json(self):
return SettingsLoadStrategyJson
def test_should_check_a_valid_json_file(self, strategy_json):
assert strategy_json.is_valid_file('foo.... |
9927705 | from .dict_hash import sha256, dict_hash
from .hashable import Hashable
from .validate_consistent_hash import validate_consistent_hash
__all__ = ["sha256", "dict_hash", "Hashable", "validate_consistent_hash"]
|
9927758 | from typing import Tuple
import numpy as np
def get_minus1_start_end(ints: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
iminus1 = np.where(ints == -1)[0]
istart = [0] + list(iminus1[:-1] + 1)
iend = iminus1
return istart, iend
|
9927767 | import math
import time
import kopf
import collections
import json
import pandas as pd
from kubernetes import client, config
from utils import getAveragePodUsage, getCurrentReplicas, getMultiClusterDeployment, getMultiClusterService
# Create federated HPA
@kopf.daemon('fogguru.eu', 'v1', 'multiclusterhorizontalpodauto... |
9927774 | from stix_shifter.stix_translation import stix_translation
from stix_shifter_utils.utils.error_response import ErrorCode
import unittest
import re
MODULE = "proofpoint"
translation = stix_translation.StixTranslation()
def _test_query_assertions(translated_query, test_query):
assert translated_query['queries'] ==... |
9927838 | from typing import List, Dict
import torch
import torchmetrics
from datasets import load_dataset, Dataset
import fugashi
def process_example(example: Dict) -> Dict:
tokens = example['tokens']
text = ''.join(tokens)
labels = []
for token in tokens:
new_label_count = len(token)
new_la... |
9927844 | import numpy as np
from qmsolve import Hamiltonian, SingleParticle,TimeSimulation, init_visualization, m_e, e, Å, T , eV, femtoseconds
#==========================================================================================================================================================================
# This examp... |
9927866 | import io
import textwrap
from typing import Any, Dict, Type, TypeVar
from cattr.converters import Converter
from gherkin.errors import ParserError
from gherkin.parser import Parser
from gherkin.token_scanner import TokenScanner
from .ast_node.gherkin_document import GherkinDocument
from .errors import DeserializeErr... |
9927889 | from maggma.api.resource import ReadOnlyResource
from mp_api.routes.substrates.models import SubstratesDoc
from maggma.api.query_operator import (
PaginationQuery,
SortQuery,
SparseFieldsQuery,
NumericQuery,
StringQueryOperator,
)
from mp_api.routes.substrates.query_operators import SubstrateStruct... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.