id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11440857 | import platform
import struct
import sys
import os
from os.path import dirname
version_info = (1, 2, 0)
version = '.'.join(str(c) for c in version_info)
def print_version():
arch = struct.calcsize("P") * 8
print("Page Walker: %s" % version)
print("Python: %s (%s-bit)" % (platform.python_version(), arch)... |
11440870 | from django.contrib import admin
from django.contrib.gis.admin import OSMGeoAdmin
from rgd.admin.mixins import MODIFIABLE_FILTERS, TASK_EVENT_FILTERS, TASK_EVENT_READONLY, reprocess
from rgd_imagery.models import KWCOCOArchive
@admin.register(KWCOCOArchive)
class KWCOCOArchiveAdmin(OSMGeoAdmin):
list_display = (
... |
11440878 | from abc import ABC, abstractmethod
from typing import Dict, List
import numpy as np
import random
import re
import jsonpickle
import my_log
import utils
from context_builder import ContextBuilder, BatchedContextFeatures
from context_builder import ContextFeatures
from ngram_builder import NGramBuilder, BatchedNGram... |
11440887 | import logging
from faults import *
# Seed for the random number generator. This makes tests repeatable.
seed = 1
# Time between faults in seconds
delay = 1
# Probability of a fault occuring.
p_fault = 0.5
# if debug is true, log which fault we would do, but don't inject the fault.
debug = False
# only inject faul... |
11440888 | def trigrams(phrase):
phrase = phrase.replace(' ', '_')
return ' '.join(phrase[a:a + 3] for a in xrange(len(phrase) - 2))
|
11440921 | import requests
import re
from utils import *
import json
import time
class Login(object):
session = requests.session()
session.headers['User-Agent'] = UA
access_token = None
def __init__(self, configfile='user.ini'):
self._init()
self.configfile = configfile
self.user = read_... |
11440955 | from .node_hook import MlflowNodeHook, mlflow_node_hook
from .pipeline_hook import MlflowPipelineHook, mlflow_pipeline_hook
|
11440983 | from datetime import datetime
from hata import Client, DATETIME_FORMAT_CODE, ActivityRich
TOKEN = ''
Sakuya = Client(TOKEN)
@Sakuya.events
async def ready(client):
print(f'{client:f} is connected!')
@Sakuya.events
async def message_create(client, message):
if message.content == '!ping':
await clie... |
11440999 | from tool.runners.python import SubmissionPy
class ThoreSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
numbers = set([int(n) for n in s.split()])
target = 2020
for n1 in numbers:
for ... |
11441003 | import argparse
import benchmark
import conf
import mlflow
def _parse_args():
parser = argparse.ArgumentParser(prog="DPSDGym",
description="Differentially private synthetic data generators benchmarking suite",
epilog="Sample command: python... |
11441021 | from datetime import datetime, timezone
from monthdelta import monthdelta
def get_first_day_of_month_x_months_ago(x = 12):
return (datetime.now(tz=timezone.utc) - monthdelta(x)) \
.replace(day=1, hour=0, minute=0, second=0)
|
11441022 | import random
import numpy as np
file_path="/home/lili/data/train.txt"
percentage = 0.1
with open(file_path, "r") as file:
line_count=0
for line in file:
line=line.strip()
line_count+=1
if line_count % 1000000 == 0:
print("progress {}".format(line_count))
print("total {}"... |
11441093 | import importlib
import pkgutil
import os
def import_modules(file_dir, package):
pkg_dir = os.path.dirname(file_dir)
for (_, name, _) in pkgutil.iter_modules([pkg_dir]):
importlib.import_module("." + name, package)
def all_subclasses(cls_, package: str):
subclasses = list(
set(cls_.__sub... |
11441126 | from .train import Train # noqa
from .inference import Inference # noqa
from .eval import Eval # noqa
from .flops import Flops # noqa
|
11441144 | from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from ralph.data_center.models.physical import Rack, RackAccessory, ServerRoom
from ralph.dc_view.serializers.models_serializer import (
DataCenterAssetSerializer,
PDUSerializer,
RackAccesso... |
11441216 | import factory
from spellbot.models import Guild
class GuildFactory(factory.alchemy.SQLAlchemyModelFactory):
xid = factory.Sequence(lambda n: 1000 + n)
name = factory.Faker("company")
motd = factory.Faker("sentence")
class Meta:
model = Guild
sqlalchemy_session_persistence = "flush"
|
11441270 | import torch
import numpy as np
from maf import MAF
from made import MADE
from datasets.data_loaders import get_data, get_data_loaders
from utils.train import train_one_epoch_maf, train_one_epoch_made
from utils.validation import val_maf, val_made
from utils.test import test_maf, test_made
from utils.plot import sample... |
11441288 | from collections import namedtuple
import contextlib
from .parser_ import Parser, Transformer_WithPre, v_args
from .struct_type import StructuredType
from .native_type import as_var, NativeType, MetaType
from .ir_type import IRType, StringType
from .function_type import FunctionDispatchType, FunctionType, Invokable, \... |
11441317 | import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demoMouseClicks import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
def mousePressEvent(self, event):
if event.buttons() & QtCor... |
11441334 | import sys
import re
POSSIBLE_CHARS_NUMBER_FOLLOWS_WITH = [' ', '\n', ')', ',']
# this is basically the whole LLVM layer
I = 0
STACK = []
class LLVMCode:
def __init__(self, io, code = ''): # the only constructor for now is by double* instruction
self.io = io
self.code = code
def __getitem__(s... |
11441335 | import re
import sys
import numpy as np
def get_alignment_ids(data_dir, chromosomes):
alignments = set()
for chromosome in chromosomes:
file_name = data_dir + "/" + "peaks1_alignments_chr" + chromosome + ".txt"
with open(file_name) as f:
for line in f:
alignments.add... |
11441357 | def binarySearch(A,num,l,r):
mid = l + (r-l)//2
if r >= l:
if A[mid] == num:
return("Found")
elif A[mid] > num:
return binarySearch(A,num,l,mid-1)
elif A[mid] < num:
return binarySearch(A,num,mid+1,r)
else:
return("Not Found")
#this non... |
11441372 | import pytest
import sys
from os.path import abspath, dirname, join, pardir
import subprocess
cmd_client_path = abspath(join(dirname(__file__), "cmd_etcd_client.py"))
etcdctl_path = abspath(
join(dirname(__file__), pardir, "etcd-v3.3.10-linux-amd64/etcdctl")
)
def cleanup(key):
subprocess.run([etcdctl_path, ... |
11441384 | import os
from ggplib.player import get
from ggplib.player.gamemaster import GameMaster
from ggplib.db import lookup
from ggpzero.util import attrutil
from ggpzero.defs import confs, templates
from ggpzero.nn.manager import get_manager
from ggpzero.player.puctplayer import PUCTPlayer
from ggpzero.battle.bt import pr... |
11441423 | import tclab # pip install tclab
import numpy as np
import time
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# define energy balance model
def heat(x,t,Q1,Q2):
# Parameters
Ta = 23 + 273.15 # K
U = 10.0 # W/m^2-K
m = 4.0/1000.0 # kg
Cp = 0.5 * 1000... |
11441430 | import numpy as np
import torch
def get_view_dir_map(img_size, proj_inv, R_inv):
'''
Get view direction map in camera space
img_size: [2, ]
proj_inv: [N, 3, 3]
R_inv: [N, 3, 3]
return0: [N, img_size[0], img_size[1], 3]
return1: [N, img_size[0], img_size[1], 3]
'''
batch_size = proj... |
11441445 | from src.model.serverInfoManagement import getOnlineMinute, addMinuteOnlineMinute
from pymysql import Connection
from src.model.makeDatabaseConnection import makeDatabaseConnection
def test():
db = makeDatabaseConnection()
onlineMinute = getOnlineMinute(db)
assert isinstance(onlineMinute, int)
assert a... |
11441501 | from archon.deribit.ws.Wrapper import DeribitWrapper
import archon.config as config
from archon.ws.broker import WSBroker
wsbroker = WSBroker()
apikeys = config.parse_toml("apikeys.toml")
k = apikeys["DERIBIT"]["public_key"]
s = apikeys["DERIBIT"]["secret"]
w = DeribitWrapper(key=k,secret=s)
"""
instr = w.getinstr... |
11441505 | description = 'NEUTRA shutters (HE, FS, Exp)'
display_order = 10
group = 'lowlevel'
epics_timeout = 3.0
devices = dict(
# Main Shutter HE
he_sopen = device('nicos.devices.epics.EpicsDigitalMoveable',
epicstimeout = epics_timeout,
description = 'HE Shutter opening bit',
readpv = 'SQ:N... |
11441534 | from aws_cdk import (
core as cdk,
aws_codebuild as codebuild,
aws_codecommit as codecommit,
aws_codepipeline as codepipeline,
aws_codepipeline_actions as codepipeline_actions,
aws_lambda as lambda_,
aws_s3 as s3,
aws_iam as iam,
aws_kms as kms,
aws_logs as logs,
)
class Cloudf... |
11441598 | from typing import Dict, Iterable, Optional
from crowdin_api.api_resources.abstract.resources import BaseResource
from crowdin_api.api_resources.webhooks.enums import (
WebhookContentType,
WebhookEvents,
WebhookRequestType,
)
from crowdin_api.api_resources.webhooks.types import WebhookPatchRequest
class ... |
11441606 | import pandas as pd
import pdb
from pprint import pprint
import columns_contain
cc = columns_contain.columns_contain
def summarize(df):
'''return dataframe summarizing df
result.index = df.columns
result.column = attributes of the columns in df
'''
description = df.describe()
# print descript... |
11441660 | from multimerchant.wallet import Wallet
import time
from block_io import BlockIo
import six
import os
import sys
try:
os.environ["HD_PRIVKEY"]
except KeyError:
print "Please generate an HD wallet first. See README.rst on https://github.com/blockio/multimerchant-python"
print "Or do this:"
print "\t $ p... |
11441667 | fruits = ("apple", "banana", "cherry")
# fungsi iter() disini digunakan untuk membuat iterator
fruits_iter = iter(fruits)
# mengecek tipe data fruits_iter
print("Tipe data dari fruits_iter:", fruits_iter)
# Untuk mengakses isi dari iterator kita menggunakan fungsi next
print(next(fruits_iter))
print(next(fruits_iter... |
11441676 | import gym
import gym.spaces as spaces
import numpy as np
from collections import deque
class GrayscaleImage(gym.ObservationWrapper):
def __init__(self, env):
super().__init__(env)
old_observation_space = env.observation_space
self.observation_space = spaces.Box(
low=np.expand... |
11441760 | from media_tree.admin import FileNodeAdmin
from media_tree.extension.base_extenders import MediaDefiningExtender
class AdminExtender(MediaDefiningExtender):
"""In order to extend the ModelAdmin, you need to subclass this class and
define the appropriate attributes:
"""
Media = None
"""A Media cla... |
11441763 | from collections import OrderedDict
import attr
from rest_framework import serializers
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator
class ModelSubSerializer(serializers.ModelSerializer):
"""
ModelSubSerializer al... |
11441783 | import pytest
from spikeinterface import download_dataset
from spikeinterface.extractors import read_mearec
from spikeinterface.sorters import run_sorter
def test_run_sorter_local():
local_path = download_dataset(remote_path='mearec/mearec_test_10s.h5')
recording, sorting_true = read_mearec(local_path)
... |
11441835 | from tasks.R2R.utils import load_datasets, load_nav_graphs
from tasks.R2R.env import LowLevelR2RBatch
from tasks.R2R.utils import check_config_judge
from collections import defaultdict
import json
import os
import networkx as nx
import numpy as np
import pprint
pp = pprint.PrettyPrinter(indent=4)
class Evaluation(ob... |
11441855 | import torch.nn as nn
from torchvision.models import squeezenet
from base import BaseModel
class SqueezeNet(BaseModel):
def __init__(self, num_classes=196, use_pretrained=False):
super(BaseModel, self).__init__()
self.model = squeezenet.squeezenet1_0(pretrained=use_pretrained)
self.model.... |
11441885 | from bsbolt.CallMethylation.CallValues import CallMethylationValues
from bsbolt.CallMethylation.CallVector import CallMethylationVector
from bsbolt.CallMethylation.ProcessMethylationContigs import ProcessContigs
|
11441888 | from jenkins_job_wrecker.cli import parse_args, get_xml_root
import os
import xml.etree.ElementTree
import pytest
fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
ice_setup_xml_file = os.path.join(fixtures_path, 'ice-setup.xml')
class TestArgParser(object):
# "-f" tests
def test_missing... |
11441908 | import sys
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
if sys.version_info.minor < 8:
from typing_extensions import Protocol, runtime_checkable
else:
from typing import Protocol, runtime_checkable # type: ignore
from pydicom.dataset impor... |
11441957 | from slim.utils.autoload import import_path
from app import app
import config
import permissions.roles_apply
if __name__ == '__main__':
import model._models
import_path('./api')
app.run(host=config.HOST, port=config.PORT)
|
11441970 | import logging
import os
import json
from jinja2 import Template
from lib import (
create_response,
get_reports,
render_template
)
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
DOMAIN = os.environ.get("DOMAIN")
def lambda_handler(event, context):
logger.info(f"Got... |
11441973 | import numpy as np
import multiprocessing
from multiprocessing import Pool, Process, Array
from contextlib import closing
import glob
import time
from functools import partial
import pandas as pd
import argparse
import os
parser = argparse.ArgumentParser()
#parser.add_argument('-fn','--fn',required=True)
parser.add_ar... |
11441978 | from urllib.parse import urlencode
from ..helpers import Config, Match
from .parser import StringParser, PathParser, IntegerParser, FloatParser
from .pattern import Pattern
class Router(Config):
"""Router is a component responsible for the routing.
Router's only two fings to do are to check if request/constr... |
11441996 | import numpy as np
import scipy.linalg as LA
from lq.policies import LinK
class Linear_Quadratic:
def __init__(self, A, B, Q, R, x0, ep):
# self.random_seed = 1
# np.random.seed(self.random_seed)
self.A = A.astype('float32')
self.B = B.astype('float32')
self.Q = Q.astype('f... |
11442004 | from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import List, Optional, Union
from reiz.ir.backends import base
from reiz.ir.builder import IRBuilder
from reiz.ir.optimizer import IROptimizer
from reiz.ir.printer import IRPrinter
from reiz.schema import ESDLSchema
from ... |
11442070 | from django.contrib import admin
from common.actions import make_export_action
from officer import models
class StoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
list_display = ('id', 'title', 'officer', 'created_date', 'custom_order')
list_display_links = ('id', 'title')
searc... |
11442072 | from torchray.attribution.linear_approx import linear_approx
from torchray.benchmark import get_example_data, plot_example
# Obtain example data.
model, x, category_id, _ = get_example_data()
# Linear approximation backprop.
saliency = linear_approx(model, x, category_id, saliency_layer='features.29')
# Plots.
plot_... |
11442079 | from pandas import DataFrame, Series
from spacy_conll.formatter import CONLL_FIELD_NAMES
def test_doc_conll_pd(base_doc):
assert base_doc.has_extension("conll_pd")
assert base_doc._.conll_pd is not None
assert isinstance(base_doc._.conll_pd, DataFrame)
assert CONLL_FIELD_NAMES == list(base_doc._.conl... |
11442096 | from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import os
#9913 lines
##AUTHID,"STATUS","sEXT","sNEU","sAGR","sCON","sOPN","cEXT","cNEU","cAGR","cCON","cOPN","DATE","NETWORKSIZE","BETWEENNESS","NBETWEENNESS","DENSITY","BROKERAGE","NBROKERAGE","TRANSITIVITY"
#parse dataset
data_perUser =... |
11442115 | import onnx
from onnx import helper
from onnx import TensorProto, OperatorSetIdProto
# inputs/outputs
X = helper.make_tensor_value_info('X', TensorProto.FLOAT, [2, 1])
O1 = helper.make_tensor_value_info('O1', TensorProto.FLOAT, [2, 1])
O2 = helper.make_tensor_value_info('O2', TensorProto.FLOAT, [2, 1])
O3 = helper.mak... |
11442125 | import tensorflow as tf
from utils import Patching
from utils import tfrecord
from tensorflow.keras import backend as K
# [320, 260, 316] is the shape for NAKO dataset
# [236, 320, 260] is the shape for NAKO_IQA dataset
def tfdata_generator(file_lists, label_lists, is_training, num_parallel_calls=4, patch_size=[64,... |
11442139 | import pytest
import moldesign as mdt
from . import helpers
from .molecule_fixtures import *
@pytest.mark.parametrize('fixturename', molecule_standards['hasmodel'])
def test_model_assigned(fixturename, request):
mol = request.getfixturevalue(fixturename)
assert mol.ff is not None
@pytest.mark.parametrize('... |
11442156 | from flask import jsonify, url_for, current_app
from .. import main
@main.route('/')
def index():
"""Entry point for the API, show the resources that are available."""
return jsonify(links={
"user.fetch_user_by_id": {
"url": url_for(
'.fetch_user_by_id',
use... |
11442159 | import cv2
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--image_folder',
type=str,
help='',
)
parser.add_argument(
'--video_name',
type=str,
help='',
)
parser.add_argument(
'--rate',
type=int,
default=16,
help='',
)
args = parser.parse_args(... |
11442169 | import time
from pybrain.datasets.supervised import SupervisedDataSet
from pybrain.structure.modules.sigmoidlayer import SigmoidLayer
from pybrain.supervised.trainers.backprop import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
import numpy as np
from tentacle.board import Board
from tentacle.game... |
11442177 | import pytest
from django.contrib.auth.backends import ModelBackend
from django.test import override_settings
from django.urls import reverse
from rest_framework import status
from .factories import get_user
from .utils import (
check_auth_token, check_code_token, get_api_client,
get_verification_code_from_mai... |
11442201 | from dps.hyper import run_experiment
from dps.utils import copy_update
from silot.run import basic_config, alg_configs, env_configs
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--conv', action='store_true')
parser.add_argument('--max-digits', type=int, choices=[6, 12], req... |
11442221 | from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest
from yowsup.layers.protocol_profiles.protocolentities import SetPrivacyIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
entity = SetPrivacyIqProtocolEntity("all", ["profile","last","status"])
class SetPrivacyIqProtocolEnti... |
11442250 | import matplotlib
matplotlib.use('Agg') # this needs to be here exceptionslly
import matplotlib.pyplot as plt
plt.style.use('bmh')
def paramagg(data):
'''
USE: paramagg(df)
Provides an overview in one plot for a parameter scan. Useful
to understand rough distribution of accuracacy and loss for bot... |
11442283 | import os
import sys
THIS_FILE_DIR = os.path.abspath(os.path.split(__file__)[0])
PATH_TO_MODULE_TO_TEST = os.path.abspath( os.path.join(THIS_FILE_DIR, "..") )
sys.path = [PATH_TO_MODULE_TO_TEST] + sys.path
|
11442306 | from .bread_spec import STEPS_PER_TABLE
from .vendor.six.moves import range
class TableFX(object):
def __init__(self, params, table_index, fx_index):
self._params = params
self._table_index = table_index
self._fx_index = fx_index
@property
def command(self):
"""the effect'... |
11442358 | from datetime import datetime
from unittest.mock import Mock, patch
import pytest
from hammurabi import Pillar
from tests.helpers import get_passing_rule
@patch("hammurabi.pillar.JsonReporter")
def test_register(mocked_reporter):
mock_reporter = Mock()
mock_reporter.laws = list()
mocked_reporter.return_... |
11442405 | import json
def load_fixture(path: str):
with open(f"tests_unit/fixtures/{path}") as json_file:
return json.load(json_file)
|
11442442 | import requests
import re
from urllib import request
from bs4 import BeautifulSoup as bs
from datetime_helper import get_yesterday_date,datetime_to_str,str_to_date
save_flows_file = 'sub_flows.txt'
sub_data_js_file = 'sub_data.js'
def get_page_url(page):
base_url = 'https://www.bjsubway.com/support/cxyd/klxx/ind... |
11442450 | import tensorflow as tf
import numpy as np
import argparse
from PIL import Image
import cv2
from scipy.io import loadmat,savemat
from faceReconstruction.preprocess_img import Preprocess
from faceReconstruction.load_data import *
from faceReconstruction.reconstruct_mesh import Reconstruction
import os
def p... |
11442452 | import serial
import time
import cv2
from picamera import PiCamera
import numpy as np
# from scipy import io
import multiprocessing
import math
import threading
# import matplotlib.pyplot as plt
class MySerial:
def __init__(self):
self._ser = serial.Serial('/dev/ttyAMA0', 9600) # 初始化串口
# 命令初始化
... |
11442469 | import enum
import socket
import zmq
from .exceptions import ZebrokNotImplementedError
class SocketType(enum.Enum):
"""
Type of socket connection to be established
"""
ZmqPull = zmq.PULL
ZmqPush = zmq.PUSH
def convert_hostname_to_ip(hostname):
"""
Converts host name... |
11442483 | import pandas as pd
import numpy as np
import torch
import matplotlib.pyplot as plt
import os
import sys
import pickle
from torchid.ssfitter import NeuralStateSpaceSimulator
from torchid.ssmodels import NeuralStateSpaceModel
if __name__ == '__main__':
dataset_type = 'val'
model_type = '1step_nonoise'
COL... |
11442497 | def test():
assert Token.has_extension(
"reversed"
), "Você registrou a extensão no token?"
ext = Token.get_extension("reversed")
assert ext[2] is not None, "Você definiu o getter corretamente?"
assert (
"getter=get_reversed" in __solution__
), "Você atribuiu a função get_reverse... |
11442500 | import pickle
from .interface import *
class MemoryTree(MemoryManager):
"""Memory Tree
A basic memory tree.
Extends:
MemoryManager
"""
def __init__(self, n_children):
self.n_children = n_children
self.root = None
def set_root(self, state, h):
"""Set tree's r... |
11442504 | from tkinter import *
root = Tk()
root.title("calculator")
root.iconbitmap("C:/Users/lalita/Downloads//icon.ico")
e=Entry(root,width=55,borderwidth=10,bg="white")
e.grid(row=0,column=0,padx=10,pady=10,columnspan=4)
def button_click(number):
num=e.get()
e.delete(0,END)
e.inse... |
11442527 | import sys
from pathlib import Path
sys.path.append("_vendor")
from . import gui
gui.create_menu()
__version__ = "0.7.1"
TEST_DIR = Path(__file__).parent.parent / "tests"
TESTDATA_DIR = TEST_DIR / "testdata"
|
11442565 | print(exec("def foo(): return 42"))
print(foo())
d = {}
exec("def bar(): return 84", d)
print(d["bar"]())
|
11442579 | import atexit
import functools
from pyspark import SparkConf, SparkContext
import six
import sys
import os
from stolos.plugins import api, log_and_raise, TasksConfigBaseMapping
from . import log
def receive_kwargs_as_dict(func):
"""A decorator that recieves a dict and passes the kwargs to wrapped func.
It's ... |
11442596 | import asyncio
import sys
from db import create_engine
from constants import SYMBOL
from binance_helpers import init_binance_socket_manager, read_binance_symbol
async def main():
symbol = SYMBOL
if len(sys.argv) == 2:
symbol = sys.argv[1]
engine = create_engine(symbol)
bm = await init_binance_... |
11442615 | from django.contrib import admin
# Register your models here.
from .models import LimitRule, LogEventParser, ParseHelper
admin.site.register(LimitRule)
admin.site.register(LogEventParser)
admin.site.register(ParseHelper)
|
11442623 | import sys
sys.path.append('../')
from util import parameter_number
from sklearn.metrics import accuracy_score
import torch
import torch.optim as optim
import torch.nn as nn
class Manager():
def __init__(self, model, args):
self.args_info = args.__str__()
self.device = torch.device('cuda:{}'.format... |
11442629 | import json
import datetime
import time
import os
import boto3
from boto3.dynamodb.conditions import Key, Attr
import redis
from datetime import timedelta
# Updates game server data to Redis (called by the game servers)
# Also checks any outdated placement reservations on the server (clients that got a placement but n... |
11442653 | from .. import rfb_icons
from ..rfb_utils.prefs_utils import get_pref
import bpy
# ------- Subclassed Panel Types -------
class _RManPanelHeader():
COMPAT_ENGINES = {'PRMAN_RENDER'}
@classmethod
def poll(cls, context):
return context.engine in cls.COMPAT_ENGINES
def draw_header(self, context)... |
11442671 | import pandas as pd
print(pd.__version__)
# 1.2.2
df = pd.read_csv('data/src/sample_date.csv',
index_col='date', parse_dates=True).head(3)
print(df)
# val_1 val_2
# date
# 2017-11-01 65 76
# 2017-11-07 26 66
# 2017-11-18 47 47
print(type(df.i... |
11442673 | import os
import random
import tempfile
import pytest
import teek
SMILEY_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'smiley.gif')
def test_width_and_height():
image = teek.Image(file=SMILEY_PATH)
assert image.width == 32
assert image.height == 32
# tests that use th... |
11442678 | import os, logging
def build(obj):
ddl_source = os.path.join( obj.source_folder, "aasb", "messages" )
if os.path.exists( ddl_source ):
from buildconfig import run
logging.info( "Building AASB message headers..." )
run.start( ddl_source, os.path.join( obj.build_folder, "aasb-message-head... |
11442698 | import os
import math
from collections import OrderedDict
import itertools
import torch
from tslearn.metrics import dtw_path
import numpy as np
from bpe.model import networks_bpe
class SimilarityAnalyzer:
def __init__(self, config, model_path):
self.body_parts = config.default_body_parts
self.bo... |
11442702 | import os
import wx
# ordered for modifier entries in menus
modifiernames = [
(wx.ACCEL_CTRL, 'Ctrl'),
(wx.ACCEL_ALT, 'Alt'),
(wx.ACCEL_SHIFT, 'Shift'),
# (wx.ACCEL_CMD, 'Ctrl'),
]
keynames = {
wx.WXK_MENU: 'Menu',
wx.WXK_NUMPAD_TAB: 'Numpad Tab',
wx.WXK_NUMPAD_SEPARATOR: 'Numpad Separator',... |
11442709 | HELPER_SETTINGS = {
'TIME_ZONE': 'Europe/Zurich',
'INSTALLED_APPS': [
'filer',
'aldryn_boilerplates',
'easy_thumbnails',
'aldryn_gallery',
],
'TEMPLATE_CONTEXT_PROCESSORS': [
'aldryn_boilerplates.context_processors.boilerplate',
],
'STATICFILES_FINDERS': [... |
11442740 | import abc
from abc import abstractmethod
from dataclasses import dataclass
from typing import List, Optional, Type, Union
from nuplan.common.actor_state.state_representation import StateSE2
from nuplan.common.maps.abstract_map import AbstractMap
from nuplan.common.maps.maps_datatypes import TrafficLightStatusData
fro... |
11442759 | import torch
from torch import nn
from model.sentence_encoder import sentence_encoder
class SentenceBERTClassifier(nn.Module):
def __init__(self, dataset, sentence_model, device, number_layers=2, layer_size=256, minimum_layer_size=8,
dropout_rate=0.0):
super().__init__()
self.data... |
11442793 | def quicksort(numbers, low, high):
"""Python implementation of quicksort."""
if low < high:
pivot = _partition(numbers, low, high)
quicksort(numbers, low, pivot)
quicksort(numbers, pivot + 1, high)
return numbers
def _partition(numbers, low, high):
pivot = numbers[low]
le... |
11442801 | from dataclasses import dataclass
from pathlib import Path
from typing import Dict
from unittest.mock import patch
from coltrane.renderer import StaticRequest, render_markdown
def test_render_markdown(settings, tmp_path: Path):
settings.BASE_DIR = tmp_path
(tmp_path / "content").mkdir()
(tmp_path / "con... |
11442844 | from .env import BaseModelBasedEnv, BaseBatchedEnv
from .policy import BasePolicy, BaseNNPolicy
from .q_function import BaseQFunction, BaseNNQFunction
from .v_function import BaseVFunction, BaseNNVFunction
from .runner import Runner
from .utils import compute_advantage, gen_dtype
|
11442854 | from reskit import TEST_DATA
from reskit.wind.core.power_curve import PowerCurve, compute_specific_power
import numpy as np
import pandas as pd
import pytest
def test_compute_specific_power():
assert np.isclose(compute_specific_power(4200, 136), 289.1223014645158)
output = compute_specific_power(np.linspace... |
11442904 | from .PBXResolver import *
from .PBX_Base_Target import *
class PBXAggregateTarget(PBX_Base_Target):
def __init__(self, lookup_func, dictionary, project, identifier):
super(PBXAggregateTarget, self).__init__(lookup_func, dictionary, project, identifier); |
11442913 | import maya.cmds as mc
import maya.OpenMaya as OpenMaya
import glTools.utils.mesh
import glTools.utils.stringUtils
import os
import os.path
import gzip
def writeGeoCache(path,name,mesh,startFrame,endFrame,pad=4,uvSet='',worldSpace=True,gz=False):
'''
Write a .geo cache per frame for the specified mesh geometry.
... |
11442921 | from abc import ABC, abstractmethod
class Agent(ABC):
@abstractmethod
def getAction(self, game):
pass
@abstractmethod
def action_lookup(self, action):
pass |
11442927 | import pytest
from typing import List
import spacy
from spacy.tokens import Doc
from scripts.azure.azure_ner_pipe import (
make_azure_entity_recognizer,
AzureEntityRecognizer,
)
from scripts.azure.text_analytics import (
TextAnalyticsClient,
ResponseBody,
ResponseDocument,
)
class MockTextAnalytic... |
11443042 | import socket
import netifaces
import dns.resolver
import config
LOOPBACK_NETWORK_NAME = netifaces.interfaces()[0]
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.