id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11448341 | from unittest import mock
import pytest
from hulks.check_invalid_domains import InvalidDomainsHook
@pytest.fixture
def hook():
return InvalidDomainsHook()
def test_invalid_domains_validate(capsys, hook):
hook.lines_iterator = mock.Mock(return_value=[(1, "https://foobar.herokuapp.com")])
result = hook.... |
11448363 | import pretrainedmodels
import pretrainedmodels.utils
import numpy as np
import torch
import torch.nn as nn
def resnet34_fm(pretrained='imagenet', num_input_channels=3):
model = getattr(pretrainedmodels, 'resnet34')(pretrained=pretrained)
layer0 = nn.Sequential(model.conv1, model.bn1, model.relu)
layer1 ... |
11448394 | import numpy as np
from utils import gen_traj
class Reinforce:
def __init__(self, env, alpha, gamma, the_d, pi_gen, log_pi, the_0=None):
self.env = env
self.a = alpha
self.g = gamma
self.the_d = the_d
self.pi_gen = pi_gen
self.log_pi = log_pi
self.the_0 = the_0
self.reset()
def tr... |
11448397 | from jinja2 import Template
from nose.tools import raises
from ketchlip.controllers.base_controller import BaseController
from ketchlip.views.search_view import SearchView
@raises(NotImplementedError)
def test_raises_type_error():
BaseController().show("")
def test_get_view():
controller = BaseController()
... |
11448428 | load_modules = {
'hw_USBtin': {'port':'loop', 'debug':2, 'speed':500}, # IO hardware module
'can_controls':
{'bus':'ECU_TEST',
'commands':[
{'cmd':'a','Unlock':'0x122:2:fff0'},
{'Lock' :'0x122:2:ffff'},
{'Open Trunk':'290:2:ffa0'}
],
'statuses':[
... |
11448442 | import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
import os
import math
options = VarParsing.VarParsing ('analysis')
options.register ('runNumber',
100, # default value
VarParsing.VarParsing.multiplicity.singleton,
VarPa... |
11448448 | import discord_logging
import utils
from classes.key_value import KeyValue
log = discord_logging.get_logger()
class _DatabaseKeystore:
def __init__(self):
self.session = self.session # for pycharm linting
self.log_debug = self.log_debug
def save_keystore(self, key, value):
if self.log_debug:
log.debug(... |
11448525 | import sys
if __name__ == "__main__":
mock_output = sys.argv[1]
print('fluentd {}'.format(mock_output))
|
11448526 | import os
import shutil
import psutil
from stp_core.common.log import getlogger
logger = getlogger()
class TempStorage:
@staticmethod
def getOpenFdsUnder(dirPath):
proc = psutil.Process()
# return {f.fd for f in proc.open_files()
# if os.path.dirname(f.path) == dirPath}
... |
11448538 | from __future__ import print_function
# Pure python implementation of <NAME>'s robust geometric predicates.
# This is a straightforward translation of the predicates in triangle.c into
# python.
## Initialization:
# There is a bit of dynamic work which happens on import to figure out
# a few magic floating point v... |
11448571 | def arg_check(func):
def wrapper(num):
if type(num) != int:
raise TypeError("Argument is not an integer")
elif num <= 0:
raise ValueError("Argument is not positive")
else:
return func(num)
return wrapper
|
11448577 | import cv2
import numpy as np
import Funciones
#Path relativo
path="./Imagenes/"
if __name__ == '__main__':
for x in range(81):
#Imagen a analizar
nombre = "prueba" + str(x) + ".png"
imagen = cv2.imread(path+nombre)
imagen = Funciones.recortarBorde(imagen)
Funciones.gu... |
11448593 | import mock
import pytest
from pygls.types import Diagnostic, Position, Range
from textx.exceptions import TextXSyntaxError
from textx_ls_server.features import diagnostics as diag
from textx_ls_server.protocol import TextXDocument
VALIDATE_FUNC_TARGET = "textx_ls_server.features.diagnostics.validate"
SERVER_CREATE_D... |
11448641 | import sys, os, os.path, time
import argparse
import numpy
import torch
import torch.nn as nn
from torch.optim import *
from torch.optim.lr_scheduler import *
from torch.autograd import Variable
from Net import Net
from util_in import *
from util_out import *
from util_f1 import *
torch.backends.cudnn.benchmark = True... |
11448647 | from ctypes import string_at
import wave
from external.pybass import *
import config
from main import bass_call, bass_call_0
class Input (object):
def __init__ (self, device=-1):
bass_call(BASS_RecordInit, device)
self._device = device
self.config = config.BassConfig()
def free(self):
"""Frees all resourc... |
11448656 | import re
from inspect import signature, Parameter
from oxygen.errors import MismatchArgumentException
from .robot_interface import (RobotInterface, get_keywords_from,
set_special_keyword)
class BaseHandler(object):
DEFAULT_CLI = {tuple(['result_file']): {}}
def __init__(self,... |
11448661 | from .free_var import get_free_vars, primfunc_with_new_body
from .traverse import get_all_nodes
from .size import get_node_size, MemoizedGetSize
from .swap import swap_tir
from .buffer import rebind_buffer_var
from .abstract import TIRVisitor, TIRAbstractTransformer, NoDispatchPatternError
|
11448664 | import numpy as np
from numpy.linalg import inv
from numpy.linalg import norm
from joblib import Parallel, delayed
from multiprocessing import Process, Manager, cpu_count, Pool
class SolveIndividual:
def solve(self, A, b, nu, rho, Z):
t1 = A.dot(A.T)
A = A.reshape(-1, 1)
tX = (A... |
11448670 | import pickle
import matplotlib.pyplot as plt
import pdb
paths = {
#"Vanilla HighLR": "../logs/blender_chair_posXYZ_posVIEW_fine1024_log2T19_lr0.01_decay100/loss_vs_time.pkl", \
"Hashed Fast": "../logs/blender_chair_hashXYZ_sphereVIEW_fine1024_log2T19_lr0.01_decay100/loss_vs_time.pkl", \
"Ha... |
11448672 | from ..framelesswindow import FramelessWindow
from ..test import QAppTestCase
class TestFramelessWindow(QAppTestCase):
def test_framelesswindow(self):
window = FramelessWindow()
window.show()
def cycle():
window.setRadius((window.radius() + 3) % 30)
self.singleSho... |
11448713 | import csv
import io
import os
from datetime import date
from unittest.mock import patch
from unittest.mock import Mock
from django.conf import settings
from django.test import TestCase
from django.test import Client
from rest_framework.test import APIClient
from frontend.tests.common import makeTrial
from frontend.... |
11448729 | import os
import sys
import subprocess
import traceback
import importlib.util as il
spec = il.spec_from_file_location("config", snakemake.params.config)
config = il.module_from_spec(spec)
sys.modules[spec.name] = config
spec.loader.exec_module(config)
sys.path.append(snakemake.config['args']['mcc_path'])
import scripts... |
11448751 | import multiprocessing
from pydantic import BaseSettings, PyObject, validator
class Settings(BaseSettings):
"""
Settings can be configured via environment variables or keyword arguments for the
fennel.App instance (which take priority).
Examples
--------
For environment variables, the prefix... |
11448758 | import numpy as np
from PIL import Image
import cv2
import torch
import torch.nn as nn
import os
import json
from collections import OrderedDict
PI = float(np.pi)
def resize_crop(img, scale, size):
re_size = int(img.shape[0]*scale)
if(re_size>0):
img = cv2.resize(img, (re_size, re_size), cv2.IN... |
11448765 | from django import template
from issues.models import Issue
from tasks.models import Task
register = template.Library()
@register.filter(name='get_title_breadcrumb')
def get_issue_task_title(issue, lang):
if isinstance(issue, Issue):
return u'Issue: {0} {1}'.format(issue.id, issue.task.get_title(lang))
... |
11448773 | import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
seed = 7
np.random.seed(seed)
############################First Split#################################
#read OMIM ids
all_omim = np.loadtxt("omim_all.txt", dtype='int')
#split by OMIMs into 5 lists for testing
np.random.shuf... |
11448812 | import textwrap
from nider.colors.utils import color_to_rgb
from nider.mixins import AlignMixin, MultilineTextMixin
from nider.utils import get_font
class Font:
'''Base class for text's font
Args:
path (str): path to the font used in the object.
size (int): size of the font.
Raises:
... |
11448856 | import logging
import os
import ray
from ray.rllib.utils import merge_dicts, try_import_torch
torch, _ = try_import_torch()
from ray.rllib.agents.ppo import PPOTrainer, PPOTorchPolicy
from grl.utils.common import pretty_dict_str
from grl.rllib_tools.space_saving_logger import get_trainer_logger_creator
from grl.uti... |
11448900 | from django.conf import settings
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import Trait
class TraitAdmin(SimpleHistoryAdmin):
date_hierarchy = "created_date"
list_display = (
"__str__",
"value_type",
"boolean_value",
"int... |
11448952 | class CreateStmt(object):
def __init__(self, parsedStmt):
self.parsedStmt = parsedStmt
self.tableName = ""
self.columnList = []
def populate(self):
self.tableName = self.parsedStmt.getTableName()
self.columnList = self.parsedStmt.getColumnList()
def getColumnCount(s... |
11448960 | from jet_django.admin.model_description import JetAdminModelDescription
class JetAdmin(object):
models = []
message_handlers = {}
def register(self, Model, fields=None, hidden=False):
self.models.append(JetAdminModelDescription(Model, fields, hidden))
def register_related_models(self):
... |
11448983 | import unittest
import functions_pybind11 as py11
import functions_boost_python as boost
class TestFunctions(unittest.TestCase):
def _test_function(self, binding):
if binding is py11:
self.assertTrue(hasattr(binding, 'print_dict'))
binding.print_dict({'foo': 123, 'bar': 'hello'})... |
11449014 | import os, sys
import shutil
import subprocess
import tensorflow as tf
import numpy as np
import tkinter as tk
from skimage.transform import resize as imresize
from glob import glob
from os.path import join as opj
from PIL import ImageTk, Image, ImageDraw, ImageFont
from tkinter.filedialog import askopenfilename
from ... |
11449021 | import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
from collections import namedtuple
from functools import partial
Model = namedtuple('SVMModelResult', ['X', 'y', 'kernelFunction', 'b', 'alphas', 'w'])
def svm_train(X, Y, C, kernelFunction, tol=0.001, max_passes=5):
m, n = X.s... |
11449030 | from numpy.random import RandomState
# import imageio
def test_segmentation():
PRNG = RandomState()
PRNG2 = RandomState()
if args.seed > 0:
PRNG.seed(args.seed)
PRNG2.seed(args.seed)
transform = Compose([
[ColorJitter(prob=0.75), None],
Merge(),
Expand((0.8, 1.5... |
11449081 | from nubia import command, context
@command
def reload() -> None:
"""Reload commands"""
ctx = context.get_context()
ctx.reload_commands()
ctx.console.print("[green bold]:white_heavy_check_mark: Reloaded commands!")
|
11449118 | from conftest import *
from models.appendix import Department
def test_get_departments(client):
"""Teste get /departments/ - Compara quantidade de departments enviados com dados do banco e valida status_code 200"""
access_token = get_access(client)
qtdDepartment = session.query(Department).count()
re... |
11449124 | import pytorch_lightning as pl
from ray import tune
from pytorch_lightning.callbacks import Callback
from train_ns_lstm import get_data, Model
from src.hyperparameters.search import main_tune
from src.args import init_lstmgnn_args, add_tune_params, add_configs
class ihm_TuneReportCallback(Callback):
def on_valida... |
11449192 | import signal
import argparse
import sys
import os
from pathlib import Path
from ImageGoNord import GoNord
from rich.console import Console
from rich.panel import Panel
def main():
signal.signal(signal.SIGINT, signal_handler)
console = Console()
tn_factory = GoNord()
tn_factory.reset_palette()
... |
11449234 | import os
import threading
from typing import Dict, Iterator, List, NamedTuple, Optional, Tuple
from urllib.error import URLError
from urllib.request import urlopen
import boto3
from redun.file import File
# Constants.
DEFAULT_AWS_REGION = "us-west-2"
# Cache for AWS Clients.
_boto_clients: Dict[Tuple[int, str, str... |
11449241 | import os
import subprocess
import numpy as np
import nibabel as nib
def nifty_reg_bspline(nifty_bin, nifty_reg_cmd, ref, flo, res=None, cpp=None, rmask=None, fmask=None, levels=None,aff= None):
"""
call bspline registration in niftyreg
:param nifty_bin: the path of niftyreg bin
:param nifty_reg_cmd:... |
11449253 | from fastai import *
from fastai.tabular import *
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
# plt.style.use('dark_background')
def gini(actual, pred, cmpcol = 0, sortcol = 1):
assert( len(actual) == len(pred) )
all = np.asarray(np.c_[ actual, ... |
11449289 | import argparse
import json
from tda.auth import client_from_token_file
from tda.contrib.orders import construct_repeat_order, code_for_builder
def latest_order_main(sys_args):
parser = argparse.ArgumentParser(
description='Utilities for generating code from historical orders')
required = parser... |
11449320 | from abc import ABC, abstractmethod
from typing import Callable, Sequence, Dict, TypeVar, Generic, Optional
import numpy as np
import sympy as sp
from pararealml import Lhs
from pararealml.core.differential_equation import DifferentialEquation
SymbolMapArg = TypeVar('SymbolMapArg')
SymbolMapValue = TypeVar('SymbolM... |
11449325 | from unittest import TestCase
import six
from cqlengine.operators import EqualsOperator
from cqlengine.statements import StatementException, WhereClause
class TestWhereClause(TestCase):
def test_operator_check(self):
""" tests that creating a where statement with a non BaseWhereOperator object fails """
... |
11449333 | import time
from argparse import ArgumentParser
from process.generate import file_processor
from utils.constants import *
from utils.strings import *
def main(args):
file_processor(vars(args)['transactions'], vars(args)['dataset'])
if __name__ == "__main__":
arg_parser = ArgumentParser(description='Deep Q... |
11449370 | from .yekta import Yekta
from .cluster_rank import ClusterRank
from .seedness_score import SeednessScore
from .sybil_rank import SybilRank
from .group_sybil_rank import GroupSybilRank
from .group_sybil_rank_v01 import GroupSybilRank as V1GroupSybilRank
from .weighted_sybil_rank import WeightedSybilRank
from .landing_pr... |
11449401 | import glob
import os
import os.path
import numpy as np
np.random.seed(1)
from keras.preprocessing import image
from keras.applications.resnet50 import ResNet50
from keras.applications.imagenet_utils import preprocess_input
def extract_features(path_frames, output_path):
no_imgs = [] # No. of images
imag... |
11449433 | import numpy as np
from finmag.util.solid_angle_magpar import return_csa_magpar
from finmag.native import llg as native_llg
# native_llg.compute_solid_angle returns a signed angle, magpar does not.
TOLERANCE = 1e-15
csa = native_llg.compute_solid_angle
csa_magpar = return_csa_magpar()
def test_solid_angle_first_oc... |
11449519 | import sys
import embed
import builtins
builtins.vars = embed.builtins_vars
sys.modules['aio_suspend'] = sys
def aio_suspend():
import aio_suspend
builtins.aio_suspend = aio_suspend
import pythons
|
11449529 | import pytest
def pytest_addoption(parser):
parser.addoption('--domain', action='store', default='mydomain2',
help='Domain to use for integration tests')
parser.addoption('--task-list', action='store', default='tasklist',
help='Task list name for integration tests')
... |
11449551 | from dppy.beta_ensembles import JacobiEnsemble
jacobi = JacobiEnsemble(beta=2) # beta must be in {0,1,2,4}, default beta=2
jacobi.sample_full_model(size_N=400, size_M1=500, size_M2=600) # M_1, M_2 >= N
# jacobi.plot(normalization=True)
jacobi.hist(normalization=True)
# To compare with the sampling speed of the tri... |
11449557 | import os
from inspect import getsourcefile
import numpy as np
import resqpy.model as rq
def write_snapshot(data, title):
# Method to write out a new snapshot of data if one is needed
reshaped_array = data.reshape(data.shape[0], -1)
np.savetxt(f'C:\\Test\\{title}.txt', reshaped_array)
def check_load_sn... |
11449564 | from twister2.tset.fn.factory.GenericFunctions import GenericFunctions
from twister2.tset.fn.factory.PartitionFunctions import PartitionFunctions
class TSetFunctions:
def __init__(self, java_ref, env):
self.__java_ref = java_ref
self.__partition_functions = PartitionFunctions(java_ref.partition()... |
11449578 | from django.db import models
from exclusivebooleanfield.fields import ExclusiveBooleanField
class UnlimitedModel(models.Model):
the_one = ExclusiveBooleanField(default=False)
def save(self, *args, **kwargs):
super(UnlimitedModel, self).save(*args, **kwargs)
self.overridden_save = True
clas... |
11449581 | class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
return max([len(i) for i in ''.join(map(str, nums)).split('0')])
|
11449593 | import pytest
from pyepm import api
from helpers import COW_ADDRESS, config, mock_json_response
def test_api_exception_error_response(mocker):
instance = api.Api(config)
mocker.patch('requests.post', return_value=mock_json_response(error={'code': 31337, 'message': 'Too Elite'}))
with pytest.raises(api.Ap... |
11449594 | import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets
def resblock(x, filter_size):
res = slim.conv2d(x, filter_size, [3, 3], activation_fn=lrelu, padding='SAME')
res = slim.conv2d(res, filter_size, [3, 3], activation_fn=lrelu, padding='SAME')
return x + res
de... |
11449595 | from joblib import Parallel, delayed
from sklearn.utils import gen_even_slices
import pandas as pd
import numpy as np
from ..trajectory_data import TrajectoryData
class TrajectoryLoader(object):
"""Base class for trajectory loaders.
"""
def load(self):
"""Loads trajectories according to the spec... |
11449610 | import numpy as np
import sys
import os.path as op
from operator import add
import logging
from glob import glob
from .all_genes import all_genes as all_genes_default
from .paths import path_to_current_db_files
from functools import reduce
logger = logging.getLogger('tcr_rearrangement.py')
__all__ = ['get_alpha_tri... |
11449614 | class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def sum_and_count_nodes(node, sum_of_values, count):
if node is None:
return sum_of_values, count
sum_of_values, count = sum_and_count_nodes(node.left, sum_of_val... |
11449630 | import urllib
from typing import List, Optional
import requests
from requests import Session
from todoist_api_python.endpoints import (
AUTHORIZE_ENDPOINT,
REVOKE_TOKEN_ENDPOINT,
TOKEN_ENDPOINT,
get_auth_url,
get_sync_url,
)
from todoist_api_python.http_requests import post
from todoist_api_python... |
11449636 | import pytest
from hackathon.constants import VE_PROVIDER, TEMPLATE_STATUS
from hackathon.hmongo.models import User, Template, UserHackathon
from hackathon.hmongo.database import add_super_user
@pytest.fixture(scope="class")
def user1():
# return new user named one
one = User(
name="test_one",
... |
11449647 | from . import context
# Create the outline of a well-formed module, with these characteristics:
# - Has enough resources to complete (temple, shops, encounters, treasure)
# - Directly connected areas have close difficulty ratings
# - Areas with large difficulty jumps may be connected by a roadblock
... |
11449660 | class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
count = collections.Counter()
seen = set()
rtn = []
for root in names:
k = count[root]
name = "{}({})".format(root,k) if k else root
while name in seen:
... |
11449671 | import httpx
import pytest
from fastapi import status
from chapter7.cors.app_without_cors import app as app_without_cors
from chapter7.cors.app_with_cors import app as app_with_cors
@pytest.mark.fastapi(app=app_without_cors)
@pytest.mark.asyncio
class TestChapter7AppWithoutCORS:
async def test_options(self, clie... |
11449692 | from __future__ import absolute_import, unicode_literals
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from django.core.urlresolvers import reverse
from .models import AreaOfInterest, Incident
class ReportIncidentForm(forms.ModelForm):
location_descri... |
11449695 | import argparse
import os
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
from zerver.data_import.rocketchat import do_convert_data
class Command(BaseCommand):
help = """Convert the Rocketchat data into Zulip data format."""
def add_arguments(self, pa... |
11449717 | import abc
class Base:
default_values = {}
@classmethod
def get_default_values(cls):
return cls.default_values.copy()
@classmethod
def get_foo(cls):
return list(cls.get_default_values().keys())
@property
@abc.abstractmethod
def label(self):
""""""
def v... |
11449748 | import logging
import numpy as np
import pandas as pd
def feature_position(hdim1_indices,hdim2_indeces,region,track_data,threshold_i,position_threshold, target):
'''
function to determine feature position
Input:
hdim1_indices: list
hdim2_indeces: list
region... |
11449761 | from .impl import *
from .matrix import Matrix
from .transformer import TaichiSyntaxError
from .ndrange import ndrange, GroupedNDRange
core = taichi_lang_core
cfg = default_cfg()
current_cfg = current_cfg()
x86_64 = core.x86_64
cuda = core.cuda
profiler_print = lambda: core.get_current_program().profiler_print()
profi... |
11449763 | from .celery import app as celery_app # noqa
default_app_config = "boltstream.apps.BoltstreamAppConfig"
|
11449777 | from crash_window import Crash_window
import json
from math import log
from operator import itemgetter
import os
from pydub import AudioSegment
import traceback
import shutil
from zipfile import ZipFile
class Fnf_chart:
"""
Object:
Represents 1 difficulty of a song in Friday Night Funkin.
... |
11449805 | import getpass
from robinhood_crypto_api import RobinhoodCrypto
def read_credentials():
username = input("Username: ")
password = <PASSWORD>()
return username, password
def read_credentials_from_file(file_name):
username, password = [x.strip() for x in open(file_name).readlines()]
return usernam... |
11449811 | import pytest
from scylla.validator import Validator
@pytest.fixture
def validator():
return Validator(host='172.16.58.3', port=1080)
@pytest.fixture
def validator2():
return Validator(host='192.168.127.12', port=80)
def test_latency(validator):
validator.validate_latency()
assert validator.succe... |
11449827 | import os
import socket
import logging
import yaml
import subprocess
import fcntl
import shlex
import names
from time import time, sleep
from redis import StrictRedis
from copy import deepcopy
from concurrent.futures import ThreadPoolExecutor
from multivac.util import unix_time
from multivac.db import JobsDB
log = l... |
11449830 | from typing import Dict
from datetime import datetime
from botocore.paginate import Paginator
class DescribeCacheClusters(Paginator):
def paginate(self, CacheClusterId: str = None, ShowCacheNodeInfo: bool = None, ShowCacheClustersNotInReplicationGroups: bool = None, PaginationConfig: Dict = None) -> Dict:
... |
11449837 | import os
import secrets
import string
from typing import List, Optional, Sequence
from itsdangerous import Serializer
from itsdangerous.url_safe import URLSafeSerializer
from blacksheep.baseapp import get_logger
logger = get_logger()
def generate_secret(length: int = 60) -> str:
alphabet = string.ascii_letter... |
11449880 | from runners.python import Submission
class AlsyiaSubmission(Submission):
def run(self, s):
# :param s: input in string format
# :return: solution flag
lines = [line.split() for line in s.split('\n')]
linesInt = [[int(item) for item in line] for line in lines]
minMaxList = [max(line) - min(line) for line ... |
11449888 | import os
import time
from typing import List, Dict, Any
import numpy as np
import pandas as pd
from ..helpers._utils import multiprocess_map
from .._logger import logger
__all__ = ["NumpyWriter"]
class NumpyWriter:
"""Write dataset into a set of numpy shards.
Args:
shard_size (int, optional):
... |
11449910 | import tweepy, yaml, re
from spotter import Spotter
class TwitterScraper(Spotter):
DEFANG_URL_FINDER = re.compile(r"(?:ftp|h(?:xx|tt)ps?)://\S+")
DEFANG_DOMAIN_FINDER = re.compile(r"\s((?=\S+\[\.\])((?:[a-z0-9-]+)(?:\.|\[\.\]))+[a-z]{2,}\S+)")
def __init__(self):
super(TwitterScraper, self).__i... |
11449943 | import datetime
from collections.abc import Mapping
from functools import partial
from itertools import chain
from typing import Any, Literal, Optional, TypedDict, Union, get_args, get_origin, get_type_hints
import arti.types
from arti.internal.type_hints import (
NoneType,
is_optional_hint,
is_typeddict,
... |
11449969 | from chatbot import CAChatBot
if __name__ == '__main__':
chatbot = CAChatBot(mode='cmd')
chatbot.run()
|
11449982 | import pandas as pd
import sys
sys.path.append('./src/AI_files')
import stopwords_tokenizer as rem_stopwords
import file_path as fp
class list_to_csv:
def __init__(self, feature_list, csv_location):
self.feature_list = feature_list
self.csv_location = csv_location
def list_to_series(self):
... |
11449984 | import json
import pandas as pd
from os import listdir
txt_folder = "data/unlabeled_txt/"
csv_folder = "data/unlabeled_csv/"
for file in listdir(txt_folder):
with open(txt_folder+file) as f:
data = json.load(f)
x = []
y = []
for pt in data:
x.append(pt['x'])
... |
11449989 | from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import UserProfile, UserPreferences
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.creat... |
11450010 | from bonsai.base.regtree import RegTree
from sklearn.datasets import make_friedman1
from sklearn.model_selection import train_test_split
import numpy as np
import unittest
from misc import apply_tree
class PredictTestCase(unittest.TestCase):
def test_predict(self):
n_samples = 1000
max_depth = 4
... |
11450030 | from pylayers.measures.vna.E5072A import *
from pylayers.measures.parker.smparker import *
from pylayers.antprop.channel import *
import pdb
vna = SCPI()
_filecalh5 = 'mimocal'
_filemesh5 = 'measDec'
# 1. perform a new SISO calibration with the VNA
vna.calibh5(Nr = 2,
Nt = 2,
_filemesh5=_filemesh5,
... |
11450089 | import torch
import numpy as np
from sklearn.cluster import KMeans
from typing import Mapping, Any, Optional
# https://github.com/scikit-learn/scikit-learn/blob/0fb307bf3/sklearn/mixture/_gaussian_mixture.py
# https://github.com/scikit-learn/scikit-learn/blob/0fb307bf3/sklearn/mixture/_base.py
def _batch_A_T_dot_B(... |
11450094 | from decimal import Decimal
import pytest
from tartiflette.scalar.builtins.string import ScalarString
@pytest.mark.parametrize(
"value,should_raise_exception,expected",
[
# TODO: maybe we shouldn't accepts None, list, dict, exceptions...
(None, False, "None"),
(True, False, "true"),
... |
11450102 | try:
import tensorflow.keras as keras
except ImportError:
try:
import keras
except ImportError:
keras = None
def BatchNorm2d(model, file=False, weights=True):
"""
Converts a torch.nn.BatchNorm2d layer
Arguments:
-model:
A LayerRepresentation object of the l... |
11450169 | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
m, n = len(matrix), len(matrix[0])
for row in matrix:
for i in range(1, n):
row[i] += row[i-1]
res = 0
for i in range(n):
for j in ra... |
11450190 | from typing import List, Union
from collections import OrderedDict
import torch
from torch import nn, einsum
from einops import rearrange, repeat
from einops.layers.torch import Rearrange, Reduce
from comvex.utils import MBConvXd, MultiheadAttention, PathDropout, ProjectionHead
from comvex.utils.helpers import name_w... |
11450191 | import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="replit-play",
version="0.0.23",
description="The easiest way ... |
11450207 | from tir import Webapp
import unittest
class GFEC060(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAGFE", "22/06/2020", "T1", "D MG 01", "78")
inst.oHelper.Program("GFEC060")
def test_GFEC060_CT001(self):
self.oHelpe... |
11450220 | from __future__ import absolute_import, division, print_function, unicode_literals
# Statsd client. Loosely based on the version by <NAME> <<EMAIL>>
import logging
import random
import socket
import time
from contextlib import contextmanager
log = logging.getLogger(__name__)
class StatsD(object):
def __init__... |
11450270 | import torch
import torch.nn as nn
import torch.nn.functional as F
from tools_for_model import ConvSTFT, ConviSTFT, \
ComplexConv2d, ComplexConvTranspose2d, NavieComplexLSTM, complex_cat, ComplexBatchNorm, \
RealConv2d, RealConvTranspose2d, \
BaseModel, SequenceModel
import config as cfg
from tools_for_loss... |
11450271 | import unittest
from functools import partial
from scipy import stats
import numpy as np
from pyapprox.leja_sequences import \
leja_objective_and_gradient, compute_finite_difference_derivative, \
leja_objective, compute_coefficients_of_leja_interpolant, \
evaluate_tensor_product_function, gradient_of_tenso... |
11450289 | import torch
import torch.nn as nn
import torch.nn.functional as F
import datetime
import time
import logging
import pandas as pd
import numpy as np
import os
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
from tqdm import tqdm
class TimeTracker(object):
def __init__(self, length=100):
... |
11450370 | import os
import json
from helios.core.engine import MatchObject, CustomRequestBuilder, RequestBuilder
from helios.core.utils import has_seen_before, response_to_dict
import sys
import logging
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class ScriptEngine:
scripts_active = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.