id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3242074 | import matplotlib.pyplot as plt
import numpy as np
from lib.plot_utils import plot_all_states, plot_agent, plot_value_table, plot_env_agent_and_policy_at_state, \
plot_env_agent_and_chosen_action, plot_policy
from lib.grid_world import a_index_to_symbol
class TDEvaluation:
def __init__(self, env, policy, ini... |
3242151 | import argparse,sys
import glob,os
import re
try:
import simplejson as json
except ImportError:
import json
def get_parser():
parser = argparse.ArgumentParser('Load patients datasets from a JSON file obtained from mongoexport pretty and convert it to datasets_loader format')
parser.add_argument('--inp... |
3242167 | import unittest, spacy, sys
from spacy.gold import biluo_tags_from_offsets
from . import NERDataset
from transformers import BertTokenizer, AlbertTokenizer
CLINICAL_DATA_PRESENT = 'clinical_data' in sys.modules
class TestCreateNERDataset(unittest.TestCase):
@unittest.skipUnless(CLINICAL_DATA_PRESENT, "Clinical ... |
3242200 | import datetime
import serial
from pymongo import MongoClient
NoOfValues = 14 #No of values written by Arduino to Serial
ArduinoPort = '/dev/ttyACM0'
BaudRate = 57600
MongoServer = '127.0.0.1'
MongoPort = 27017
def getArduinoValues():
printValues = False
sensorValues = []
listIndex = 0
ser ... |
3242213 | import bugsnag
import threading
class Terrible(Exception):
pass
def test_uncaught_exception_on_thread_sends_event(bugsnag_server):
"""
Python 3.8+ has an excepthook for spawned threads. This test checks that
exceptions thrown by threads are handled.
"""
def process():
raise Terrible... |
3242240 | from django.db.models import Manager
class PublicManager(Manager):
def get_queryset(self):
return super(PublicManager, self).get_queryset().filter(
share_status=self.model.PUBLIC)
|
3242255 | from consolemenu.items import ExternalItem
class FunctionItem(ExternalItem):
"""
A menu item to call a Python function
"""
def __init__(self, text, function, args=None, kwargs=None, menu=None, should_exit=False):
"""
:ivar str text: The text shown for this menu item
:ivar func... |
3242269 | import sys, os, re, json, codecs
import cPickle as Pickle
from PyCoreNLP.PyCoreNLP import PyCoreNLP
def saveToPKL(filename, data):
with open(filename,'wb')as f:
Pickle.dump(data, f)
return
def loadFromPKL(filename):
with open(filename,'rb') as f:
data = Pickle.load(f)
return data
de... |
3242280 | from .utils import InputExample, InputFeatures, DataProcessor
from .glue import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features
from .squad import squad_convert_examples_to_features, SquadFeatures, SquadExample, SquadV1Processor, SquadV2Processor
from .xnli import xnli_outpu... |
3242297 | import unittest
import mock
from pydiscourse import client
def prepare_response(request):
# we need to mocked response to look a little more real
request.return_value = mock.MagicMock(headers={'content-type': 'application/json; charset=utf-8'})
class ClientBaseTestCase(unittest.TestCase):
def setUp(sel... |
3242312 | import json
import os
# uitls files
def appendToFile(data, filename="output.json"):
feeds = []
with open(filename, mode='r+') as feedsjson:
feeds = json.load(feedsjson)
with open(filename, mode='w') as feedsjson:
if type(data) == type([]):
feeds = data
else:
... |
3242332 | import logging
import re
import socket
import threading
import time
from collections import deque
import six
from requests import ConnectionError
from requests.exceptions import ChunkedEncodingError
from ..errors import Etcd3WatchCanceled
from ..models import EventEventType
from ..utils import check_param
from ..util... |
3242410 | from eclcli.common import command
from eclcli.common import utils
from ..networkclient.common import utils as to_obj
class ListInternetService(command.Lister):
def get_parser(self, prog_name):
parser = super(ListInternetService, self).get_parser(prog_name)
parser.add_argument(
'--name'... |
3242453 | from fe import utils
import numpy as np
def test_sanitize_energies():
full_us = np.array([[15000.0, -5081923.0, 1598, 1.5, -23.0], [-423581.0, np.nan, -238, 13.5, 23.0]])
test_us = utils.sanitize_energies(full_us, lamb_idx=3, cutoff=10000)
expected_us = np.array([[np.inf, np.inf, 1598, 1.5, -23.0], [np... |
3242507 | from private.molecule_graph import MolGraph, InputGraph, MolKey, SubGraph
from private.grammar import ProductionRuleCorpus, generate_rule, ProductionRule
from private.subgraph_set import SubGraphSet
from private.metrics import InternalDiversity
from private.hypergraph import Hypergraph, hg_to_mol
from private.utils imp... |
3242516 | import argparse
import distutils.util
import logging
import sys
import train
def strtobool(val):
return bool(distutils.util.strtobool(val))
if __name__ == "__main__":
# Single GPU (it will also export)
# python train_3d.py
#
# Multi GPU (run export separate)
# python -m torch.distributed.la... |
3242532 | from fastai.basics import *
from .basics import *
from .preprocess import *
from .augment import *
from .data import *
from .layers import *
from .learner import *
from .models.alexnet import *
from .models.resnet import *
from .models.efficientnet import *
from .models.unet import *
from .models.deeplab import *
from ... |
3242568 | from emrichen import Context, Template
FLAVORTOWN_YAML = """
flavours: !Loop
as: a
template: !Merge
- flavour_name: !Void
available: true
- !If
test: !IsString,Lookup a
then:
flavour_name: !Lookup a
else:
!Lookup a
over:
- peasoup
- hard liquor
- flavour_name... |
3242573 | from django.shortcuts import render,HttpResponse
from mp.models import Notices,Config,Navigate,About,Countdown
import json
import time,datetime
from pytz import timezone
import requests
cst_tz = timezone('Asia/Shanghai')
def index(request):
return HttpResponse('mp_index here')
def importantNotice():
if Notic... |
3242657 | from __future__ import print_function
import os
import time
import shutil
import torch
class Checkpoint():
CHECKPOINT_DIR_NAME = 'checkpoints'
TRAINER_STATE_NAME = 'trainer_states.pt'
MODEL_NAME = 'model.pt'
def __init__(self, model, optimizer, epoch, step, train_acc_list, test_acc_list, loss_list, ... |
3242669 | from __future__ import print_function
import numpy as np
import sqaod
from sqaod.common.bipartite_graph_bf_searcher_base import BipartiteGraphBFSearcherBase
from . import cpu_bg_bf_searcher as cext
class BipartiteGraphBFSearcher(BipartiteGraphBFSearcherBase) :
def __init__(self, b0, b1, W, optimize, dtype, prefdi... |
3242672 | from stp.rc import Robot, WorldState, GameInfo, Field, Ball, GamePeriod, GameState, GameRestart
import numpy as np
RobotId = int
def generate_test_robot(robot_id: RobotId,
is_ours: bool = True,
pose: np.ndarray = np.array([0.0, 0.0, 0.0]),
twist... |
3242757 | import komand
import requests
from .. import utils
from .schema import GetRepoInput, GetRepoOutput
class GetRepo(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="get_repo",
description="Retrieve details, including ID, about a specific repo",
... |
3242839 | import math
import os
import pathlib
from glob import iglob
from multiprocessing import Pool
from os.path import exists, join
from typing import List, Optional, Tuple, cast
from urllib.request import urlopen
import cv2
import numpy as np
import PIL
from sklearn.metrics.pairwise import paired_distances
from facenet_sa... |
3242876 | from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import numpy as np
import pandas as pd
from webscrapers.abc_estates import Bolig
# Building API to Boliga.dk
# Requirements:
# Overide get_page and get_pages.
# get_page: Task: Update params and requests GET|POST logic in get_pag... |
3242921 | import ast
import unittest
from obscurepy.handlers.attribute_handler import AttributeHandler, handle_class_properties, handle_class_method_calls
from obscurepy.handlers.classdef_handler import ClassDefHandler
from obscurepy.handlers.functiondef_handler import FunctionDefHandler
from obscurepy.utils.definition_tracker i... |
3242928 | from typing import Any
from boa3.builtin import interop, public, type
@public
def call_flags_all() -> interop.contract.CallFlags:
return interop.contract.CallFlags.ALL
@public
def main(scripthash: type.UInt160, method: str, args: list) -> Any:
return interop.contract.call_contract(scripthash, method, args)... |
3242939 | import time
import asyncio
from unittest.mock import patch
import pytest
from grpclib.const import Status
from grpclib.client import _ChannelState, Channel
from grpclib.testing import ChannelFor
from grpclib.exceptions import GRPCError
from dummy_pb2 import DummyRequest, DummyReply
from dummy_grpc import DummyServic... |
3242965 | import requests
import time
def hardenedRequestsGet(url, timeout=10, maxRetries=5, sleepBetweenRetries=10, jsonResponse=False, verify=True):
result = None
retries = 0
while result is None:
try:
result = requests.get(url, timeout=timeout, verify=verify)
except (requests.exceptions.ConnectionError, requests.ex... |
3242971 | from os.path import split
from graphene import ObjectType, relay, String
from ml_dash import schema
class File(ObjectType):
class Meta:
interfaces = relay.Node,
name = String(description='name of the directory')
# description = String(description='string serialized data')
# experiments = Lis... |
3242974 | from enum import IntEnum
class FileType(IntEnum):
AssetsFile = 0
BundleFile = 1
WebFile = 2
ResourceFile = 9
ZIP = 10
|
3242975 | from django.test import SimpleTestCase
from ..log import clean_exception
class TestLogging(SimpleTestCase):
def test_bad_traceback(self):
result = "JJackson's SSN: 555-55-5555"
exception = None
try:
# copied from couchdbkit/client.py
assert isinstance(result, dict)... |
3243016 | from arekit.contrib.source.ruattitudes.io_utils import RuAttitudesVersions, RuAttitudesIOUtils
from arekit.contrib.source.ruattitudes.labels_scaler import RuAttitudesLabelConverter
from arekit.contrib.source.ruattitudes.reader import RuAttitudesFormatReader
class RuAttitudesCollection(object):
@staticmethod
... |
3243028 | import unittest
from crestdsl.model import *
import re
import z3
from crestdsl.simulation.to_z3 import Z3Converter, get_z3_value, get_z3_variable
from pprint import pprint
import logging
# logging.basicConfig(level=logging.INFO) # basic logging level
# entityLog = logging.getLogger(name="crestdsl.model.entity") # s... |
3243065 | import os
import subprocess
import copy
import argparse
import numpy as np
from bson import ObjectId
import optuna
from pokeai.util import yaml_dump
from pokeai.ai.party_db import col_rate
CONFIG_DIR = ""
train_param_tmpl = {
"tags": ["hyperparam_search"],
"battles": 10000,
"party_tags": ["good_200614_2"]... |
3243106 | import re
from typing import Any, Dict, List
from loguru import logger
from spacy.language import Language
from spacy.tokens import Doc, Span
from edsnlp.matchers.utils import get_text
from edsnlp.pipelines.core.matcher import GenericMatcher
from edsnlp.utils.filter import filter_spans
class AdvancedRegex(GenericMa... |
3243145 | import unittest
from unittest.mock import Mock, patch
from collections import defaultdict
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import balanced_accuracy_score
from trojai.modelgen.default_optimizer import DefaultOptimizer, _running_eval_acc, train_val_dataset... |
3243148 | from modelforge import register_model, Model
from itertools import islice
@register_model
class Code2VecFeatures(Model):
"""
Code2VecFeatures model - path contexts from source code.
"""
NAME = "code2vec_features"
def construct(self, value2index, path2index, value2freq, path2freq, path_contexts):
... |
3243150 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import cv2
import json
import edit_distance as ed
import pdb
import matplotlib.pyplot as plt
import random
from PIL import Image, ImageDraw, ImageFont
import sys
import math
import time
def asMinu... |
3243175 | class RandomAndIsolationForest:
def __init__(self, randomForest, isolationForest=None):
self.randomForest = randomForest
self.isolationForest = isolationForest
self.n_estimators = self.randomForest.n_estimators
self.randomForestEstimatorsIndices = [i for i in range(self.randomForest... |
3243191 | import script
from script import *
class Test(script.Script):
def randomize_timeline(self):
ids = og.get_node_ids()
time = 0
for nid in ids:
time += 500
og.send_command(time, "graph:set_node_attribute",
{
"id" : int(ra... |
3243258 | eTileColor = {
0: (51, 153, 39),
1: (48, 93, 182),
2: (232, 180, 120),
3: (228, 162, 82),
4: (84, 146, 176),
5: (51, 153, 39),
6: (228, 162, 82),
7: (130, 136, 77),
8: (130, 136, 77),
9: (51, 153, 39),
10: (21, 118, 21),
11: (228, 162, 82),
12: (51, 153, 39),
13: ... |
3243274 | import os
import re
import sys
import json
import random
from textworld import Agent
import alfworld.gen.constants as constants
class HandCodedAgentTimeout(NameError):
pass
class HandCodedAgentFailed(NameError):
pass
class BasePolicy(object):
# Object and affordance priors
OBJECTS = constants.OBJEC... |
3243290 | from os.path import isfile, join
import numpy as np
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
import textacy
max_features = 7500
def process(text):
return textacy.preprocess.preprocess_text(
text,
fix_unicode=True,
lowercase=True,
... |
3243306 | import textwrap
from ... import command
from ...needy import ConfiguredNeedy
class SyncCommand(command.Command):
def name(self):
return 'sync'
def add_parser(self, group):
parser = group.add_parser(
self.name(),
description=textwrap.dedent('''\
Attempt... |
3243323 | import pickle
import pdb
import numpy as np
import matplotlib.pyplot as plt
import os
from conf import params
def parse_pickle_save(method_names):
"""
Retrive information from pickle files for the given methods
Args:
method_names: List of strings of names
Returns:
avg_diff: Average ... |
3243336 | import pythreejs, os
from types import MethodType
directory = os.path.dirname(os.path.realpath(__file__)) + '/shaders'
def loadShaderMaterial(name):
uniforms, lights = None, True
vs, fs = None, None
if (name == 'vector_field'):
uniforms = dict(
arrowAlignment=dict(value=-1.0),
... |
3243374 | from typing import cast, Union
from rdflib import Literal, XSD, URIRef, BNode
from rdflib.term import Node
def is_typed_literal(n: Node) -> bool:
return isinstance(n, Literal) and n.datatype is not None
def is_plain_literal(n: Node) -> bool:
return isinstance(n, Literal) and n.datatype is None
def is_str... |
3243460 | from raptiformica.actions.agent import run_agent
from tests.testcase import TestCase
class TestRunAgent(TestCase):
def setUp(self):
self.agent_already_running = self.set_up_patch(
'raptiformica.actions.agent.agent_already_running'
)
self.agent_already_running.return_value = Tru... |
3243461 | from subprocess import Popen, PIPE, STDOUT
def make_order(beverage, qr=None):
url = f'https://api.boxc.in/boxc/qr/scan?qrCodeId={qr}'
cmd = 'curl -i -s ' + url + ' | grep location | cut -d " " -f 2'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
temp_url = p.std... |
3243468 | import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
from treeano.theano_extensions.padding import pad
fX = theano.config.floatX
def test_pad():
x = T.constant(np.array([[1, 2]], dtype=fX))
res = pad(x, [1, 1]).eval()
ans = np.array([[0, 0, 0, 0],
[0, 1,... |
3243503 | import numpy as np
import open3d as o3d
from transformations import *
import os,sys,yaml,copy,pickle,time,cv2,socket,argparse,inspect,trimesh,operator,gzip,re,random,torch
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))
from scipy.spatial... |
3243512 | import ida_funcs
import ida_bytes
import idc
import ida_search
import idaapi
import ida_xref
import ida_segment
import ida_offset
import ida_kernwin
from idaapi import BADADDR
from ida_search import SEARCH_DOWN, SEARCH_UP
import ida_auto
import IDAPatternSearch_utils.ida_common as ida_common
import sys
import os
impo... |
3243588 | import downhill
import numpy as np
import theano
class TestMinimize:
def test_minimize(self):
x = theano.shared(-3 + np.zeros((2, ), 'f'), name='x')
data = downhill.Dataset(np.zeros((1, 1), 'f'), batch_size=1)
data._slices = [[]]
downhill.minimize(
(100 * (x[1:] - x[:-1... |
3243589 | import collections
import struct
import sys
import os
import json
def UnpackDataPack(input_file):
uc = open(input_file,'rb')
data = uc.read()
original_data = data
version, num_entries, encoding = struct.unpack("<IIB", data[:9])
if version != 4:
raise Exception("Wrong file version ... |
3243595 | from uuid import UUID
from fastapi import FastAPI
from starlette.status import HTTP_202_ACCEPTED
from botx import Bot, BotXCredentials, IncomingMessage, Message, Status
from botx.middlewares.ns import NextStepMiddleware, register_next_step_handler
bot = Bot(bot_accounts=[BotXCredentials(host="cts.example.com", secre... |
3243639 | import socket
hostname = socket.gethostname()
if 'vogel' in hostname:
from local_vogel import *
elif 'zog' in hostname:
from local_zog import *
elif 'pi' in hostname:
from local_pi import *
|
3243645 | from jet_django.deps import django_filters
class GEOSGeometryFilter(django_filters.CharFilter):
def filter(self, qs, value):
try:
from django.contrib.gis.geos import GEOSGeometry
value = GEOSGeometry(value)
return super().filter(qs, value)
except (ValueError, T... |
3243674 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.airfare import airfare
def test_airfare():
"""Test module airfare.py by downloading
airfare.csv and testing shape of
extracted data has 45... |
3243679 | from pathlib import Path
import os
import sys
import click
from ploomber.spec import DAGSpec
from ploomber import __version__
from ploomber import cli as cli_module
from ploomber import scaffold as _scaffold
from ploomber_scaffold import scaffold as scaffold_project
@click.group()
@click.version_option(version=__ve... |
3243725 | import unittest
import numpy
from chainer.backends import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
from chainer.utils import type_check
@testing.parameterize(
{'axis': 0, 'start': 2, 'out_shape': (3, 2, 4)},
{'axis': 2, 'start': 0, 'out_shape': (4, 2, 3... |
3243739 | import re
from .. import factories as f
from .. utils import create_user_verify_login
def get_captcha_value(html_body):
captcha_text = re.split(r'What is', html_body)[1]
main_text = re.split(r'\?', captcha_text)
a = main_text[0].strip().split(' ')
if a[1] == '+':
return int(a[0]) + int(a[2])
... |
3243746 | import FWCore.ParameterSet.Config as cms
# initialize magnetic field #########################
# initialize geometry #####################
# KFUpdatoerESProducer
from TrackingTools.KalmanUpdators.KFUpdatorESProducer_cfi import *
# Chi2MeasurementEstimatorESProducer
#include "TrackingTools/KalmanUpdators/data/Chi2Meas... |
3243806 | import json
import copy
from time import time
def node(data):
return Node(data.pop('id'), **data)
def edge(data):
return Edge(data.pop('u'), data.pop('v'), **data)
def node_group(data):
return NodeGroup(data.pop('id'), **data)
def status(data):
return Status(**data)
def stage(data):
return Stag... |
3243845 | from django.conf.urls.defaults import *
urlpatterns = patterns('',
# Pending
(r'^pending/$', 'noan.repository.views.page_pending_index'),
(r'^pending/(?P<distName>[^/]+)-(?P<distRelease>[^/]+)/$', 'noan.repository.views.page_pending'),
# Users
(r'^users/$', 'noan.repository.views.page_users'),
... |
3243851 | import os
import time
import pickle
import argparse
import pandas as pd
from keras.preprocessing.sequence import pad_sequences
parser = argparse.ArgumentParser(description='Malconv-keras classifier')
parser.add_argument('--max_len', type=int, default=200000)
parser.add_argument('--save_path', type=str, default='../sa... |
3243871 | from typing import Dict
from main.geo.base.point import Point
class GeoWebCanvas:
def __init__(self, shared_state: Dict) -> None:
self.dict = shared_state # flat (shareable), json-serializable dict
self.last_update = -1
def set_position(
self,
obj: object,
icon_path: ... |
3243933 | import json
import sys
import threading
import enaml
import zmq
from io_controller import IOController
class SensorApp(object):
#def __init__(self, ip='192.168.43.48', port=2019):
def __init__(self, ip='192.168.1.80', port=2024):
self.ip = ip
self.port = port
self._run = True
... |
3243955 | import torch, torch.nn as nn
from transformers import BertTokenizer, BertModel, BertConfig, BertPreTrainedModel
class BertPlain(nn.Module):
def __init__(self, num_tokens, num_labels, dropout):
super().__init__()
self.bert = BertModel.from_pretrained('bert-base-cased')
self.bert.resize_token_embeddings(num_t... |
3243974 | import re
from tqdm import tqdm
from collections import Counter
class Statistics():
def __init__(self):
pass
@staticmethod
def get_bucket(data, bucket_num=10):
_max, _min = max(data), min(data)
base = pow(10, max(len(str(_max)) - 1, 1))
ceil = ((_max - 1) // base + 1) * ba... |
3243983 | import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import flopy
pth = os.path.join("..", "examples", "data", "mf6-freyberg")
name = "freyberg"
tpth = os.path.join("temp", "t078")
# delete the directory if it exists
if os.path.isdir(tpth):
shutil.rmtree(tpth)
# make the directory
os.makedi... |
3244053 | from carim_discord_bot import setup_instructions
def test_integration_setup():
setup_instructions.print_setup_instructions()
|
3244065 | import collections
import typing
import numpy as np
class TrainConfig(typing.NamedTuple):
T: int
train_size: int
batch_size: int
loss_func: typing.Callable
class TrainData(typing.NamedTuple):
feats: np.ndarray
targs: np.ndarray
DaRnnNet = collections.namedtuple("DaRnnNet", ["encoder", "de... |
3244103 | from libs.config import alias, color, gget
from libs.myapp import execute_sql_command
@alias(True, _type="DATABASE", t="table")
def run(table: str):
"""
db_columns
Output all columns of a table.
eg: db_columns {table}
"""
if (not gget("db_connected", "webshell")):
print... |
3244106 | import os
import argparse
from datetime import datetime
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import pprint
from torch import optim
import torch.nn as nn
# path to a pretrained word embedding file
word_emb_path = '/home/devamanyu/glove.840B.300d.txt'
assert(word_emb... |
3244122 | import unittest
from ritpytrading import cases
class TestCaseMethods(unittest.TestCase):
def setUp(self):
self._sample_case_resp = {
"name": "string",
"period": 0,
"tick": 0,
"ticks_per_period": 0,
"total_periods": 0,
"status": "ACTIV... |
3244168 | def _proto_language_impl(ctx):
go_prefix = None
if hasattr(ctx.attr.go_prefix, "go_prefix"):
go_prefix = ctx.attr.go_prefix.go_prefix
#print("pb_compile_deps %s" % ctx.attr.pb_compile_deps)
#print("pb_compile_deps files %s" % ctx.files.pb_compile_deps)
return struct(
proto_language =... |
3244180 | import os
import sys
sys.path.insert(0, os.path.realpath(os.path.join(__file__, '../../')))
for p in os.environ.get('PYTHONPATH', '').split(';'):
sys.path.append(p)
from asserts import *
from ckstyle.doCssCompress import doCompress
from ckstyle.browsers.BinaryRule import *
def doCssCompress(fileContent, fileName ... |
3244193 | from obp.policy.base import BaseContextFreePolicy
from obp.policy.base import BaseContextualPolicy
from obp.policy.base import BaseContinuousOfflinePolicyLearner
from obp.policy.base import BaseOfflinePolicyLearner
from obp.policy.contextfree import BernoulliTS
from obp.policy.contextfree import EpsilonGreedy
from obp.... |
3244213 | import svgwrite
"""
Make filter for outline of head
"""
def make_shape_filter(dwg):
shape_filt = dwg.filter(
id="FN", start=(0, 0), size=('100%', '100%'),
filterUnits="userSpaceOnUse",
color_interpolation_filters="sRGB")
shape_filt.feGaussianBlur(
stdDeviation="1", resu... |
3244229 | import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim
from torch.utils.data import DataLoader
from model.dataloader.samplers import CategoriesSampler, RandomSampler, ClassSampler
from model.models.castle import Castle
from model.models.acastle import ACastle
from model.models.protonet import... |
3244286 | print '... Importing simuvex/concretization_strategies/max.py ...'
from angr.concretization_strategies.max import *
|
3244297 | from chat.models import Chat, Room
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import User
from asgiref.sync import sync_to_async, async_to_sync
"""MESSAGE DB ENTRY"""
@sync_to_async
def create_new_message(me,friend,message,room_id):
get_room = Room.ob... |
3244319 | from plex.lib import six
import functools
import inspect
import re
import unicodedata
def flatten(text):
if text is None:
return None
# Normalize `text` to ascii
text = normalize(text)
# Remove special characters
text = re.sub('[^A-Za-z0-9\s]+', '', text)
# Merge duplicate spaces
... |
3244339 | import unittest
from base import BaseTestCase
class CreditCardTestCase(unittest.TestCase, BaseTestCase):
"""
Test cases for Credit Card number removal removal.
All these will clash with PASSPORT filth.
"""
def test_american_express(self):
"""
BEFORE: My credit card is 37828224631... |
3244409 | import time
from PIL import Image, ImageChops
# 使用第三方库:Pillow
import math
import operator
from functools import reduce
image1 = Image.open('j_temp/1.png')
image2 = Image.open('j_temp/2.png')
# 把图像对象转换为直方图数据,存在list h1、h2 中
def sdifferent(img1, img2):
h1 = img1.histogram()
h2 = img2.histogram()
# b1=list(... |
3244421 | import unittest
import numpy.testing as test
from sampler.sampler_utils import JointFactor
from factors.Factors import *
class GaussianFactorTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.var1 = Variable("X1", 1)
cls.var2 = Variable("X2", 2)
cls... |
3244432 | import os
import sys
# Ensure parent folder is in PYTHONPATH
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
from sklearn.pipeline import Pipeline
from sklearn.compose impor... |
3244443 | from botoy import Action, Botoy, GroupMsg, FriendMsg
from botoy import decorators as deco
from module import config, database
import json
bot = Botoy(qq=config.botqq,
host=config.host,
port=config.port,
# log=True,
log=False,
use_plugins=True)
action = Actio... |
3244444 | from django.contrib import admin
from .models import Site, Process, Database, DatabaseHost, SiteHost
# Register your models here.
admin.site.register(Site)
admin.site.register(SiteHost)
admin.site.register(Database)
admin.site.register(DatabaseHost)
admin.site.register(Process)
|
3244449 | import numpy as np
def cross_val_split(dirs, counts, k=5, n_iter=15, mix_step=5):
data = [dict(case=case, count=count)
for case, count in zip(dirs, counts)]
# sort raughly
data = sorted(data, reverse=True, key=lambda x: x["count"])
cross = [[v] for v in data[:k]]
for v in data[k:]:
... |
3244490 | from _read_sample_info_file import read_sample_info_file
import re
def check_text_in_filename(text, filename):
return [re.search('failed', line) for line in open(filename)
if re.search('failed', line)] |
3244505 | from typing import Tuple, Type, Union, Any
__all__ = [
"DataType",
"ScalarType",
"Shape",
"Param",
]
DataType = Type[Any]
ScalarType = Union[Type[bool], Type[int], Type[float]]
Shape = Tuple[int, ...]
Param = Tuple
|
3244553 | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
im... |
3244565 | import discord
def embed(title="", description="", image=None, color=discord.Embed.Empty):
embed = discord.Embed(title=title, description=description,color=color)
if image:
embed.set_image(url=image)
return embed
def command_error(operation, description):
return discord.Embed(title="Error: " +... |
3244580 | import numpy as np
import wandb
from matplotlib import pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
def fetch(path, trimmed_name):
plt.style.use('science')
max_accs = []
avg_accs = []
for run in wandb.Api().runs(path=path, order="-created_at"):
if run.config['trimmed_name'... |
3244638 | import json
from typing import Dict, List, Optional
from google.appengine.ext import ndb
from werkzeug.test import Client
from backend.api.trusted_api_auth_helper import TrustedApiAuthHelper
from backend.common.consts.auth_type import AuthType
from backend.common.consts.event_type import EventType
from backend.common... |
3244660 | import os
import numpy as np
import pandas as pd
import time
from multiprocessing import Pool
fleet_sim_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
try:
from src.routing.NetworkBasic import NetworkBasic as Network
except:
#fleet_sim_path = r'C:\Users\ge... |
3244663 | from securityheaders.models.cors import CORSDirective
from securityheaders.models.annotations import *
@anydirective
class AccessControlExposeHeadersDirective(CORSDirective):
@classmethod
def isDirective(cls, directive):
""" Checks whether a given string is a directive
Args:
direct... |
3244719 | from rest_framework import viewsets
from rest_framework_extensions.mixins import DetailSerializerMixin
from .models import Comment
from .serializers import CommentSerializer, CommentDetailSerializer
class CommentViewSet(DetailSerializerMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = CommentSerializer
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.