id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11488981 | import numpy as np
from random import shuffle
from scipy.sparse import csr_matrix
from deepneuro.utilities.util import add_parameter
from deepneuro.augmentation.augment import Augmentation
class ExtractPatches(Augmentation):
def load(self, kwargs):
# Patch Parameters
add_parameter(self, kwargs... |
11488982 | from __future__ import print_function
import unittest
import numpy as np
from simpegEM1D import (
GlobalEM1DProblemTD, GlobalEM1DSurveyTD,
get_vertical_discretization_time
)
from SimPEG import (
regularization, Inversion, InvProblem,
DataMisfit, Utils, Mesh, Maps, Optimization,
Tests
)
from simpegE... |
11489084 | import torch
import torch.utils.data as data
import os
import urllib.request
import zipfile
import json
from survae.data import TrainValidTestLoader, DATA_PATH
class Text8(TrainValidTestLoader):
def __init__(self, root=DATA_PATH, seq_len=256, download=True):
self.train = Text8Dataset(root, seq_len=seq_len... |
11489086 | from django.conf.urls import url
from django.urls import path
from . import views
from archeutils import views as arche_views
app_name = 'shps'
urlpatterns = [
url(
r'^ids$',
arche_views.get_ids,
name='get_ids'
),
url(
r'^arche$',
arche_views.project_as_arche_graph... |
11489115 | import shutil
from os import path
from pathlib import Path
from states.binfetchers import BinFetcher
class LocalFetcher(BinFetcher):
def __fetch_impl__(self, bin_info, bin_file):
if not path.exists(bin_file):
raise Exception("missing bin: {}".format(bin_file))
class FSCopyFetcher... |
11489120 | from datetime import datetime
class Person:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
self.year_detector()
def year_detector(self):
"""
Метод определения возраста на основе полной даты рождения + datetime
"""
now = da... |
11489154 | from scipy.stats import mannwhitneyu,wilcoxon
import numpy as np
from scipy.io import mmread
import pandas as pd
X = mmread('RFiles/all_data.mtx')
X = X.tocsr()
celllabels = np.load('Notebooks/meta/celllabels.npy')
isCSF = np.load('Notebooks/meta/isCSF.npy')
isMS = np.load('Notebooks/meta/isMS.npy')
logX = np.log10... |
11489162 | from . import gainesville
from . import cheminf
from . import jena
from girder.utility.model_importer import ModelImporter
from molecules.constants import PluginSettings
def upload_molecule(mol):
settings = ModelImporter.model('setting')
uri_base = settings.get(PluginSettings.SEMANTIC_URI_BASE)
if uri_bas... |
11489175 | import numpy as np
import cv2
import random
import colorsys
import collections
import time
# from playsound import playsound
from pprint import pprint
# # 记录目标对应的计数
# OrderedDict([('river_boat', {'down': 0, 'left': 0, 'right': 0, 'up': 0}),
# ('speedboat', {'down': 0, 'left': 1, 'right': 0, '... |
11489231 | from trading_ig.config import config
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# if you need to cache to DB your requests
from datetime import timedelta
import requests_cache
from getting_realtime_data.data_retrieval import Data_Retrieval
from sending_orders.order_management i... |
11489306 | info = {
"UNIT_NUMBERS": {
"cero": 0,
"un": 1,
"una": 1,
"uno": 1,
"dos": 2,
"tres": 3,
"cuatro": 4,
"cinco": 5,
"seis": 6,
"siete": 7,
"ocho": 8,
"nueve": 9
},
"DIRECT_NUMBERS": {
"diez": 10,
"on... |
11489358 | from .core import *
from .about import __version__
from .about import __author__
from .about import __title__
from .about import __summary__
from .about import __email__
|
11489363 | import torch
import numpy as np
import numba
import copy
from ...utils import common_utils
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...ops.iou3d_nms import iou3d_nms_utils
import warnings
try:
from numba.errors import NumbaPerformanceWarning
warnings.filterwarnings("ignore", category=Numba... |
11489367 | import aiohttp
import asyncio
import logging
from typing import (
Dict,
Optional
)
from hummingbot.data_feed.data_feed_base import DataFeedBase
from hummingbot.logger import HummingbotLogger
from hummingbot.core.utils.async_utils import safe_ensure_future
class CoinGeckoDataFeed(DataFeedBase):
cgdf_logger... |
11489373 | expected_output = {
"total_entries_displayed": 3,
"index": {
1: {
"advertisement_ver": 2,
"capabilities": "Router Switch CVTA phone port",
"device_id": "R6(9P57K4EJ8CA)",
"duplex_mode": "full",
"entry_addresses": {"172.16.1.203": {}},
... |
11489378 | import sys, os
sys.path.insert(0,os.getcwd())
# dictionay to check valid words
import enchant
D = enchant.Dict("en_US")
# code for bot ai
import ai
from typing import Any,Dict,List
# implementation class
'''
class ScrabbleBotHandler(object):
def usage(scrabble):
return 'bot for playing scrabble'
def handle_me... |
11489397 | import sys
from autonetkit.workflow.workflow import BaseWorkflow
def main(filename):
"""
@param filename:
"""
workflow = BaseWorkflow()
network_model = workflow.load(filename)
workflow.run(network_model, target_platform="kathara")
if __name__ == '__main__':
filename = sys.argv[1]
m... |
11489451 | import subprocess
import click
def ping_ip(ip_address, count):
"""
Ping IP_ADDRESS and return True/False
"""
reply = subprocess.run(
f"ping -c {count} -n {ip_address}",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
if re... |
11489486 | from tool.runners.python import SubmissionPy
class ThChSubmission(SubmissionPy):
def run(self, input):
seats = {
get_seat_id(*get_row_and_seat(boarding_pass))
for boarding_pass in input.split("\n")
}
all_seats = set(range(2 ** 10 - 1))
for seat_id in all_sea... |
11489488 | import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from core.bounds import WSR_mu_plus
from core.concentration import get_tlambda, get_lhat_from_table, get_lhat_from_table_binarysearch
import numpy as np
from scipy.optimize import brentq
from tqdm import tqdm
import pdb
if __name__ == "__main... |
11489667 | import bacon
shader = bacon.Shader(vertex_source=
"""
precision highp float;
attribute vec3 a_Position;
attribute vec2 a_TexCoord0;
attribute vec4 a_Color;
varying vec2 v_TexCoord0;
varying vec4 v_Color;
uniform mat4 g_Projection;
void main()
{
gl_Position = g_Project... |
11489691 | from zzcore import StdAns
import re, requests
from subprocess import getoutput,call
from config import REMOTE_MC_URL
class Ans(StdAns):
AllowGroup = [959613860, 125733077, 204097403, 1140391080]
def GETMSG(self):
if len(self.parms) < 2:
return '不加参数是坏文明!'
cmd = self.parms[1]
... |
11489701 | import structlog
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
log = structlog.get_logger(__name__)
class Config(AppConfig):
name = 'readthedocs.builds'
label = 'builds'
verbose_name = _("Builds")
def ready(self):
import readthedocs.builds.tasks
|
11489723 | from setuptools import setup, find_packages
version = '{{ cookiecutter.version }}dev'
install_requires = [
'pytest-pypom-navigation',
'colander',
'pytest-variables[yaml]',
'pytest-bdd',
'pytest-splinter',
'pypom_form',
{%- if cookiecutter.testrail == 'y' %}
'pytest-testrail',
{%- endif %}... |
11489812 | import keras.backend as K
import numpy as np
from kfs.layers.convolutional import (Convolution2DEnergy_TemporalBasis,
Convolution2DEnergy_TemporalCorrelation)
def _test_smoke(channel_order=None):
from kfs.layers.convolutional import Convolution2DEnergy_TemporalBasis
from ke... |
11489818 | import numpy as np
import pycountry_convert as pc
def get_continent(country):
try:
country_code = pc.country_name_to_country_alpha2(country, cn_name_format='default')
return pc.country_alpha2_to_continent_code(country_code)
except (KeyError, TypeError):
return country
def fix_country... |
11489842 | from sentimentja import Analyzer
from pprint import pprint
analyzer = Analyzer()
pprint(analyzer.analyze([
"final fantasy 14 超楽しい",
"クソゲーはつまらん",
"エアリスが死んで悲しい",
"冒険の書が消える音こわい",
"廃人ゲーマーのスキルすごい",
"ケフカキモい"
]))
|
11489878 | import rmf_adapter.type as types
import numpy as np
import datetime
# TYPES ======================================================================
def test_types():
# Test CPPDeliveryMsg
msg = types.CPPDeliveryMsg("pickup_place",
"pickup_dispenser",
... |
11489881 | import logging
# from uuid import UUID
from weakref import WeakValueDictionary
from openpathsampling.netcdfplus.base import StorableNamedObject, StorableObject
from openpathsampling.netcdfplus.cache import MaxCache, Cache, NoCache, \
WeakLRUCache
from openpathsampling.netcdfplus.proxy import LoaderProxy
from futu... |
11489885 | from os import environ
MINECRAFT_POCKET_EDITION = 0
MINECRAFT_PI = 1
MINECRAFT_DESKTOP = 2
minecraftType = MINECRAFT_POCKET_EDITION
try:
minecraftType = int(environ['MINECRAFT_TYPE'])
except:
pass
isPE = ( minecraftType != MINECRAFT_DESKTOP )
|
11489886 | import numpy as np
from lifelong_rl.optimizers.random_shooting.rs_optimizer import RSOptimizer
class CEMOptimizer(RSOptimizer):
def __init__(
self,
sol_dim,
num_iters,
population_size,
elites_frac,
cost_function,
upper_bound=1,
... |
11489903 | import enolib
from enolib import TerminalReporter
from tests.util import snapshot
input = '''
> comment
# section
field: value
list:
- item
- item
> comment
- item
## subsection
fieldset:
entry = value
> comment
entry = value
'''.strip()
def test_terminal_reporter_produces_colored_terminal_output():
docume... |
11489957 | import unittest
import numpy as np
from tf2rl.misc.huber_loss import huber_loss
class TestHuberLoss(unittest.TestCase):
def test_huber_loss(self):
"""Test of huber loss
huber_loss() allows two types of inputs:
- `y_target` and `y_pred`
- `diff`
"""
# [1, 1] -> [0.5... |
11489978 | from enum import Enum
from typing import Dict, Type, Tuple
from nonebot.typing import overrides
from nonebot.utils import escape_tag
from nonebot.adapters import Event as BaseEvent
from .message import Message
from .api import Message as GuildMessage
from .api import User, Guild, Member, Channel
from .api import Mes... |
11489982 | import json
import pytest
import requests
from .fixtures import tornado_server, tornado_app, sample_data1_server, sample_data2_server
from .util import (
assert_error, assert_success, assert_created, assert_deleted, Client
)
def test_malformed(sample_data1_server):
client = sample_data1_server
assert_err... |
11489989 | import json
from django import forms
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from u2flib_server import u2f
class SecondFactorForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.request = kwargs.pop('request'... |
11489993 | import sys
class Progress:
def __init__(self, total, message='progress'):
self.message = message
self.total = total
self.current = 0
def next(self, step=1, extra_message=''):
bar_length, status = 20, ""
self.current += step
progress = float(self.current) / floa... |
11490017 | from aiogram.types import InlineKeyboardMarkup
from aiogram.types import InlineKeyboardButton
from aiogram.types import ChatType
from bot.platforms.telegram.utilities.keyboards import cancel_button
from bot.utilities.types import Command
def login_way_chooser(is_old: bool, chat_type: ChatType) -> InlineKeyboardMark... |
11490025 | cn_formats = [
"rdf-xml",
"turtle",
"citeproc-json",
"citeproc-json-ish",
"text",
"ris",
"bibtex",
"crossref-xml",
"datacite-xml",
"bibentry",
"crossref-tdm",
]
cn_format_headers = {
"rdf-xml": "application/rdf+xml",
"turtle": "text/turtle",
"citeproc-json": "tra... |
11490067 | import codecs
from reamber.algorithms.convert.ConvertBase import ConvertBase
from reamber.bms.BMSMap import BMSMap
from reamber.bms.lists.BMSBpmList import BMSBpmList
from reamber.bms.lists.notes.BMSHitList import BMSHitList
from reamber.bms.lists.notes.BMSHoldList import BMSHoldList
from reamber.quaver.QuaMap import ... |
11490108 | from django.contrib import admin
from oldp.apps.topics.models import Topic
@admin.register(Topic)
class TopicAdmin(admin.ModelAdmin):
date_hierarchy = 'updated_date'
list_display = ('title', 'created_date', 'updated_date')
search_fields = ['title']
|
11490243 | import numpy as np
import pyqg
import pytest
from pyqg.diagnostic_tools import calc_ispec
def test_calc_ispec():
# Create a radial sine wave spiraling out from the center of the model's
# spatial field (with a given frequency)
m = pyqg.QGModel()
radius = np.sqrt((m.x-m.x.mean())**2 + (m.y-m.y.mean())**... |
11490279 | import sys
import random
def gen_labels(inputFile, outputFile, l_num):
v_num = 0
with open(inputFile, 'r') as fin:
for line in fin:
u,v = map(int, line.strip().split())
v_num = max(v_num, max(u, v))
v_num += 1
with open(outputFile, 'w') as fout:
for u in xrange(v... |
11490303 | import torch.nn as nn
import torch.optim as optim
import sys
sys.path.append('../vanilla_densenet_small/')
from densenet import DenseNet
def get_model(learning_rate=1e-3):
model = DenseNet(
growth_rate=12, block_config=(8, 12, 10),
num_init_features=48, bn_size=4, drop_rate=0.25,
final_d... |
11490316 | import sqlite3
import pickle
from datetime import datetime
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
class BlackjackSQL(object):
def __init__(self, filename):
self.sql = sqlite3.connect(filename)
self.cursor = self.sql... |
11490336 | import msgDB
import _thread
import requests
import urllib3
import random
import time
import sys
import os
urllib3.disable_warnings()
def rest_program():
print('restart')
#python = sys.executable
#os.execl(python, python, * sys.argv)
#return "a"
def is_int(s):
try:
int(s... |
11490398 | from docx import Document
from docxcompose.composer import Composer
from utils import ComposedDocument
from utils import docx_path
from utils import FixtureDocument
import pytest
def test_contains_predefined_styles_in_masters_language(merged_styles):
style_ids = [s.style_id for s in merged_styles.doc.styles]
... |
11490405 | import math
from pandac.PandaModules import NodePath, Point3
from . import PartyGlobals
inverse_e = 1.0 / math.e
def getCogDistanceUnitsFromCenter(distance):
return int(round(distance * (PartyGlobals.CogActivityArenaLength / 2.0)))
class CameraManager:
nextID = 0
def __init__(self, cameraNP):
se... |
11490428 | import argparse
import os
import json
import transformers
from filelock import FileLock
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoTokenizer,
DataCollatorForSeq2Seq,
HfArgumentParser,
Seq2SeqTrainer,
Seq2SeqTrainingArguments,
set_seed,
)
def load_qid2query(filena... |
11490449 | import http.server
import socketserver
PORT = 89
HOST = "0.0.0.0"
DIRECTORY = '.' # 'livedash' when served from OpenPilot location 'openpilot/selfdrive/livedash'
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs... |
11490545 | from __future__ import print_function
import lldb
import argparse
def parse_args(raw_args):
"""Parse the arguments given to write"""
# Need to provide 'prog' (name of program) here otherwise
# argparse tries to get it from sys.argv[0], which breaks
# when called in lldb.
parser = argparse.Argument... |
11490566 | jinxuejie = [
'国子先生晨入太学',
'招诸生立馆下',
'诲之曰',
'业精于勤荒于嬉',
'行成于思毁于随',
'方今圣贤相逢',
'治具毕张',
'拔去凶邪',
'登崇畯良',
'占小善者率以录',
'名一艺者无不庸',
'爬罗剔抉',
'刮垢磨光',
'盖有幸而获选',
'孰云多而不扬',
'诸生业患不能精',
'无患有司之不明',
'行患不能成',
'无患有司之不公',
'言未既',
'有笑于列者曰',
'先生欺余哉',
'弟子事先生于兹有年矣',
'先生口不绝吟于六艺之文',
'手不停披于百家之编',
'纪事者必提其要',
'纂言者必钩其玄',
... |
11490573 | import FWCore.ParameterSet.Config as cms
from Configuration.Geometry.GeometryDD4hepExtended2021_cff import *
|
11490585 | import unittest
from uuid import uuid4
from arangodb.api import Database
from arangodb.orm.fields import NumberField, ForeignKeyField, BooleanField, CharField
from arangodb.orm.models import CollectionModel
from arangodb.query.advanced import Query
class CollectionModelManagerTestCase(unittest.TestCase):
def setU... |
11490588 | class _InteropInterface:
def __init__(self):
pass
InteropInterface = _InteropInterface()
|
11490603 | import random, heapq
# Assuming `online` is the set of users that is online, find a path to
# send `amount` coins from `frm` to `to` through `coins` where each
# step along the path is between users that have adjacent fragments.
# A transfer done in this way does not contribute to fragmentation.
def find_path(coins, f... |
11490623 | import math
import multiprocessing
import random
from contextlib import contextmanager, ExitStack
from functools import partial
from math import log2, floor
from pathlib import Path
from random import random
import torch
import torch.nn.functional as F
from gsa_pytorch import GSA
import trainer.losses as L
import tor... |
11490635 | from pykdebugparser.kevent import Kevent
from pykdebugparser.trace_handlers.perf import CallstackFlag, KperfTiState, SamplerAction
def test_perf_event(traces_parser):
events = [
Kevent(timestamp=7006023115068,
data=(b'\t\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x... |
11490682 | from lint import Linter
class Puppet(Linter):
language = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^([^:]+:){2}\s*(?P<error>(Syntax error at|Could not match) \'?(?P<near>[^ ]*?)\'?.*) at [^:]*:(?P<line>\d+)$'
def run(self, cmd, code):
return self.tmpfile(cmd, c... |
11490805 | from pgopttune.config.config import Config
class TuneConfig(Config):
def __init__(self, conf_path, section='turning'):
super().__init__(conf_path)
self.config_dict = dict(self.config.items(section))
@property
def study_name(self):
return self.get_parameter_value('study_name')
... |
11490807 | from haystack import indexes
from mozdns.txt.models import TXT
from mozdns.mozdns_index import MozdnsIndex
class TXTIndex(MozdnsIndex, indexes.Indexable):
txt_data = indexes.CharField(model_attr='txt_data')
def get_model(self):
return TXT
|
11490819 | from urllib.parse import quote
from bddrest import status, response, when, Given
import yhttp
def test_rewrite_nodefault():
log = []
foo = yhttp.Application()
bar = yhttp.Application()
app = yhttp.Rewrite()
app.route(r'/foo/?', r'/', foo)
app.route(r'/bar/?', r'/', bar)
@app.when
de... |
11490820 | from __future__ import print_function
from functools import reduce
import re
import numpy as np
from keras.preprocessing.sequence import pad_sequences
def tokenize(sent):
'''Return the tokens of a sentence including punctuation.
>>> tokenize('Bob dropped the apple. Where is the apple?')
['Bob', 'dropped'... |
11490835 | from collections import OrderedDict
from wazimap.data.tables import get_model_from_fields, get_datatable
from wazimap.data.utils import (get_session, add_metadata, ratio, merge_dicts, group_remainder,
get_stat_data, get_objects_by_geo, percent)
from wazimap.geo import geo_data
PROFILE_SECTIONS = (
"demograph... |
11490856 | import dt
import unittest
import numpy as np
# ----------------------------------------------------------------------------
# SYMMETRY
# ----------------------------------------------------------------------------
class TestDT(unittest.TestCase):
def test_identity(self):
"""Assert that equal potentials are alre... |
11490858 | import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("EQUALITY_ROOT", "~/.equality/mainnet"))).resolve()
|
11490880 | import copy
import rdtest
import renderdoc as rd
from typing import Tuple
class GL_Shader_Editing(rdtest.TestCase):
demos_test_name = 'GL_Shader_Editing'
def check_capture(self):
eid = self.find_action("fixedprog").eventId
self.controller.SetFrameEvent(eid, False)
pipe: rd.PipeState ... |
11490909 | import os
import cv2
import numpy as np
import depthai
import json
from lane_detection import Lanes
base = "/home/satinders/Documents/personal projects/deepway/depthai/resources/nn"
class DepthAi:
max_z = 6
min_z = 0
max_x = 1.3
min_x = -0.5
def __init__(self):
# self.lanes = Lanes()
... |
11490916 | from globibot.lib.plugin import Plugin
from globibot.lib.decorators import command
from globibot.lib.helpers import parsing as p
from globibot.lib.helpers import formatting as f
from globibot.lib.helpers.hooks import master_only
from functools import reduce
from .permissions import permission_names, PERMISSION_NAMES
... |
11490939 | import pymysql.cursors
conexion = pymysql.connect(host='192.168.56.2',
user='pepito',
password='<PASSWORD>',
db='test',
cursorclass=pymysql.cursors.DictCursor)
try:
with conexion.cursor() as cursor:
sql = "INSER... |
11490951 | from mher.samplers.sampler import RandomSampler
from mher.samplers.her_sampler import HER_Sampler
from mher.samplers.nstep_sampler import Nstep_Sampler, Nstep_HER_Sampler
from mher.samplers.prioritized_sampler import PrioritizedSampler, PrioritizedHERSampler
|
11490959 | from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.types import PairSymbolType
from cryptoxlib.clients.binance.exceptions import BinanceException
def map_pair(pair: Pair) -> str:
return f"{pair.base}{pair.quote}"
def map_ws_pair(pair: Pair) -> str:
return map_pair(pair).lower()
def extract_s... |
11490978 | from datetime import date
from typing import Any
from seedwork.domain.entities import Entity
from seedwork.domain.value_objects import Currency, UUID
from modules.catalog.domain.rules import ListingPriceMustBeGreaterThanZero
from .value_objects import ListingStatus
class Listing(Entity):
title: str
descriptio... |
11491003 | def get_cell_value(cell):
return type(lambda: 0)(
(lambda x: lambda: x)(0).func_code, {}, None, None, (cell,)
)()
# longer and more verbose version:
import new
def get_cell_value(cell):
def make_closure_that_returns_value(use_this_value):
def closure_that_returns_value():
retu... |
11491023 | import json
from tornado.ioloop import IOLoop
from appscale.admin.constants import CONTROLLER_STATE_NODE
class ControllerState(object):
""" Keeps track of the latest controller state. """
def __init__(self, zk_client):
""" Creates a new ControllerState object.
Args:
zk_client: A KazooClient.
"... |
11491047 | from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Literal
from .typing import ImplicitDict, StringBasedDateTime
import s2sphere
TIME_FORMAT_CODE = 'RFC3339'
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
EARTH_CIRCUMFERENCE_M = 40.075e6
API_0_3_5 = '0.3.5'
API_0_3_17 = '0.3.17'
# In Bo... |
11491059 | from openprocurement.api.utils import get_now, parse_date
from openprocurement.tender.core.tests.base import change_auth
from openprocurement.api.constants import RELEASE_2020_04_19
from openprocurement.tender.core.utils import calculate_tender_date, calculate_complaint_business_date
from openprocurement.tender.core.co... |
11491066 | import math
def harmonic_wavefunction(x, N):
psi=[0, (math.pi)**(-1./4)*math.exp(-x**2/2)]
for n in range(2,N):
psi+=[math.sqrt(2./n)*x*psi[n-1]-math.sqrt((n-1)/n)*psi[n-2], ]
return psi
|
11491069 | import pytest
from django.core.urlresolvers import reverse
from wunderhabit import views
from wunderhabit import default
from .utils import get_user
from .utils import mock_messages
from wunderlist.tests.utils import mock_wunderlist_api
from wh_habitica.tests.utils import mock_habitica_api
@pytest.mark.usefixtures(... |
11491089 | import pytest
import mimetypes
def verify_file(gb_api, httpserver, filename, custom_filename, content_type, expected_content_type):
if not content_type:
# guess content type
content_type = mimetypes.guess_type(filename)[0]
httpserver.serve_content(content=open(filename, 'rb').read(),
... |
11491100 | import tensorflow as tf
import numpy as np
#import os, sys, inspect
from datetime import datetime
import EmotionDetectorUtils
"""
lib_path = os.path.realpath(
os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], "..")))
if lib_path not in sys.path:
sys.path.insert(0, lib_path... |
11491102 | import grpc
import pytest
from google.protobuf import empty_pb2
from couchers import errors
from couchers.models import UserBlock
from couchers.sql import couchers_select as select
from proto import blocking_pb2
from tests.test_fixtures import blocking_session, db, generate_user, make_user_block, session_scope, testco... |
11491105 | from pytest import raises
from Authentication import Client
from CommonServerPython import DemistoException
import demistomock as demisto
BASE_URL = 'https://example.com/v1/'
GET_CREDENTIALS = {
'credential': [
{'username': 'User1', 'password': '<PASSWORD>', 'name': 'DBot Demisto'},
{'username': '... |
11491202 | import os
import re
import flake8
import pytest
from flake8_nb import __version__
from flake8_nb.flake8_integration.cli import Flake8NbApplication
from flake8_nb.flake8_integration.cli import get_notebooks_from_args
from flake8_nb.flake8_integration.cli import hack_option_manager_generate_versions
from flake8_nb.pars... |
11491235 | import dataclasses
from pathlib import Path
import pytest
from common.node.cluster import Cluster
from common.node.node import Node
from common.test_config import TestConfig
THIS_DIR = Path(__file__).parent
def pytest_addoption(parser):
for field in dataclasses.fields(TestConfig):
required = field.defa... |
11491252 | import requests
import os
import json
from lxml import html
import argparse
import datetime
import time
import random
from selenium import webdriver
SUMMARY_RULE = [
'//main[@class="content"]/section/div[@class="qa-arrangement"]/div[@class="qa-arrangement-body"]/div[@class="qa-title"]',
'//main/div[@class="qa-... |
11491259 | import numpy as np
import scipy.stats
import pytest
import matplotlib.pyplot as plt
from gp import PeriodicKernel, GaussianKernel
from .. import BQ
from .. import bq_c
DTYPE = np.dtype('float64')
options = {
'n_candidate': 10,
'x_mean': 0.0,
'x_var': 10.0,
'candidate_thresh': 0.5,
'kernel': Gauss... |
11491288 | import mindspore.numpy as mnp
import mindspore.ops as ops
from mindspore.communication import init, get_rank
init()
data = mnp.ones((1, 2)) * (get_rank() + 1)
print(f'allreduce之前:{data} at rank {get_rank()}')
allreduce_sum = ops.AllReduce(ops.ReduceOp.SUM)
data = allreduce_sum(data)
print(f'allreduce之后:{data} at rank ... |
11491306 | import asyncio
import random
import typing
from typing import Optional, Union
import disnake
from disnake.ext import commands
from monty.bot import Monty
from monty.constants import ERROR_REPLIES, Colours, Icons
from monty.log import get_logger
from monty.utils.converters import WrappedMessageConverter
from monty.uti... |
11491312 | import random
def split_by_percent(data, train_percentage):
train_indices = random.sample(list(range(len(data))), int(train_percentage*len(data)))
train = [row for i,row in enumerate(data) if i in train_indices]
test = [row for i,row in enumerate(data) if i not in train_indices]
return train, test
def test():... |
11491339 | import argparse
import os
import tensorflow as tf
from tensorflow_privacy.privacy.optimizers.dp_optimizer_keras_vectorized import (
VectorizedDPKerasSGDOptimizer,
)
import flwr as fl
import common
# Make TensorFlow logs less verbose
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
# global for tracking privacy
PRIVAC... |
11491361 | from unittest import TestCase, expectedFailure
import re
import shutil
from typing import Any, TYPE_CHECKING
import integration_helpers as helpers
# This list should match test_fixed_sequence in mock_server.c
test_fixed_sequence = [0.0, 1.0, 0.5, -1.0, 280.0, -12.5, 16.3, 425.87, -100000.0, 0.001]
class FileLoadTest... |
11491374 | import torch
import numpy as np
import scipy.sparse as sp
import torch_quiver as qv
import time
from ogb.nodeproppred import Evaluator, PygNodePropPredDataset
from scipy.sparse import csr_matrix
import os
import os.path as osp
from quiver.sage_sampler import GraphSageSampler
def get_csr_from_coo(edge_index):
sr... |
11491383 | import numpy as np
from pyquante2 import *
from pyquante.scf.iterators import AveragingIterator
import matplotlib.pyplot as plt
#
# Compute RHF on N2 molecule for interatomic
# separation R in a range with N points.
#
N = 50
R_vec = np.linspace(0.5, 3.0, N)
E_vec = np.zeros((N,))
for k in range(N):
R = R_vec[k]
... |
11491390 | import unittest
import mock
from blink1.blink1 import Blink1, BlinkConnectionFailed, InvalidColor
class TestSimpleLightControl(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.b1 = Blink1()
@classmethod
def tearDownClass(cls):
cls.b1.off()
cls.b1.close()
del ... |
11491395 | import numpy as np
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
def forward_pass(network, _in, _tar, mode='validation', weights=None):
_input = _in.to(device)
_target = _tar.float().unsqueeze(0).to(device)
output = network.network_forward(_input, weights)
if mode == 'validat... |
11491431 | import gym
import numpy as np
from rl4rs.server.gymHttpClient import Client
class HttpEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self, env_id, config={}):
remote_base = config["remote_base"]
self.client = Client(remote_base)
self.instance_id = self.client.env_cr... |
11491435 | from dataclasses import dataclass
from functional import seq
from typing import List
from anki import Collection
from anki.notes import Note as AnkiNote
from ..utils.constants import UUID_FIELD_NAME
@dataclass
class UuidFetcher:
collection: Collection
def get_deck_config(self, uuid: str):
return ge... |
11491443 | import timeit
from functools import wraps
from optimus.helpers.logger import logger
def time_it(method):
def timed(*args, **kw):
start_time = timeit.default_timer()
f = method(*args, **kw)
_time = round(timeit.default_timer() - start_time, 2)
logger.print("{name}() executed in {ti... |
11491500 | from src.rfunctions import *
from src.custlogger import *
from collections import defaultdict
try:
import dns.rdatatype
import dns.message
import dns.query
import dns.reversename
except ImportError:
notfound.append('dnspython')
logger = logging.getLogger(__name__)
def dns_query(server, timeout, protocol, q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.