id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
416291 | import torch
import os
from utils import geo_utils, ba_functions
import numpy as np
def prepare_predictions(data, pred_cam, conf, bundle_adjustment):
# Take the inputs from pred cam and turn to ndarray
outputs = {}
outputs['scan_name'] = data.scan_name
calibrated = conf.get_bool('dataset.calibrated')
... |
416301 | import numpy as np
import pytest
from neutralocean.eos.tools import vectorize_eos
from neutralocean.eos.jmd95 import rho as rho_jmd95
from neutralocean.eos.jmd95 import rho_s_t as rho_s_t_jmd95
from neutralocean.eos.jmd95 import rho_p as rho_p_jmd95
from neutralocean.eos.jmdfwg06 import rho as rho_jmdfwg06
from neut... |
416306 | import pyarrow.parquet as pq
import pandas as pd
import numpy as np
import json
from typing import List, Callable, Iterator, Union, Optional
from sportsdataverse.errors import SeasonNotFoundError
from sportsdataverse.dl_utils import download
def espn_mbb_schedule(dates=None, groups=None, season_type=None, limit=500) -... |
416311 | from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
Lattice = SchLib(tool=SKIDL).add_parts(*[
Part(name='GAL16V8',dest=TEMPLATE,tool=SKIDL,keywords='GAL PLD 16V8',description='Programmable Logic Array, DIP-20/SOIC-20/PLCC-20',ref_prefix='U',num_units=1,fplist=['DIP*', 'PDIP*', 'SO... |
416329 | import sys
import struct
import time
from i2cdriver import I2CDriver, EDS
if __name__ == '__main__':
i2 = I2CDriver(sys.argv[1])
d = EDS.Magnet(i2)
while 1:
print(d.measurement())
|
416372 | from datetime import datetime
from agent import source, cli
from ..test_zpipeline_base import TestInputBase
from ...conftest import generate_input
class TestClickhouse(TestInputBase):
__test__ = True
params = {
'test_source_create': [{'name': 'test_jdbc_clickhouse', 'type': 'clickhouse', 'conn': 'clic... |
416472 | import numpy as np;
m=5;
n=7;
c = np.array( [2, 1.5, 0, 0, 0, 0, 0] );
A = np.array( [ [12, 24, -1, 0, 0, 0, 0],
[16, 16, 0, -1, 0, 0, 0],
[30, 12, 0, 0, -1, 0, 0],
[1, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 1] ] );
b = np.array( [ 120, 120, 120, 15, 15] );
x = np.array( [14, 1, 72, 120, 312, 1, 14] ... |
416491 | import trio
import serverwamp
from serverwamp.adapters.trio import TrioAsyncSupport
async def long_running_job(session):
await session.send_event('job_events', job_status='STARTED')
await trio.sleep(3600)
await session.send_event('job_events', job_status='COMPLETED')
rpc_api = serverwamp.RPCRouteSet()
... |
416501 | import asyncio
# This example uses the sounddevice library to get an audio stream from the
# microphone. It's not a dependency of the project but can be installed with
# `pip install sounddevice`.
import sounddevice
from amazon_transcribe.client import TranscribeStreamingClient
from amazon_transcribe.handlers import ... |
416522 | import numpy as np
class Rotor:
def __init__(self, position_body, direction_body, clockwise, torque_coef):
self.position = position_body
self.direction = direction_body
self.direction = self.direction / np.linalg.norm(self.direction)
self.clockwise = clockwise
self.torque_co... |
416566 | from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7
#import kratos core and applications
import KratosMultiphysics
import KratosMultiphysics.SolidMechanicsApplication as KratosSolid
## This proces sets the value of a scalar variable t... |
416572 | import datetime
import logging
import pathlib
from jinja2 import Environment, PackageLoader, select_autoescape
import async_imgkit.api
import pi_weatherstation.helpers as helpers
try:
import pi_weatherstation.output.display.ST7789_display as display
except ModuleNotFoundError:
logging.warning("Problem loadin... |
416576 | import os
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECURITY WARNING: keep the secret key used in production secret!... |
416719 | from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Activation
from keras.layers.merge import Concatenate
from keras.models import Model
from keras.regularizers import l2
from ..utils.net_uti... |
416757 | import torch
from torchvision.transforms import functional as F
class Compose():
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, target):
for t in self.transforms:
image, target = t(image, target)
return image, target
class ToTensor... |
416774 | import wx
from meerk40t.gui.laserrender import swizzlecolor
from meerk40t.kernel import Context
from meerk40t.svgelements import Color
_ = wx.GetTranslation
class PropertiesPanel(wx.Panel):
"""
PropertiesPanel is a generic panel that simply presents a simple list of properties to be viewed and edited.
I... |
416799 | import torch
from typing import Dict, Any
from .result import Result
class ModelInterface:
def create_input(self, data: Dict[str, torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
def decode_outputs(self, outputs: Result) -> Any:
raise NotImplementedError
def __call__(self, data:... |
416842 | import json
from datetime import datetime
from decimal import Decimal
import numpy as np
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded.
"""
numpy_ty... |
416847 | from __future__ import division, print_function, unicode_literals
import os
import re
from DateTime import DateTime
from HTMLParser import HTMLParser
def seperate_metadata_and_content(s):
"""
Given a string the metadata is seperated from the content. The string must be in the following format:
metada... |
416896 | import os
from models.inference_model import InferenceModel
import config
import utils.utils as utils
import torch
import PIL.Image as Image
import torchvision.transforms as transforms
from tqdm import tqdm
import argparse
# inference configurations #
network_name = 'on_white_II'
use_saved_config = False # use the c... |
416919 | import numpy as np
import torch
import torch.distributions as dist
from torch import nn
from modules.commons.conv import ConditionalConvBlocks
from modules.commons.normalizing_flow.res_flow import ResFlow
from modules.commons.wavenet import WN
class FVAEEncoder(nn.Module):
def __init__(self, c_in, hidden_size, c... |
416956 | class ArrayParam:
def mfouri(self, oper="", coeff="", mode="", isym="", theta="", curve="", **kwargs):
"""Calculates the coefficients for, or evaluates, a Fourier series.
APDL Command: ``*MFOURI``
Parameters
----------
oper
Type of Fourier operation:
... |
416962 | import os
import tempfile
import torch
from pytorch_transformers import BertTokenizer
from onir.interfaces import bert_models
from onir import vocab, util, config
from onir.modules import PrettrBertModel
import tokenizers as tk
@vocab.register('prettr_bert')
class PrettrBertVocab(vocab.Vocab):
@staticmethod
d... |
416973 | import time
import argparse
import traceback
import numpy as np
import torch
from torch.utils.data import DataLoader
import networkx as nx
import dgl
from models import MLP, InteractionNet, PrepareLayer
from dataloader import MultiBodyGraphCollator, MultiBodyTrainDataset,\
MultiBodyValidDataset, MultiBodyTestData... |
417017 | import unittest
import datetime
from google.cloud import bigquery
from .. import bqclient_test
from ..bqclient import BqClient
class Test(unittest.TestCase):
def setUp(self):
self.query = 'SELECT count(*) FROM `bigquery-public-data.usa_names.usa_1910_current` WHERE year=2017 AND number>1000;'
def ... |
417023 | from datetime import timedelta, datetime
import pytest
from pandas_to_sql.testing.utils.asserters import assert_, get_expected_and_actual
from copy import copy
import pandas as pd
import pandas_to_sql
def test_replace():
df = pytest.df1
df['new_value'] = df.random_str.str.replace('m','v').str.replace('z','_3... |
417039 | from flask import session, Blueprint
from lexos.helpers import constants as constants
from lexos.managers import session_manager as session_manager
from lexos.models.k_means_model import KMeansModel
from lexos.views.base import render
k_means_blueprint = Blueprint("k-means", __name__)
@k_means_blueprint.route("/k-me... |
417065 | from typing import Optional
from abc import abstractmethod
from mobilium_proto_messages.message_processor import MessageProcessor
from mobilium_proto_messages.message_sender import MessageSender
from mobilium_server.utils.shell_executor import ShellExecutor
class ShellMessageProcessor(MessageProcessor):
def __i... |
417066 | from pyravendb.tests.test_base import TestBase
from pyravendb.data.query import Facet, FacetMode
from pyravendb.raven_operations.maintenance_operations import PutIndexesOperation
from pyravendb.data.indexes import IndexDefinition
import unittest
class Product(object):
def __init__(self, name, price_per_unit):
... |
417142 | from django.contrib import admin
# Register your models here.
from .models import Spot, Comment
# Register your models here.
class SpotAdmin(admin.ModelAdmin):
list_display = ('id', 'city', 'name', 'longitude', 'latitude',
'commit_user_name', 'commit_message', 'commit_date')
search_fields = (
... |
417175 | from . import sql
CUSTOM_REPORTS = (
('Custom Reports', (
sql.DistrictMonthly,
sql.HeathFacilityMonthly,
sql.DistrictWeekly,
sql.HealthFacilityWeekly,
)),
)
|
417179 | from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
from hazelcast.protocol.builtin import CodecUtil
# hex: 0x013900
_REQUEST_MESSAGE_TYPE = 80128
# hex: 0x013901
_R... |
417224 | def LCSlength(X, Y, lx, ly): # Parameters are the two strings and their lengths
if lx == 0 or ly == 0:
return 0
if X[lx - 1] == Y[ly - 1]:
return LCSlength(X, Y, lx - 1, ly - 1) + 1
return max(LCSlength(X, Y, lx - 1, ly), LCSlength(X, Y, lx, ly - 1))
print("Enter the first string : \n")
X... |
417247 | import chainer
import chainer.functions as F
import chainer.links as L
class NumberRecognizeNN(chainer.Chain):
def __init__(self, input_size, output_size, hidden_size=200, layer_size=3):
self.input_size = input_size
self.output_size = output_size
self.hidden_size = hidden_size
sel... |
417280 | from src.automata.ldba import LDBA
# an example automaton for "goal1 or goal2 while avoiding unsafe" or "(FG goal1 | FG goal2) & G !unsafe"
# automaton image is available in "./assets" or "https://i.imgur.com/gyDED4O.png"
# only the automaton "step" function and the "accepting_sets" attribute need to be specified
# "a... |
417289 | from pyziabm.orderbook3 import Orderbook
import unittest
class TestOrderbook(unittest.TestCase):
'''
Attribute objects in the Orderbook class include:
order_history: list
_bid_book: dictionary
_bid_book_prices: sorted list
_ask_book: dictionary
_ask_book_prices: sorted ... |
417316 | import sys
import os
from . import performance_tester as pt
from argparse import ArgumentParser
def main(args=None):
if args is None:
# command line arguments
parser = ArgumentParser(description='performance_tester.py: '
'tests pyJac performance'
... |
417350 | import torch
from torch.nn.parameter import Parameter
import torch.nn.init as init
class ScaleLayer(torch.nn.Module):
def __init__(self, num_features, use_bias=True):
super(ScaleLayer, self).__init__()
self.weight = Parameter(torch.Tensor(num_features))
init.ones_(self.weight)
self... |
417384 | import os
from os import path
import sys
import shutil, glob
import logging
import uuid
import hashlib
from subprocess import PIPE, STDOUT
import lib
from lib import CouldNotLocate, task
LOG = logging.getLogger(__name__)
class IEError(Exception):
pass
@task
def package_ie(build, **kw):
'Sign executables, Run NSIS... |
417385 | import pandas
class Static:
CURRENT_PLOT = None
PLOTS = []
class Plot:
def __init__(self, **kwargs):
# TODO - fix how chart type is assuigned. the use of messy right now
self.layers = []
if "chart_type" in kwargs:
self.chart_type = kwargs["chart_type"]
else:
... |
417437 | from mpas_analysis.shared.regions.compute_region_masks_subtask \
import ComputeRegionMasksSubtask, get_feature_list
from mpas_analysis.shared.regions.compute_region_masks \
import ComputeRegionMasks
|
417440 | from enum import Enum
from typing import Optional
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.utils._encode import _check_unknown
from sklearn.utils._encode import _encode
from etna.datasets import TSDataset
from etna.transforms.base import Transform
class ImputerMode(str, ... |
417447 | import os
from mattermostdriver import Driver
from requests.exceptions import ConnectionError, HTTPError
from patter.exceptions import (
FileUploadException,
MissingChannel,
MissingEnvVars,
MissingUser,
)
config_vars = {
"MATTERMOST_TEAM_NAME": os.getenv("MATTERMOST_TEAM_NAME", None),
"MATTE... |
417465 | import time
import os
import glob
import inspect
import gym
import pybullet_envs
from gym.envs.registration import load
from stable_baselines.deepq.policies import FeedForwardPolicy
from stable_baselines.common.policies import register_policy
from stable_baselines.bench import Monitor
from stable_baselines import logg... |
417510 | import enum
class MoveDirection(enum.Enum):
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
class CountDirection(enum.IntEnum):
HORIZONTAL = 0
VERTICAL = 1
class ResettableCount:
resetLoop = False
def __init__(self, resets_to_nonzero):
self.totalCount = 0
se... |
417530 | from django.conf.urls import url
from apps.mock_server.views import http_server
from apps.mock_server.views import http_interface
urlpatterns = [
url(r'^mock/([\w\-\.]+)/([\w\-\.]+)/([\w\-\.]+)([\w\-\.\/]+)$', http_server.mock),
url(r'^mockserver/readme$', http_server.readme, name="MOCK_HTTP_readme"),
#ad... |
417546 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.SimulatedConv2d(4,4,4,'../simulation_files/tpu_16_16_pes.cfg', 'dogsandcats_tpu_tile.txt', sparsity_ratio=0.0, groups=4) # Number of input feature maps (in... |
417571 | import uuid
import walrus
from spyne.application import Application
from spyne.service import ServiceBase
from spyne.model.primitive import Integer, Unicode
from spyne.model.complex import Iterable, ComplexModel, Array
from spyne.decorator import srpc
from spyne.protocol.soap import Soap11
import time
from lxml import ... |
417647 | r"""
Contains helper functions to extract skeleton data from the NTU RGB+D dataset.
Three functions are provided.
- *read_skeleton*: Parses entire skeleton file and outputs skeleton data in a dictionary
- *read_xyz*: Only keeps 3D coordinates from dictionary and returns numpy version.
- *read_xy_ir*: Only... |
417716 | from utils import *
data_dir = '/Users/kylemathewson/Desktop/data/'
exp = 'P3'
subs = [ '001']
sessions = ['ActiveWet']
nsesh = len(sessions)
event_id = {'Target': 1, 'Standard': 2}
sub = subs[0]
session = sessions[0]
raw = LoadBVData(sub,session,data_dir,exp)
epochs = PreProcess(raw,event_id,
emcp_epochs=... |
417724 | from .Config import Config
class SearchHelper:
@staticmethod
def getChannelIdExamples():
return Config.CHANNEL_ID_EXAMPLES
@staticmethod
def getVideoClipIdExamples():
return Config.VIDEO_CLIP_ID_EXAMPLES
@staticmethod
def getUrlExamples():
return Config.URL_EXAMPLES |
417734 | import torch
import torch.nn.functional as F
from tqdm import tqdm
from dice_loss import dice_coeff
def eval_net(net, loader, device, n_val):
"""Evaluation without the densecrf with the dice coefficient"""
net.eval()
tot = 0
with tqdm(total=n_val, desc='Validation round', unit='img', leave=False) as... |
417746 | import logging
from typing import BinaryIO, List
import numpy as np
from .known import vlr_factory, IKnownVLR
from .vlr import VLR
from ..utils import encode_to_len
logger = logging.getLogger(__name__)
RESERVED_LEN = 2
USER_ID_LEN = 16
DESCRIPTION_LEN = 32
class VLRList(list):
"""Class responsible for managin... |
417751 | from .. import *
def get_dataset_from_code(code, batch_size):
""" interface to get function object
Args:
code(str): specific data type
Returns:
(torch.utils.data.DataLoader): train loader
(torch.utils.data.DataLoader): test loader
"""
dataset_root = "./assets/data"
if ... |
417760 | import traceback
import cv2
import os
from pluto.common.utils import SrtUtil, TimeUtil
class Snapshot(object):
def __init__(self):
self.video_file = ""
self.video_capture = None
self.srt_file = ""
self.srt_subs = []
self.width = 0
self.height = 0
self.dura... |
417772 | import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from torchvision.datasets.folder import default_loader
from tqdm import tqdm
logger = logging.getLogger(__file__)
def _... |
417807 | from sqlalchemy import (
Column,
ForeignKey,
Integer,
String,
Float,
Index,
Table,
Enum
)
from ..app import db
class SourceRole(db.Model):
"""
A role linked to a document source.
"""
__tablename__ = "source_roles"
id = Column(Integer, primary_key=True)
... |
417815 | import logging
import os
import tkinter as tk
import tkinter.ttk as ttk
import typing
from tkinter.filedialog import askopenfilename
from fishy.engine.common.event_handler import IEngineHandler
from fishy.engine.fullautofisher.mode.imode import FullAutoMode
from fishy.helper import helper
from fishy import web
from f... |
417861 | import os
import sys
import shlex
import logging
import datetime
import subprocess
def git_hash():
cmd = 'git log -n 1 --pretty="%h"'
ret = subprocess.check_output(shlex.split(cmd)).strip()
if isinstance(ret, bytes):
ret = ret.decode()
return ret
def git_diff_config(name):
cmd = f'git di... |
417862 | import ast
import glob
import os
import sys
from libpy.build import LibpyExtension
from setuptools import find_packages, setup
if ast.literal_eval(os.environ.get("LIBPY_SIMDJSON_DEBUG_BUILD", "0")):
optlevel = 0
debug_symbols = True
max_errors = 5
else:
optlevel = 3
debug_symbols = False
max_e... |
417901 | from triggerflow.service.storage import TriggerStorage
def add_event_source(trigger_storage: TriggerStorage, workspace: str, event_source: dict, overwrite: bool):
# Check eventsource schema
if {'name', 'class', 'parameters'} != set(event_source):
return {"error": "Invalid eventsource object"}
exi... |
417918 | import requests
import json
# Extracts a region from each frame of a given GIF file
# https://pixlab.io/#/cmd?id=cropgif for more info.
req = requests.get('https://api.pixlab.io/cropgif',params={
'img': 'http://cloud.addictivetips.com/wp-content/uploads/2009/testing.gif',
'key':'My_PixLab_Key',
"x":150,
"y":70,
... |
417919 | from typing import Any, Dict, Sequence, Tuple, Union
import higher
import hydra
import pytorch_lightning as pl
import torch
from omegaconf import DictConfig
from torch.optim import Optimizer
import torch.nn.functional as F
class BaseModel(pl.LightningModule):
def __init__(self, cfg: DictConfig, *args, **kwargs) ... |
417940 | from unittest import mock
import unittest
import os
import shutil
import io
import re
import zipfile
import time
import functools
from webscrapbook import WSB_DIR, Config
from webscrapbook import util
from webscrapbook.scrapbook.host import Host
from webscrapbook.scrapbook import book as wsb_book
from webscrapbook.scra... |
418074 | import pytest
grblas = pytest.importorskip("grblas")
from metagraph.plugins.python.types import PythonNodeMapType
from metagraph.plugins.numpy.types import NumpyNodeMap, NumpyNodeSet
from metagraph.plugins.graphblas.types import GrblasNodeMap, GrblasNodeSet
from metagraph import NodeLabels
import numpy as np
from grb... |
418080 | import euclid
from euclid import *
from solid.utils import * # Only needed for EPSILON. Tacky.
# NOTE: The PyEuclid on PyPi doesn't include several elements added to
# the module as of 13 Feb 2013. Add them here until euclid supports them
def as_arr_local( self):
return [ self.x, self.y, self.z]
def set_leng... |
418086 | from DyCommon.Ui.DyTableWidget import *
class DyStockTradeStrategyMarketMonitorDataWidget(DyTableWidget):
""" 股票实盘策略数据窗口 """
def __init__(self, strategyCls):
super().__init__(None, True, False)
self._strategyCls = strategyCls
self.setColNames(strategyCls.dataHeader)
self.set... |
418087 | import KratosMultiphysics as Kratos
import KratosMultiphysics.StatisticsApplication as KratosStats
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.StatisticsApplication.spatial_utilities import GetItemContainer
from KratosMultiphysics.StatisticsApplication.method_utilities import Get... |
418095 | from __future__ import print_function
import errno
import matplotlib
matplotlib.use('Agg')
import shutil
from subprocess import Popen, PIPE, check_output
import os
import pwd
import shlex
import sys
import time
import glob
import math
print("*****************************")
print("OpenWorm Master Script v0.9.1")
print(... |
418099 | from marshmallow import Schema, fields
from werkzeug.exceptions import Forbidden
from opendc.models.topology import ObjectSchema
from opendc.models.model import Model
class PrefabSchema(Schema):
"""
Schema for a Prefab.
"""
_id = fields.String(dump_only=True)
authorId = fields.String(dump_only=Tr... |
418115 | import torch
import torch.nn as nn
import helper_functions.config as cfg
from helper_functions.losses import custom_loss
from helper_functions.Blocks import upScale, normalBlock, Residual
class G1(nn.Module):
def __init__(self, ngf, zDim = 100):
super(G1, self).__init__()
self.gf_dim = ngf
... |
418141 | import unittest
import os
import sys
if os.environ.get('USELIB') != '1':
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pyleri import (
KeywordError,
create_grammar,
Sequence,
Choice,
Keyword,
Token,
List
) # nopep8
class TestList(unittest.TestCase):
def ... |
418147 | from django.db import connections
from pdns.models import Domain
query = "INSERT INTO domainmetadata (domain_id, kind, content) VALUES (%s, 'ALLOW-AXFR-FROM', 'AUTO-NS')"
with connections["pdns"].cursor() as cursor:
cursor.execute('SELECT DISTINCT domain_id FROM domainmetadata')
ok_domains = [row[0] for row ... |
418149 | import sc2
class ExampleBot(sc2.BotAI):
async def on_step(self, iteration):
# On first step, send all workers to attack enemy start location
if iteration == 0:
print("Game started")
for worker in self.workers:
await self.do(worker.attack(self.enemy_start_loca... |
418174 | import mmcv
from mmcv.utils import Registry
def _build_func(name: str, option: mmcv.ConfigDict, registry: Registry):
return registry.get(name)(option)
MODELS = Registry('models', build_func=_build_func)
|
418176 | from fontTools.ttLib.tables._v_m_t_x import table__v_m_t_x
import _h_m_t_x_test
import unittest
class VmtxTableTest(_h_m_t_x_test.HmtxTableTest):
@classmethod
def setUpClass(cls):
cls.tableClass = table__v_m_t_x
cls.tag = "vmtx"
if __name__ == "__main__":
import sys
sys.exit(unittes... |
418211 | from functools import partial
from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import (
WebDriverWait
)
class EsperarElementoNotClick:
def __init__(self, locator):
self.locator = locator
def __call__(self, webdriver):
el... |
418230 | import numpy as np
from utility import *
# Not using rn, but maybe this is useful?
class SignalData:
I = None
II = None
III = None
aVR = None
aVL = None
aVF = None
V1 = None
V2 = None
V4 = None
V3 = None
V5 = None
V6 = None
def leadValues(text: str, conversion) -> boo... |
418292 | from threading import Lock, currentThread
class _SingletonPerThreadMetaClass(type):
""" A metaclass that creates a SingletonPerThread base class when called. """
_instances = {}
_lock = Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
obj_name = "%s__%s" % (cls.__name__,... |
418392 | import FWCore.ParameterSet.Config as cms
idealMagneticFieldRecordSource = cms.ESSource("EmptyESSource",
recordName = cms.string('IdealMagneticFieldRecord'),
iovIsRunNotTime = cms.bool(True),
firstValid = cms.vuint32(1)
)
ParametrizedMagneticFieldProducer = cms.ESProducer("ParametrizedMagneticFieldProducer... |
418403 | from dexp.datasets.base_dataset import BaseDataset
from dexp.datasets.clearcontrol_dataset import CCDataset
from dexp.datasets.joined_dataset import JoinedDataset
from dexp.datasets.zarr_dataset import ZDataset
|
418425 | import numpy as np
import vggnet, resnet, wide_resnet, inception_light
def one_hot(dense, ndim=10):
N = dense.shape[0]
ret = np.zeros([N, ndim])
ret[np.arange(N), dense] = 1
return ret
def get_model(name, learning_rate=0.001, SEED=777, resnet_layer_n=3):
# right position..?
if name == "vggnet... |
418428 | from FordStuff import *
import time
# initalize
mydll = CDLL('Debug\\ecomcat_api')
# HS CAN
handle = mydll.open_device(1,0)
# get current
read_by_wid = mydll.read_message_by_wid_with_timeout
read_by_wid.restype = POINTER(SFFMessage)
z = mydll.read_message_by_wid_with_timeout(handle, 0x80, 1000)
curren... |
418458 | import os
import subprocess
from datetime import datetime
from jinja2 import Environment
from moban.externals.file_system import exists, is_dir, read_unicode
import fs
import yehua.utils as utils
from yehua.utils import get_user_inputs
from jinja2_fsloader import FSLoader
class Project:
def __init__(self, yehua... |
418461 | from django.core import paginator
from django.http import JsonResponse
from myapp import common
from myapp.common import ch_login
from myapp.models import MicroBlog, Collect
from myapp.const import *
# 收藏实体记录(0博客,1新闻【必须要有itemUrl】,2音乐)
@ch_login
def collect(request):
r_userid = request.META.get("HTTP_USERID")
... |
418485 | import graphAttack as ga
import numpy as np
import scipy.optimize
"""Control script"""
def run():
"""Run the model"""
N, T, D, H1, H2 = 2, 3, 4, 5, 4
trainData = np.linspace(- 0.1, 0.3, num=N * T * D).reshape(N, T, D)
trainLabels = np.random.random((N, T, D))
mainGraph = ga.Graph(False)
xop ... |
418486 | import json
import os
from setuptools.command.install import install
class InstallEntry(install):
def run(self):
default_site = 'codeforces'
cache_dir = os.path.join(os.path.expanduser('~'), '.cache', 'coolkit')
from main import supported_sites
for site in supported_sites:
... |
418496 | from scan_worker import scan
import time
import json
from storage.storage_manager import StorageManager
from push import RestApiPusher
from config import *
from storage.tables.vuln_task import VulnTask
storageManager = StorageManager()
storageManager.init_db()
def get_all_targets():
targets = ["http://testhtml5.... |
418512 | from django import forms
from django.db import models
from django.test import TestCase
from django.test.utils import override_settings
from sanitizer.templatetags.sanitizer import (sanitize, sanitize_allow,
escape_html, strip_filter, strip_html)
from .forms import SanitizedCharField as SanitizedFormField
from .mod... |
418529 | import asyncio
import logging
import json
import re
import asyncio
import datetime
from pyenvisalink import EnvisalinkClient
from pyenvisalink.dsc_envisalinkdefs import *
_LOGGER = logging.getLogger(__name__)
from asyncio import ensure_future
class DSCClient(EnvisalinkClient):
"""Represents a dsc alarm client.""... |
418536 | from .Auth import Auth
from .Csrf import Csrf
from .Sign import Sign
from .MustVerifyEmail import MustVerifyEmail
|
418544 | import random as rnd
import statistics as stat
import matplotlib.pyplot as plt
import numpy as np
import math
Avg_IAT = 1.0 # Average Inter-Arrival Time
Avg_ST = 0.5 # Average Service Time
Num_Sim_Pkts = 10000 # Number of Simulated Packets
Infinity = math.inf # A very large Number
N = 0.0 # Number of cu... |
418565 | import zipfile
import sys
import paradoxparser
import datetime
TECH_SCORE_MULTIPLIER = 10
ACCUMULATED_ENERGY_MULTIPLIER = 0.1
ACCUMULATED_MINERALS_MULTIPLIER = 0.05
ACCUMULATED_INFLUENCE_MULTIPLIER = 0.05
ENERGY_PRODUCTION_MULTIPLIER = 2
MINERAL_PRODUCTION_MULTIPLIER = 1.5
INFLUENCE_PRODUCTION_MULTIPLIER = 1
NUM_SUBJE... |
418610 | def get_inverse_ub_matrix_from_xparm(handle):
"""Get the inverse_ub_matrix from an xparm file handle
Params:
handle The file handle
Returns:
The inverse_ub_matrix
"""
from scitbx import matrix
return matrix.sqr(
handle.unit_cell_a_axis + handle.unit_cell_b_axis + handl... |
418622 | import numpy as np
import scipy.sparse as sp
from scipy import linalg
from graphgallery.utils import tqdm
from graphgallery import functional as gf
from graphgallery.attack.targeted import Common
from ..targeted_attacker import TargetedAttacker
from .nettack import compute_alpha, update_Sx, compute_log_likelih... |
418630 | from discoverlib import geom, graph
import numpy
import math
from multiprocessing import Pool
import os.path
from PIL import Image
import random
import scipy.ndimage
import sys
import time
def graph_filter_edges(g, bad_edges):
print 'filtering {} edges'.format(len(bad_edges))
ng = graph.Graph()
vertex_map = {}
fo... |
418643 | import os
from weasyprint import urls
from bs4 import BeautifulSoup
# check if href is relative --
# if it is relative it *should* be an html that generates a PDF doc
def is_doc(href: str):
tail = os.path.basename(href)
_, ext = os.path.splitext(tail)
absurl = urls.url_is_absolute(href)
abspath = os.... |
418648 | import astor
import z3
from .to_z3 import Z3Converter, get_minimum_dt_of_several_anonymous
from crestdsl import sourcehelper as SH
from .epsilon import Epsilon
import logging
logger = logging.getLogger(__name__)
def get_behaviour_change_dt_from_constraintset(solver, constraints, dt, ctx=z3.main_ctx()):
times = {c... |
418652 | import pandas as pd
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import pickle
data = load_boston()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target, name='target')
print('Column order:', list(X.columns))
X.sample(1, random_state=0).iloc... |
418670 | from simple_NER.annotators.remote.dbpedia import SpotlightNER
# you can also self host
host='http://api.dbpedia-spotlight.org/en/annotate'
ner = SpotlightNER(host)
for r in ner.extract_entities("London was founded by the Romans"):
print(r.value, r.entity_type, r.uri)
score = r.similarityScore
"""
Lond... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.