id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11407662 | import argparse
from collections import Counter, defaultdict
from dpu_utils.mlutils import Vocabulary
import heapq
import json
import logging
import numpy as np
import os
import random
import sys
import torch
from torch import nn
from constants import START, END, NL_EMBEDDING_PATH, CODE_EMBEDDING_PATH, MAX_VOCAB_SIZE,... |
11407737 | from pathlib import Path
from typing import Dict, List, Iterable
import numpy
import pysptk
import pyworld
from .wave import Wave
_min_mc = -18.3
_is_target = lambda a: isinstance(a, numpy.ndarray) # numpy.nan is not target
class AcousticFeature(object):
all_keys = ('f0', 'sp', 'ap', 'coded_ap', 'mc', 'voice... |
11407771 | import re
import sublime
from .view import MdeTextCommand
class MdeBaseUnIndentListItemCommand(MdeTextCommand):
"""
This is an interanal text command class shared by `(un)indent_list_item` commands.
It is responsible to read settings and cycle through all selections to replace text.
"""
def run... |
11407792 | import os, glob, shutil
import pandas as pd
from datetime import datetime
from configparser import ConfigParser, NoOptionError
from simba.rw_dfs import *
from simba.drop_bp_cords import *
from simba.features_scripts.extract_features_16bp import extract_features_wotarget_16
from simba.features_scripts.extract_fea... |
11407816 | from __future__ import annotations
from kubernetes_asyncio import client
class K8sAsync:
def __init__(self, core_client: client.CoreApi, v1_client: client.CoreV1Api):
self.core_client = core_client
self.v1_client = v1_client
|
11407851 | import os
import json
import numpy as np
from random import randrange
from .maze_env import MazeEnv
from definitions import ROOT_DIR
import matplotlib.pyplot as plt
if __name__ == "__main__":
size_maze = 15
steps_per_episode = 5000
measure_exploration = size_maze != 15
episodes = 10
env = Maze... |
11407859 | from hellosign_sdk.tests.functional_tests import BaseTestCase
from hellosign_sdk.resource import Embedded, UnclaimedDraft, SignatureRequest
from hellosign_sdk.utils import HSException, NotFound
import os
#
# The MIT License (MIT)
#
# Copyright (C) 2014 hellosign.com
#
# Permission is hereby granted, free of charge, ... |
11407867 | import os
import shutil
from unittest import TestCase
from micro.core.params import Params
class TestEndpoints(TestCase):
def setUp(self):
self.test_folders = [
["MICRO_LOG_FOLDER_PATH", "/tmp/micro_apirest_logs"],
["MICRO_PID_FOLDER_PATH", "/tmp/micro_apirest_pids"]
]
... |
11407876 | from .ddpg import DDPG
from .dqn import DQN
from .fqf import FQF
from .iqn import IQN
from .misc import SlacObservation
from .ppo import PPO
from .qrdqn import QRDQN
from .sac import SAC
from .sac_ae import SAC_AE
from .sac_discor import SAC_DisCor
from .sac_discrete import SAC_Discrete
from .slac import SLAC
from .td3... |
11407885 | import sys
from struct import pack
if len(sys.argv) < 4:
print('Usage: {} sc_x86 sc_x64 sc_out'.format(sys.argv[0]))
sys.exit()
sc_x86 = open(sys.argv[1], 'rb').read()
sc_x64 = open(sys.argv[2], 'rb').read()
fp = open(sys.argv[3], 'wb')
'''
\x31\xc0 xor eax, eax
\x40 inc eax
\x0f\x84???? jz sc_x64
'''
fp.write(... |
11407890 | import jyotisha
from jyotisha import custom_transliteration
from jyotisha.panchaanga.temporal import time, names
def get_lagna_data_str(daily_panchaanga, scripts, time_format):
jd = daily_panchaanga.julian_day_start
lagna_data_str = jyotisha.custom_transliteration.tr('lagnAni—', scripts[0])
for lagna_ID, lagna_... |
11407934 | import ast
import functools
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import sys
objectives = 3 # amount of objectives to be plotted
weights = 11 # amount of weights
figsize = [12, 6] # figure size, inches
plotsize = [2, 7] # amount of subplots in plot
if len(sys.... |
11407969 | import os
import shutil
import cv2
import numpy as np
from tqdm import tqdm
from utils.masked_face_creator import MaskedFaceCreator
class SoFMaskedFaceDatasetCreator:
def __init__(self, dataset_path, new_dataset_folder_path, mask_type="a"):
self.dataset_path = dataset_path
self.new_dataset_folde... |
11408023 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
class InlineKeyboard(InlineKeyboardMarkup):
_SYMBOL_FIRST_PAGE = '« {}'
_SYMBOL_PREVIOUS_PAGE = '‹ {}'
_SYMBOL_CURRENT_PAGE = '· {} ·'
_SYMBOL_NEXT_PAGE = '{} ›'
_SYMBOL_LAST_PAGE = '{} »'
def __init__(self, row_w... |
11408026 | import unittest
import sys
import os
import types
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
from pandas import DataFrame
pandas_avail = True
except ImportError:
pandas_avail = False
try:
import requests_cache
caching_avail = True
except ImportError:
... |
11408112 | from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType
import pandas as pd
import numpy as np
# ***** DO NOT EDIT LINES BELOW *****
# These lines may be overwritten if input/output changes.
@register(
inputs={"data": DataType.Any, "t": DataType.String},
outputs={"resamp... |
11408136 | import warnings
from django.urls import reverse
def warn_insecure(sender, **kwargs):
from .models import FFAdminUser
if FFAdminUser.objects.count() == 0:
path = reverse("api-v1:users:config-init")
warnings.warn(
f"YOUR INSTALLATION IS INSECURE: PLEASE ACCESS http://<your-server-d... |
11408167 | from __future__ import absolute_import, print_function
import glob
import os
import pickle
import numpy as np
from loguru import logger
from tqdm import tqdm
_VALID_SUBSETS = ['train', 'val', 'test']
class GOT10k(object):
r"""`GOT-10K <http://got-10k.aitestunion.com//>`_ Dataset.
Publication:
``GO... |
11408213 | from pyupload.uploader.base import Uploader
class CatboxUploader(Uploader):
def __init__(self, filename):
self.filename = filename
self.file_host_url = "https://catbox.moe/user/api.php"
def execute(self):
file = open(self.filename, 'rb')
try:
data = {
... |
11408240 | from policyglass import Principal
def test_short_account_id():
assert str(Principal("AWS", "123456789012")) == "AWS arn:aws:iam::123456789012:root"
def test_account_id():
assert Principal(type="AWS", value="arn:aws:iam::123456789012:root").account_id == "123456789012"
def test_is_account():
assert Pri... |
11408248 | import random
import string
from typing import Dict
from fastapi.testclient import TestClient
from app.config import settings
from app.utils.security import frontend_hash
def random_lower_string(k: int = 32) -> str:
return "".join(random.choices(string.ascii_lowercase, k=k))
def random_hash(hash_type: str = "... |
11408288 | from Interprete.NodoAST import NodoArbol
from Interprete.Tabla_de_simbolos import Tabla_de_simbolos
from Interprete.Arbol import Arbol
from Interprete.Valor.Valor import Valor
from StoreManager import jsonMode as dbms
from Interprete.CREATE_TABLE import clases_auxiliares
from Interprete.Meta import HEAD
from Interprete... |
11408308 | from ._impl import odeint
from ._impl import odeint_adjoint
from ._impl import cheb1_interp_torch, compute_barycentric_weights, r8vec_cheby1space
from ._impl import odeint_linear_func, odeint_chebyshev_func
from ._impl import odeint_chebyshev_func, odeint_linear_func |
11408314 | from Tea.model import TeaModel
class RuntimeOptions(TeaModel):
def __init__(self, autoretry=False, ignore_ssl=False, max_attempts=0, backoff_policy="", backoff_period=0,
read_timeout=0, connect_timeout=0, local_addr="", http_proxy="", https_proxy="", no_proxy="",
max_idle_c... |
11408326 | from . import zeep
def to_builtin(obj, *, target_cls=dict):
"""
Turn zeep XML object into python built-in data structures
Args:
target_cls (Type[dict]):
Which type of dictionary type will be used for objects.
As this project's minimum Python version officially supported is... |
11408329 | import utils, torch, time, os
import numpy as np
from torch.autograd import Variable
from Generative_Models.Generative_Model import GenerativeModel
from Data.load_dataset import get_iter_dataset
class BEGAN(GenerativeModel):
def __init__(self, args):
super(BEGAN, self).__init__(args)
self.gamma ... |
11408335 | from elasticsearch_dsl import connections, Search, Q, A
import config
class BitsharesElasticSearchClient():
def __init__(self, default_cluster_config, additional_clusters_config):
self._create_connection('operations', default_cluster_config, additional_clusters_config)
self._create_connection('obje... |
11408342 | import sys,os
import subprocess
import time, glob
L=2000
sim_prefix = '/20140820_seqs'
dt=200
jobcount = 0
# inner loops = 2*2*4*1*3*4 = 2**7 * 3 approx 400
n=20
i=0
D=0.5
istep=0
first_gen = 5000
last_gen = 25000 #min(5000 + istep*(i+1)*dt, 24800)
dir_list= glob.glob('../data_new/N_10000_L_2*_sdt_1*')
for year in xra... |
11408381 | import numpy as np
import pytest
from plio.utils import covariance
def test_compute_covariance():
# This test is using values from an ISIS control network
lat = 86.235596
lon = 140.006195
rad = 1736777.625
sigmalat = 15.0
sigmalon = 15.0
sigmarad = 25.0
semimajor_rad = 1737400.0
c... |
11408382 | import config
from flask import session, redirect, url_for, flash, g, abort
from functools import wraps
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if "team_id" in session and session["team_id"]:
return f(*args, **kwargs)
else:
flash("You need to be ... |
11408386 | import sqlite3
import numpy as np
from sqlite3 import Error
from pandas import DataFrame as df
import re
from mpunet.database import default_tables
class DBConnection(object):
def __init__(self, db_file_path):
self.db_file_path = db_file_path
self._connection = None
self._cursor = None
... |
11408421 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import shutil
from onnx import defs
from onnx import helper
from onnx import TensorProto
import numpy as np
import tensorflow as tf
from onnx_tf.backend... |
11408437 | from lldbsuite.test.lldbtest import *
import os
import time
import json
ADDRESS_REGEX = '0x[0-9a-fA-F]*'
# Decorator that runs a test with both modes of USE_SB_API.
# It assumes that no tests can be executed in parallel.
def testSBAPIAndCommands(func):
def wrapper(*args, **kwargs):
TraceIntelPTTestCaseBas... |
11408458 | from .api import Legalizer
from .base import LegalizerBase
@Legalizer.register
class GraphDefLegalizer(LegalizerBase):
TARGET = 'tensorflow'
class _OpTypeRenamePostProcessing(object):
_RENAME_MAP = {
'BatchMatMulV2': 'MatMul',
# FIXME: need to update matcher before adding this line
# 'Add':... |
11408474 | import re
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you m... |
11408477 | import subprocess
from flask.cli import AppGroup
translations = AppGroup("translations", help="Manages translations")
@translations.command(help="Refreshes the translations potfile")
def genpot():
subprocess.run(
"""pybabel extract \
--msgid-bugs-address="<EMAIL>" \
--copyright-holder="Phuks LLC"... |
11408487 | import numpy as np
from rdkit import Chem
from typing import List
# Symbols for different atoms
ATOM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe',
'As', 'Al', 'I', 'B', 'V', 'K', 'Tl', 'Yb', 'Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se', 'Ti',
'Zn', 'H', 'Li', 'Ge', 'C... |
11408509 | from subprocess import CalledProcessError
from rkd.api.contract import ExecutionContext
from rkd.api.syntax import TaskDeclaration
from rkd_harbor.test import BaseHarborTestClass
from rkd_harbor.tasks.running import UpgradeTask
from rkd_harbor.tasks.running import StopAndRemoveTask
from rkd_harbor.tasks.running import ... |
11408521 | import argparse
import numpy as np
from src.animate_scatter import AnimateScatter
from src.whale_optimization import WhaleOptimization
def parse_cl_args():
parser = argparse.ArgumentParser()
parser.add_argument("-nsols", type=int, default=50, dest='nsols', help='number of solutions per generation, default: 5... |
11408569 | from corehq.extensions import extension_point, ResultFormat
def customize_user_query(user, domain, user_query):
for mutator in user_query_mutators(domain):
user_query = mutator(user, domain, user_query)
return user_query
@extension_point(result_format=ResultFormat.FLATTEN)
def user_query_mutators(do... |
11408571 | from time import time
from math import atan2, degrees, hypot
class BlueDotPosition:
"""
Represents a position of where the blue dot is pressed, released or held.
:param float x:
The x position of the Blue Dot, 0 being centre, -1 being far left
and 1 being far right.
:param ... |
11408584 | import os
import torch
import torch.backends.cudnn as cudnn
import opts
import train
import utils
import models.__init__ as init
import getdata as ld
import random
from tensorboardX import SummaryWriter
parser = opts.optionargparser()
writer = SummaryWriter()
def main():
global opt, best_err1
opt = parser.par... |
11408596 | from p3ui import *
import asyncio
from imageio import imread
import p3ui.skia as skia
import numpy as np
repeat_x = 100
repeat_y = 10
base = imread('image.png')
# minions = np.concatenate((minions, np.ones((minions.shape[0], minions.shape[1], 1)) * 255.), axis=2)
rgba = np.zeros((base.shape[0] * repeat_y, base.shape[... |
11408602 | from model_zoo import flags, datasets, preprocess
from model_zoo.inferer import BaseInferer
flags.define('checkpoint_name', 'model-best.ckpt')
class Inferer(BaseInferer):
def data(self):
(x_train, y_train), (x_test, y_test) = datasets.boston_housing.load_data()
_, x_test = preprocess.standar... |
11408613 | from bs4 import BeautifulSoup
import requests
import time
import lxml
import sys
import os
import re
import csv
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
FOLDER = os.path.join(CURRENT_DIR, 'podium-data')
def main():
# allEpisodes = get_episode_range(1,35)
# create_save_folder()
listfile = os.path.jo... |
11408635 | from lego.apps.events.fields import PublicEventListField
from lego.apps.meetings.fields import MeetingListField
from lego.apps.restricted.models import RestrictedMail
from lego.apps.users.fields import AbakusGroupListField, PublicUserListField
from lego.utils.serializers import BasisModelSerializer
class RestrictedMa... |
11408645 | import frappe
def get_context(context):
context.current_state = frappe.form_dict.state if frappe.form_dict.state != "All" else None
context.current_category = frappe.form_dict.category if frappe.form_dict.category != "All" else None
context.metatags = {
"name": "Updates and Case Studies",
"description": "Liter... |
11408658 | from django.test import SimpleTestCase
from chat.engine.utils import timestamp
from datetime import datetime
class TimestampTest(SimpleTestCase):
def test(self):
self.assertEqual(
timestamp(datetime(2016, 7, 20, 9, 46, 39)),
1469007999
)
|
11408660 | import os
import json
import logging
import sys
from collections import defaultdict
import numpy as np
import tensorflow as tf
from sacred import Experiment
from sacred.observers import MongoObserver
import gnnbench.models
from gnnbench.data.make_dataset import get_dataset_and_split_planetoid, get_dataset, get_train_... |
11408684 | from ..cw_model import CWModel
class CampaignLinkClicked(CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.campaignId = None # (Integer)
self.contactId = None # *(Integer)
self.dateClicked = None # (String)
self.url = None # *(Str... |
11408686 | from django.conf.urls import patterns, url
from affiliates.statistics import views
urlpatterns = patterns('',
url(r'^statistics/$', views.index, name='statistics.index'),
url(r'^statistics/category/(?P<pk>\d+)/$', views.CategoryDetailView.as_view(),
name='statistics.category'),
)
|
11408688 | import tempfile
import time
import webbrowser
from pathlib import Path
from subprocess import PIPE, Popen, check_call
from ..exceptions import NotTestedRule
from ..html_builder.graph import Graph
from .client import Client
START_OF_FILE_NAME = 'graph-of-'
class ClientHtmlOutput(Client):
def __init__(self, args)... |
11408711 | from enum import IntEnum
from django.db import models
from osf.models.base import BaseModel
from osf.utils.fields import NonNaiveDateTimeField
class JobState(IntEnum):
"""Defines the six states of registration bulk upload jobs.
"""
PENDING = 0 # Database preparation is in progress
INITIALIZED = 1 ... |
11408767 | from dateutil import tz
from datetime import datetime
import dateutil.parser as tparser
def time_to_utc(time):
"""
Returns 'UTC' conversion of the given time in "ISO-8601 like" format.
'time' is a string data type.
"""
utc_zone = tz.tzutc()
dt = tparser.parse(time)
in_utc = dt... |
11408800 | import pytest
import sympy
import numpy as np
import scipy.linalg as la
from .. import kwant_rmt
from ..hamiltonian_generator import continuum_hamiltonian, check_symmetry, \
bloch_family, make_basis_pretty, constrain_family, continuum_variables, \
continuum_pairing, remove_duplicates, subtract_family, displa... |
11408801 | import logging
import os
from testing.functional_tests.t_utils import create_tmp_dir, __data_testing_dir__, download_functional_test_files
from testing.common_testing_util import remove_tmp_dir
from ivadomed.scripts import prepare_dataset_vertebral_labeling
logger = logging.getLogger(__name__)
def setup_function():
... |
11408818 | from tf_components.visualization.clip_uint8 import *
from tf_components.visualization.haar_visualization import *
|
11408843 | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from events.classes import Event
event_ocr_document_version_submit = Event(
name='ocr_document_version_submit',
label=_('Document version submitted for OCR')
)
event_ocr_document_version_finish = ... |
11408858 | from hypothesis import given, example
import hypothesis.strategies as st
from tally.tally import *
@given(st.lists(st.booleans()))
@example([])
@example([True])
@example([True,True])
@example([False])
@example([False,False])
def test_at_most_one_alt_hypothesis(lst):
s = Tally()
mgr = VarMgr( s)
a = mgr.add_var(... |
11408872 | from typing import Optional
from sqlalchemy.orm import Session
from autoconf import conf
from autofit.non_linear.abstract_search import NonLinearSearch
from autofit.non_linear.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.abstract_search import PriorPasser
from autofit.non_linea... |
11408873 | import boto3
import json
import logging
log = logging.getLogger()
log.setLevel(logging.DEBUG)
APPLICABLE_RESOURCES = ["AWS::S3::Bucket"]
config = boto3.client('config')
def evaluate_compliance(configuration_item):
if configuration_item["resourceType"] not in APPLICABLE_RESOURCES:
return {
"co... |
11408874 | from ..base import Core
from ..mixins import (
ScrapyMixin,
NoChangeMixin,
)
from .query import parse, regular
class Onereq(
ScrapyMixin,
NoChangeMixin,
Core
):
name = 'onereq'
def spy(self, query, timeout, options={}):
return super(Onereq, self).spy(regular(query), timeout, optio... |
11408891 | import pandas as pd
import numpy as np
from core.evaluation.eval import Evaluator
from context.debug import DebugKeys
# TODO: Move this logger into a root of a networks folder in future.
class CSVLogger:
"""
This class holds necessary columns for csv table.
Columns devoted to results per certain epoch fo... |
11408911 | def dice( num, sides ):
return reduce(lambda x, y, s = sides: x + random.randrange(s), range( num + 1 )) + num
|
11408915 | import time
from model import *
from utils import*
import DMaskRCNN as model
import coco
from extract import parse_annotation, resize_bbox
import skimage.io
# Root directory of the project
root_dir = os.getcwd()
# Directory to save logs and trained model
model_dir = os.path.join(root_dir, "domain_logs")
# Local pat... |
11408931 | from py42.services.alertrules import ExfiltrationService
class TestExfiltrationClient:
def test_get_by_id_posts_expected_data_for_exfiltration_type(self, mock_connection):
alert_rule_client = ExfiltrationService(mock_connection, "tenant-id")
alert_rule_client.get("rule-id")
assert mock_co... |
11408947 | import torch
import pytest
import random
from molbart.tokeniser import MolEncTokeniser
regex = "\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9]"
# Use dummy SMILES strings
smiles_data = [
"CCO.Ccc",
"CCClCCl",
"C(=O)CBr"
]
example_tokens = [
["^... |
11409036 | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
class PointNetFeatures(nn.Module):
def __init__(self, bottleneck_size=1024, input_shape="bcn"):
super().__init__()
if input_shape not in ["bcn", "bnc"]:
raise ValueError(
... |
11409037 | import os
from chromedriver_py import binary_path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class settings:
chromedriver_path: str = binary_path
current_session_path: str = os.path.join(BASE_DIR, "assets", "current_session.txt")
credentials_path: str = os.path.join(BASE_DIR,... |
11409076 | import pytest
from ..data import settings
__all__ = ['testing_envs']
@pytest.fixture(scope='function')
def testing_envs(monkeypatch):
for k, v in settings.ENVS_AND_VALS:
monkeypatch.setenv(k, v)
|
11409082 | from typing import Any
import pytest
from qcodes.utils.validators import Anything, Validator
from .conftest import AClass, a_func
class BrokenValidator(Validator[Any]):
def __init__(self):
pass
def test_broken():
# nor can you call validate without overriding it in a subclass
b = BrokenValida... |
11409087 | from signal import pause
import cv2
from pitop import Camera, Pitop, TiltRollHeadController
from pitop.processing.algorithms.faces import FaceDetector
def track_face(frame):
face = face_detector(frame)
robot_view = face.robot_view
cv2.imshow("Faces", robot_view)
cv2.waitKey(1)
if face.found:
... |
11409088 | import pickle
import random
def test_pickle():
from scitbx.array_family import flex
from dials.model.data import PixelList
size = (100, 100)
sf = 10
image = flex.double(flex.grid(size))
mask = flex.bool(flex.grid(size))
for i in range(len(image)):
image[i] = random.randint(0, 100... |
11409137 | from gtd.utils import cached_property
from strongsup.executor import Executor, Denotation
from strongsup.predicate import Predicate
from strongsup.utils import EOU
from strongsup.value import Value
from strongsup.tables.structure import (
parse_number,
parse_date,
Date,
ensure_same_typ... |
11409145 | from sympy.core.decorators import call_highest_priority
from sympy.core.expr import Expr
from sympy.core.mod import Mod
from sympy.core.numbers import Integer
from sympy.core.symbol import Symbol
from sympy.functions.elementary.integers import floor
class Higher(Integer):
'''
Integer of value 1 and _op_priori... |
11409180 | import numpy as np
import pickle
from progressbar import ProgressBar, Bar, Percentage, FormatLabel, ETA
from sklearn.metrics import precision_recall_fscore_support
NUM_HEROES = 108
NUM_FEATURES = NUM_HEROES*2
# Import the test x matrix and Y vector
preprocessed = np.load('test_5669.npz')
X = preprocessed['X']
Y = pre... |
11409207 | from fastapi import APIRouter, Depends
from meilisearch_python_async import Client
from meilisearch_python_async.models.search import SearchResults
from meilisearch_fastapi._config import MeiliSearchConfig, get_config
from meilisearch_fastapi.models.search_parameters import SearchParameters
router = APIRouter()
@ro... |
11409227 | import os, sys, ast, subprocess, argparse
def evaluate_output(gold_file, out_file):
eval_cmd = ['java', 'Scorer', gold_file, out_file]
#print (eval_cmd)
output = subprocess.Popen(eval_cmd, stdout=subprocess.PIPE).communicate()[0]
output = str(output, 'utf-8')
output = output.splitlines()
p,r,f1... |
11409301 | import numpy as np
import skimage.restoration as skr
import scipy.ndimage as scnd
import matplotlib as mpl
import matplotlib.pyplot as plt
import stemtool as st
import matplotlib.offsetbox as mploff
import matplotlib.gridspec as mpgs
import matplotlib_scalebar.scalebar as mpss
import numba
def phase_diff(angle_image)... |
11409314 | import random
import numpy as np
import torch
import torch.nn as nn
from advex_uar.attacks.attacks import AttackWrapper
from advex_uar.attacks.fog import fog_creator
class FogAttack(AttackWrapper):
def __init__(self, nb_its, eps_max, step_size, resol, rand_init=True, scale_each=False,
wibble_dec... |
11409327 | from learntools.core import *
import learntools.embeddings.solns.ex2_recommend_function as recc_solution_module
import learntools.embeddings.solns.ex2_recommend_nonobscure as recc_no_solution_module
class RecommendFunction(CodingProblem):
_vars = ['recommend', 'model']
_hint = (
'''I recommend breaking the f... |
11409342 | from .measures import lyap_r, lyap_e, sampen, hurst_rs, corr_dim, dfa, \
binary_n, logarithmic_n, logarithmic_r, expected_h, logmid_n, expected_rs, \
lyap_r_len, lyap_e_len, rowwise_chebyshev, rowwise_euclidean
from .datasets import brown72, tent_map, logistic_map, fbm, fgn, qrandom, \
load_qrandom
|
11409343 | from numpy import *
def createcgcells(cgelcon,tlocal,ne):
nce, nve = tlocal.shape;
cells = zeros((ne*nce,nve));
tlocal = tlocal.flatten('F')-1;
for el in range (0,ne):
m = nce*el;
cells[m:(m+nce),:] = reshape(cgelcon[tlocal,el],[nce,nve],'F');
#cells = cells - 1;
return cells... |
11409353 | import os
import pickle
from argparse import ArgumentParser
import pandas as pd
from util import ProcessedFolder
class NaiveEntityMerger:
def __init__(self):
self.entity_dict = {}
self.reverse_dict = {}
self.entity_count = 0
def add_entity(self, name: str, email: str):
if (n... |
11409431 | from typing import List, Dict, Optional
from tabulate import tabulate
import shutil
import os
import logging
def generate_openlane_files(
projects,
interface_definitions: Dict[str, Dict[str, int]],
target_user_project_wrapper_path: Optional[str],
target_user_project_includes_path: Optional[str],
t... |
11409435 | from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from collections import defaultdict
from naturalproofs.tokenize_pairwise import replace_links
import torch
import numpy as np
import json
import transformers
class SequenceRetrievalDataset(Dataset):
def __init__(
self, data, xpad, ... |
11409470 | import json
from collections import Counter
import numpy as np
from sentence_retrieval.sent_tfidf import OnlineTfidfDocRanker
from utils import fever_db, check_sentences, text_clean
import config
import drqa_yixin.tokenizers
from drqa_yixin.tokenizers import CoreNLPTokenizer
from tqdm import tqdm
from utils import c_s... |
11409473 | import FWCore.ParameterSet.Config as cms
pfElectronBenchmarkGeneric = cms.EDAnalyzer("GenericBenchmarkAnalyzer",
OutputFile = cms.untracked.string('benchmark.root'),
InputTruthLabel = cms.InputTag(''),
minEta = cms.double(-1),
maxEta = cms.double(2.5),
recPt = cms.double(2.0),
deltaRMax = cms.... |
11409478 | import math
print(math.sqrt(25))
print(math.pow(5, 3))
print(math.log10(1000))
print(math.log(125, 5))
|
11409488 | from function_scheduling_distributed_framework.beggar_version_implementation.beggar_redis_consumer import start_consuming_message
def f(x):
print(x)
start_consuming_message('no_frame_queue',consume_function=f) |
11409499 | import trend_analysis as ta
import logging
import numpy as np
import pwlf
from sets import Set
import time
import matplotlib.pyplot as plt
import statsmodels.api as sm
from scipy import stats
class line:
def __init__(self, slope, intercept):
self.slope = slope
self.intercept = intercept
class rec... |
11409513 | from unittest.case import TestCase
from .action import (
ACTION_ADD_TODO,
ACTION_SET_VISIBILITY_FILTER,
ACTION_TOGGLE_TODO,
VisibilityFilters,
add_todo,
set_visibility_filter,
toggle_todo,
)
class TestAction(TestCase):
def test_add_todo(self):
text = 'My Action'
act... |
11409550 | import ratcave as rc
import pytest
import numpy as np
def test_from_translation_matrix():
for _ in range(10):
mat = np.random.rand(4, 4)
trans = rc.Translation.from_matrix(mat)
assert np.all(np.isclose(trans.xyz, mat[:3, -1]))
def test_to_translation_matrix():
for _ in range(10):
... |
11409575 | from unittest import TestCase
from phi import math, field
from phi.field import CenteredGrid, Noise, StaggeredGrid
from phi.math import extrapolation, NotConverged, batch
from phi.physics import diffuse
class TestDiffusion(TestCase):
def test_diffuse_centered_batched(self):
grid = CenteredGrid(Noise(bat... |
11409622 | import json
from logging import LogRecord
from ores.logging.logstash_fomatter import LogstashFormatter
def test_format():
formatter = LogstashFormatter(tags=['ores'], host='ores.test.wmnet')
log_record = LogRecord('test_ores', 2, '/dev/test/ores', 55, 'Log made',
[], None)
form... |
11409638 | def doubleInteger(i):
""" double_integer == PEP8 (forced mixedcase by CodeWars) """
return i * 2
|
11409653 | import uuid
import json
def make_name(name, nonce=None):
if nonce is None:
nonce = uuid.uuid4().hex
return '%s-%s' % (name, nonce)
def format_json(tpl, as_string=True, **kwargs):
conf = tpl.format(**kwargs)
conf = json.loads(conf)
if as_string:
conf = json.dumps(conf)
return ... |
11409659 | import matplotlib.pyplot as plt
"""
General figure setup
"""
plt.rc('text', usetex=True)
plt.rc('font', family='serif', size=12)
plt.rc('legend', fontsize=8)
plt.rc('figure', facecolor='white')
|
11409670 | import pandas as pd
from xplore.data import xplore
df = pd.read_csv('tests/fifa_ranking.csv')
xplore(df)
|
11409694 | import time
import os
import re
from . import log
def file_rotated(file_name, orig_stat):
while True:
try:
new_stat = os.stat(file_name)
if orig_stat == None:
return True, new_stat
elif orig_stat.st_ino != new_stat.st_ino:
return True, ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.