id
stringlengths
3
8
content
stringlengths
100
981k
9977775
from foundations import * f = Foundation() #proc_ready: queue of processes that are ready proc_ready = Queue() #proc_waiting: queue of processes that are waiting to be executed proc_waiting = Queue() #q: denotes the ticks per process q = 0 #i: counter to keep track of the current tick i = 0 results = [] #fcfs(procs: ...
9977798
import os import subprocess def parse_tag(tag): image_type = None version = None if "-" not in tag: version = tag else: image_type, version = tag.split("-") return image_type, version def tag_to_version(tag): image_type, version = parse_tag(tag) return version def ensur...
9977799
import re from datetime import datetime from urllib.parse import urljoin import scrapy from city_scrapers_core.constants import NOT_CLASSIFIED from city_scrapers_core.items import Meeting from city_scrapers_core.spiders import CityScrapersSpider class AlleAssetDistrictSpider(CityScrapersSpider): name = "alle_ass...
9977809
import pytest from aiohttp import BasicAuth from aiohttp_socks import SocksConnector, SocksVer from aiograph import Telegraph, types from aiograph.utils import exceptions def test_prepare_content(): telegraph = Telegraph() with pytest.raises(exceptions.ContentRequired): telegraph._prepare_content(Non...
9977814
import torch import numpy as np from torch.autograd import Variable import torch.nn.functional as F import torch.nn as nn import copy import math import os class speaker_model(nn.Module): def __init__(self, num_inputs, mulspk_type, speakers=None, cuda=False): super(speaker_model, self).__init__() ...
9977884
from datetime import date, datetime from decimal import Decimal from logging import getLogger from typing import Dict, Tuple, Union from xml.etree import ElementTree from .constants import URL_BASE from .currencies import Currency, CURRENCIES from ..exceptions import ExchangeRateNotFound, WrongArguments from .basic im...
9977896
import functools import numpy as np import queueing_tool as qt # Make an adjacency list adja_list = {0: {1: {}}, 1: {k: {} for k in range(2, 22)}} # Make an object that has the same dimensions as your adjacency list that # specifies the type of queue along each edge. edge_list = {0: {1: 1}, 1: {k: 2 for k in range(...
9977930
import time from .data_structures import * from .qallse import Qallse, Config1GeV from .qallse_base import QallseBase class MpConfig(Config1GeV): #: To be kept, a quadruplet needs to be part of at least one chain of #: min_qplet_path or more (including itself). Hence, setting this parameter #: to one has...
9977946
class AnalyzerConf: """Base configuration class (driver specific) used by the rule engine. :return: [description] :rtype: [type] """ # driver specific threshold for caption (used by rule engine) CAPTION_CONFIDENCE_THRESHOLD = 0.20 # driver specific threshold for OCR (used by rule engine) ...
9977958
import click import os.path import odooku import odooku_addons from odooku.params import params from odooku.helpers.split import split ADDONS_PATH = os.path.abspath('addons') def resolve_comma_seperated(ctx, param, value): return split(value, ',') def resolve_addons(ctx, param, value): paths = [ ...
9978004
import os from ctypes import * # Load the multikey search library d = os.path.dirname(os.path.realpath(__file__)) par = os.path.join(d, os.pardir) lib = CDLL(os.path.join(par, "obj", "libcryptmk.so")) # Have to change directories to read the params dir that's hard-coded # in ec/ec.cc, not sure how to fix this. os.chdi...
9978010
import tensorflow as tf from external.BB2SegNet.refinement_net.network.Layer import Layer from external.BB2SegNet.refinement_net.network.Util import prepare_input, get_activation, apply_dropout, conv2d, conv2d_dilated, bootstrapped_ce_loss, \ class_balanced_ce_loss from external.BB2SegNet.refinement_net.datasets imp...
9978032
import balanced balanced.configure('<KEY>') account = balanced.Account.fetch('/accounts/<KEY>') account.settlements
9978051
import pytest from exploits.hashes.collisions import java7_hashmap from test.exploits.dummy_output import DummyOutput def test_java7_hashmap_run(): output = DummyOutput() n_collisions = 10 hash_table_size = 1024 target_hash = 848473 java7_hashmap.options['n_collisions'] = n_collisions java7_ha...
9978092
from typing import List, Any import numpy as np from PIL import Image from collections import OrderedDict import joblib import os import grpc import tensorflow as tf from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2_grpc from src.app.configurations import _Mod...
9978104
import numpy as np import pytest from psyneulink.core import llvm as pnlvm x = np.random.rand() y = np.random.rand() @pytest.mark.benchmark(group="Builtins") @pytest.mark.parametrize("op, args, builtin, result", [ (np.exp, (x,), "__pnl_builtin_exp", np.exp(x)), (np....
9978120
import os, sys, platform output = 'luarpc' cdefs = "-DLUA_CROSS_COMPILER -DLUA_RPC" # Lua source files and include path lua_files = """lapi.c lcode.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c ltm.c lundump.c lvm.c lzio.c lauxlib.c lbaselib.c ld...
9978129
import argparse import torch.nn as nn import torch.nn.functional as F from torchvision.utils import save_image import pdb import wandb import mir from data import * from utils import get_logger, get_temp_logger, logging_per_task, onehot, distillation_KL_loss, \ naive_cross_entropy_loss, get_grad_...
9978150
from __future__ import print_function import json import boto3 print('Loading function') ARCH_TO_AMI_NAME_PATTERN = { # Architecture: (pattern, owner) "PV64": ("amzn-ami-pv*.x86_64-ebs", "amazon"), "HVM64": ("amzn-ami-hvm*.x86_64-gp2", "amazon"), "HVMG2": ("amzn-ami-graphics-hvm-*x86_64-ebs*", "67959...
9978170
import argparse import os import sys from reggol.colored_formatter import ColoredFormatter from reggol.logger import CustomConsoleAndFileLogger import logging _level = None _default_logpath: str = None def set_default_loglevel(loglevel: str) -> None: """ Set the default loglevel. Should be one of the loglev...
9978178
from contextlib import contextmanager from node.blockchain.facade import BlockchainFacade from node.blockchain.models import Schedule from node.blockchain.types import NodeRole from node.core.utils.cryptography import get_node_identifier def make_node_as_role(node_identifier, node_role): next_block_number = Bloc...
9978181
import frappe import json from facility_management.utils.functools import concat_not_empty from functools import reduce @frappe.whitelist() def get(filters): filters = json.loads(filters) labels = _get_labels() datasets = _get_datasets(filters) return { 'labels': labels, 'datasets': da...
9978182
import unittest import numpy as np import chainer from chainer.backends import cuda from chainer import testing from chainer.testing import attr from chainercv.links.model.faster_rcnn import ProposalCreator from chainercv.utils import generate_random_bbox @testing.parameterize( {'train': True}, {'train': F...
9978290
from typing import Union import numba import numpy from gensim.models.basemodel import BaseTopicModel from spec2vec.Document import Document def calc_vector(model: BaseTopicModel, document: Document, intensity_weighting_power: Union[float, int] = 0, allowed_missing_percentage: Union[fl...
9978298
from __future__ import print_function import math from collections import Counter import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.nn import Parameter from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence from collections import defaultdict from ....
9978328
import os import torch import imageio import numpy as np from tqdm import tqdm from config import parse_args from models import make_mlp_model from losses import img_mse, img_psnr from datasets import SingleImage from torch.utils.tensorboard import SummaryWriter def downsample(input, factor=1): if factor...
9978351
from base.torchnlp_dataset import TorchnlpDataset from torchnlp.datasets.dataset import Dataset from torchnlp.encoders.text import SpacyEncoder from torchnlp.utils import datasets_iterator from torchnlp.encoders.text.default_reserved_tokens import DEFAULT_SOS_TOKEN from torch.utils.data import Subset from nltk.corpus i...
9978379
def df_add_scorecol(data, metric, win_threshold=.66, lose_threshold=.33, win_points=2, lose_points=-2, tie_points=0, score_col_name='score'): '''Adds an arbitrary score based ...
9978436
from abc import ABC from typing import Dict from torch.utils.data import Dataset as TorchDataset class Dataset(ABC): def __init__(self, data_type: str): assert data_type in ["RGB", "features"] self.data_type = data_type def class_count(self) -> int: raise NotImplementedError() d...
9978474
from typing import List import torch from torch import Tensor from pfhedge._utils.bisect import find_implied_volatility from pfhedge._utils.doc import _set_attr_and_docstring from pfhedge._utils.doc import _set_docstring from pfhedge._utils.str import _format_float from pfhedge.nn.functional import d1 as compute_d1 f...
9978492
class BaseFsAccessor(object): """ Base class for accessing file systems. For example local and cloud(S3) ones. Provides the common interface to access different file systems. """ def remove_folder_recursively(self, path): raise NotImplementedError def remove_file(self, path): r...
9978500
import numpy as np from microsim.opencl.ramp.params import Params from microsim.opencl.ramp.simulator import Simulator from microsim.opencl.ramp.snapshot import Snapshot from microsim.opencl.ramp.disease_statuses import DiseaseStatus sentinel_value = (1 << 31) - 1 fixed_factor = 8388608.0 nplaces = 8 npeopl...
9978503
import yaml import logging from tqdm import tqdm def read_yaml(file_path): f = open(file_path, 'r', encoding='utf-8') cont = f.read() return yaml.load(cont)
9978522
import _init_paths from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list from datasets.factory import get_imdb import caffe import argparse import pprint import time, os, sys import numpy as np import h5py import cv2 from fast_rcnn.config import cfg, get_output_dir from fast_rcnn.bbox_transform import clip_bo...
9978534
def get_callback(progress): from keras.callbacks import Callback import numpy as np import logging import time logger = logging.getLogger(name=__name__) class PiperProgressReporter(Callback): def __init__(self, progress): super(PiperProgressReporter, self).__init__() ...
9978547
import json from http import HTTPStatus import pytest from app import app class TestDispatchRequestGeneral: def test_404(self, apigw_event) -> None: apigw_event['requestContext']['resourcePath'] = '/NOT_IMPLEMENTED_PATH' response = app.dispatch_request(apigw_event, {}) assert response['s...
9978551
from types import GeneratorType import pytest import deezer pytestmark = pytest.mark.vcr class TestResource: def test_resource_relation(self, client): """Test passing parent object when using get_relation.""" album = client.get_album(302127) tracks = album.get_tracks() assert tr...
9978584
import numpy as np from numpy import linalg as la import logging from typing import Callable, List, Tuple, Dict def random_sample(bounds: np.ndarray, k: int) -> np.ndarray: """ Generate a set of k n-dimensional points sampled uniformly at random :param bounds: n x 2 dimenional array containing upper/lower ...
9978593
import functools import pytest from gerrychain import MarkovChain, Partition, proposals from gerrychain.accept import always_accept from gerrychain.constraints import (no_vanishing_districts, single_flip_contiguous) from gerrychain.grid import Grid from gerrychain.updaters import c...
9978629
import threading from pysnmp.entity.rfc3413.oneliner import cmdgen from icssploit import ( exploits, wordlists, print_status, print_error, LockedIterator, print_success, print_table, boolify, multi, validators ) class Exploit(exploits.Exploit): """ Module performs brut...
9978653
import sys import subprocess import optparse from process_whole_archive_option import ProcessWholeArchiveOption def get_leaks_suppressions(cmd): supp, newcmd = [], [] for arg in cmd: if arg.endswith(".supp"): supp.append(arg) else: newcmd.append(arg) return supp, n...
9978656
try: import rate_NR import rate_genNR import rate_UV import dmdd_efficiencies as eff except ImportError: pass import os,os.path,shutil import pickle import logging import time on_rtd = False try: import numpy.random as random import numpy as np from scipy.stats import poisson ...
9978688
import argparse import pandas import seaborn as sns import matplotlib.pyplot as plt from rlutil.logging import log_processor import scripts.plot_utils as plot_utils def filter_fn(params): if params['target_mode'] == 'q*': return False if params['weight_states_only'] == False: return False ...
9978723
from setuptools import setup setup(name='redbull', version='0.81', packages=['redbull'], python_requires=">=3.6", zip_safe=False)
9978746
def test(): assert ( "list(doc.ents) + [span]" in __solution__ ), "Você adicionou a partição a doc.ents?" assert ( "span_root_head = span.root.head" in __solution__ ), "Você está selecionando o 'head' do token raiz da partição?" assert ( "print(span_root_head.text" in __solut...
9978782
import psycopg2 from galvanalyser.database import Row class RangeLabelRow(Row): def __init__( self, dataset_id, label_name, lower_bound, upper_bound, info=None, id_=None, ): self.id = id_ self.dataset_id = dataset_id self.label_na...
9978787
from typing import Optional import tensorflow as tf from transformers import ( AutoConfig, PretrainedConfig, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFPreTrainedModel, ) from common.arguments import ModelArguments from common.utils import create_config def create_model(model_...
9978790
from matplotlib.colors import to_rgb """Module with objects and methods to choose and define the color code to represent pharmacophoric features when a pharmacophore is shown. This module contains predefined color palettes to represent pharmacophoric features, as well as a method to extract color codes from these pale...
9978810
from fusionauth.fusionauth_client import FusionAuthClient # You must supply your API key and URL here client = FusionAuthClient('api-key', 'http://localhost:9011') user_request = { 'sendSetPasswordEmail': False, 'skipVerification': True, 'user': { 'email': '<EMAIL>', 'password': 'passwor...
9978814
from .flatwrapper import FlatWrapper class CallFlatWrapper(FlatWrapper): def flatten_children(self): self.flattened_children.extend(self.original_node.args) self.flattened_children.append(self.extract_receiver_node()) def transform_node(self): twin = self.original_node.twin ne...
9978827
from ..common.alignment_type import AlignmentType from ..common.from_to import FromTo from ..gfa1.to_gfa2 import ToGFA2 as GFA1_ToGFA2 from ..gfa1.references import References as GFA1_References from ..gfa1.oriented_segments import OrientedSegments from ..gfa1.alignment_type import AlignmentType as GFA1_AlignmentType f...
9978830
import pytest import unyt as u from unyt.testing import assert_allclose_units import gmso from gmso.core.box import Box from gmso.formats.lammpsdata import read_lammpsdata, write_lammpsdata from gmso.tests.base_test import BaseTest from gmso.tests.utils import get_path class TestLammpsWriter(BaseTest): @pytest.m...
9978877
import os from django.test import TestCase from django.test import Client from django.contrib.auth import get_user_model from django.urls import reverse BASE_DIR = os.path.abspath( os.path.join( os.path.dirname(__file__), ".." ) ) src_file_path = os.path.join( BASE_DIR, "data", "berlin.pdf...
9978880
import json import pytest from django.utils.encoding import force_text try: from wagtail.core.fields import StreamField except ImportError: from wagtail.wagtailcore.fields import StreamField from wagtail_svgmap.blocks import ImageMapBlock from wagtail_svgmap.models import ImageMap stream_field = StreamField...
9978902
from src.platform.weblogic.interfaces import WINTERFACES from requests.utils import dict_from_cookiejar from sys import stdout from log import LOG import utility import state default_credentials = [('weblogic', 'weblogic'), ('weblogic', 'weblogic1') ] def _auth(usr, pswd,...
9978918
import pandas.util.testing as tm class BaseExtensionTests(object): assert_series_equal = staticmethod(tm.assert_series_equal) assert_frame_equal = staticmethod(tm.assert_frame_equal) assert_extension_array_equal = staticmethod( tm.assert_extension_array_equal )
9978947
from bs4 import BeautifulSoup import time import asyncio import aiohttp from helper.asyncioPoliciesFix import decorator_asyncio_fix import re from helper.html_scraper import Scraper class Zooqle: def __init__(self): self.BASE_URL = 'https://zooqle.com' self.LIMIT = None def _parser(self, htm...
9979003
from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms...
9979018
import numpy as np import torch from .quant_layer import QuantModule, lp_loss from .quant_model import QuantModel from .quant_block import BaseQuantBlock from .adaptive_rounding import AdaRoundQuantizer from .set_weight_quantize_params import get_init, weight_get_quant_state from .set_act_quantize_params import set_act...
9979033
from __future__ import with_statement from PyObjCTools.TestSupport import * from Quartz import * import Quartz import os import sys try: long except NameError: long = int if sys.version_info[0] != 2: def buffer(value): if isinstance(value, bytes): return value return value.enc...
9979038
import click from esque.cli.autocomplete import list_consumergroups, list_contexts, list_topics from esque.cli.helpers import ensure_approval from esque.cli.options import State, default_options from esque.cli.output import blue_bold, green_bold from esque.cluster import Cluster from esque.config import ESQUE_GROUP_ID...
9979096
from __future__ import division, absolute_import import numpy as np import numpy.linalg as la class ShapeDescriptor(object): """Class that calculates rotation-invariant shape descriptors based on the radius of gyration tensor. """ def __init__(self, coor): coor = np.asmatrix(coor) # ...
9979133
from django.urls import path, include from rest_framework.authtoken.views import obtain_auth_token from .views import * app_name = "airport_app" urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/token/', obtain_auth_token, name='token'), path('flights/', FlightsView.as_view()), path('flights/<in...
9979142
from setuptools import find_packages, setup setup( name='qpth', version='0.0.15', description="A fast and differentiable QP solver for PyTorch.", author='<NAME>', author_email='<EMAIL>', platforms=['any'], license="Apache 2.0", url='https://github.com/locuslab/qpth', packages=find_p...
9979171
from pytest import mark from scanapi.tree import EndpointNode @mark.describe("endpoint node") @mark.describe("headers") class TestHeaders: @mark.context("when parent spec has no headers attribute defined") @mark.it("should set headers attribute the same as the node's one") def test_when_parent_has_no_hea...
9979195
import numpy as np import torch from matplotlib import pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error torch.manual_seed(7) # Load the dataset D_numpy = np.load("D.npy")[:, 0, :] # We only have one SOAP...
9979203
from collections.abc import Iterable from datetime import datetime import six from ...exceptions import ImproperlyConfigured arrow = None try: import arrow except ImportError: pass class ArrowDateTime(object): def __init__(self): if not arrow: raise ImproperlyConfigured( ...
9979225
import cv2 import os import pickle from os.path import join, exists import tohand as th import argparse from tqdm import tqdm hc = [] def convert(gesture_folder, target_folder): rP = os.getcwd() mData = os.path.abspath(target_folder) if not exists(mData): os.makedirs(mData) gesture_folder =...
9979245
import sys import os sys.path.append(os.pardir) import pytest from pytz import timezone from types import GeneratorType try: from minette.tagger.mecabtagger import MeCabTagger, MeCabNode except Exception: # Skip if import dependencies not found pytestmark = pytest.mark.skip def test_init(): tagger = ...
9979259
from toolz import partition_all def compute_date_range_chunks(sessions, start_date, end_date, chunksize): """Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the p...
9979268
import caffe import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--network', type=str, required=True,help="The network prototxt") parser.add_argument('--caffemodel', type=str, required=True, help="The caffemodel of the network") args = parser.par...
9979274
import os import json import gzip import random import itertools import argparse import transcripts def dump(by_group, splits, subset_name, gz = True): for split_name, transcript in by_group.items(): input_path = os.path.join(splits, f'{subset_name}_{split_name}.json') + ('.gz' if gz else '') with (gzip.open(in...
9979289
import pandas as pd from reamber.bms import BMSHit from tests.test.bms.test_fixture import bms_map def test_type(bms_map): assert isinstance(bms_map.hits[0], BMSHit) def test_from_series(): hit = BMSHit.from_series(pd.Series(dict(offset=1000, column=1, sample=b'0'))) assert BMSHit(1000, 1, b'0') == hit ...
9979293
from parsimonious import nodes from soap.semantics import cast, ErrorSemantics _lift_child = nodes.NodeVisitor.lift_child _lift_first = lambda self, node, children: children[0] _lift_second = lambda self, node, children: children[1] _lift_children = lambda self, node, children: children _lift_text = lambda self, nod...
9979306
import pytest from typing import Tuple import flair.datasets from flair.data import Dictionary, Corpus from flair.embeddings import WordEmbeddings, DocumentRNNEmbeddings from flair.models.text_regression_model import TextRegressor # from flair.trainers.trainer_regression import RegressorTrainer from flair.trainers imp...
9979319
import os import yaml from warnings import warn from copy import deepcopy class Parameters: """ Global parameters module Parameters are used in many procedures, and are often defined only in the parameters.yml file ONLY Parameters are organized in the following groups: * assignment * distrib...
9979321
from dataflow.nerd.load_blender import load_blender_data from dataflow.nerd.load_nerf_blender import load_blender_data as load_nerf_blender_data from dataflow.nerd.load_real_world import load_llff_data from dataflow.nerd.dataflow import add_args, create_dataflow
9979330
from abc import ABC, abstractmethod import numpy as np from PIL import ImageOps import logging log = logging.getLogger(__name__) class AbstractPoseModel(ABC): """ Abstract class for pose estimation models. """ def __init__(self, tfengine): """Initialize posenet-base class...
9979336
import os import json import datetime import numpy as np import glob import framework.configbase def gen_common_pathcfg(path_cfg_file, is_train=False): path_cfg = framework.configbase.PathCfg() path_cfg.load(json.load(open(path_cfg_file))) output_dir = path_cfg.output_dir path_cfg.log_dir = os.path.join(ou...
9979352
import Distance as di import numpy as np from scipy.spatial.distance import pdist if __name__ == "__main__": dis=di.Distance() a=np.array([1.5 for i in range(128)]) b=np.array([2 for i in range(128)]) s=np.array([0.27 for i in range(128)]) print("使用本库的计算结果: ") print("欧氏距离 = ", dis...
9979357
from px_cookie import PxCookie def verify(ctx, config): """ main verification function, verifying the content of the perimeterx original token risk if exists :param pxContext ctx: perimeterx request context object :param PxConfig config: global configurations :return bool: Returns True if verifica...
9979405
from collections import namedtuple import torch from common.trainer import to_cuda @torch.no_grad() def do_validation(net, val_loader, metrics, label_index_in_batch): net.eval() metrics.reset() for nbatch, batch in enumerate(val_loader): batch = to_cuda(batch) outputs, _ = net(*batch) ...
9979406
import argparse parser = argparse.ArgumentParser(description="""Generate tcrdist database files for the tcrdist_cpp code. Only necessary to re-run if the supported organisms change or new genes are added to the tcrdist database in <path_to_conga>/conga/tcrdist/db/combo_xcr.tsv""") #type is str by default parser.add_a...
9979455
def validate_split_durations(train_dur, val_dur, test_dur, dataset_dur): """helper function to validate durations specified for splits, so other functions can do the actual splitting. First the functions checks for invalid conditions: + If train_dur, val_dur, and test_dur are all None, a ValueError...
9979474
from lona.html import ( TextInput, TextArea, Button, Table, Span, HTML, Div, Ul, Tr, Td, Li, H1, P, A, ) from lona import LonaView, LonaApp app = LonaApp(__file__) @app.route('/') class ChooseRoom(LonaView): def handle_request(self, request): # find...
9979503
from django.core.management import BaseCommand, CommandError from events.models import Keyword, Place from events.utils import recache_n_events_in_locations, recache_n_events class Command(BaseCommand): help = "Update keyword and place event numbers" def add_arguments(self, parser): parser.add_argum...
9979507
import torch.nn as nn from network.common.layers import Conv2D_BN class ResidualBlock(nn.Module): def __init__(self, in_channels, activation, out_channels, kernel_size, stride, padding = 'same', groups = 1, dilation=1, bias = True): super().__init__() self.conv2d_bn_1 = Conv2D_BN(in_channels, activ...
9979525
import torch.nn as nn from models.spectral import SpectralNorm as SpectralNormalization from misc.blocks import ResidualBlock from misc.utils import PRINT from torch.nn import init def get_SN(bool): if bool: return SpectralNormalization else: return lambda x: x def print_debug(feed, layers, ...
9979530
import django.dispatch page_preedit = django.dispatch.Signal(providing_args=["page"]) page_saved = django.dispatch.Signal(providing_args=["raw", "author", "message"]) page_moved = django.dispatch.Signal(providing_args=["page", "old_path", "author", "message"])
9979533
from collections import defaultdict import sys from SPARQLWrapper import SPARQLWrapper, JSON from csv import reader import pandas as pd import sqlite3 class TripleReader: def __init__(self, triples_file): self.baseuripred = "http://www.wikidata.org/prop/direct/" self.baseuriobj = "http://www.wiki...
9979569
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from openrecipes.items import RecipeItem, RecipeItemLoader class SteamykitchenMixin(object): """ Using this as a mixin lets us reuse the parse_it...
9979576
import gym import time import unittest import ray from ray.rllib.evaluation.rollout_worker import RolloutWorker from ray.rllib.evaluation.tests.test_rollout_worker import MockPolicy class TestPerf(unittest.TestCase): @classmethod def setUpClass(cls): ray.init(num_cpus=5) @classmethod def tea...
9979617
import os from requests.exceptions import RequestException import pytest from unittest.mock import create_autospec, Mock from pyquil.api import WavefunctionSimulator, ForestConnection, QVMConnection, get_benchmarker from pyquil.api._errors import UnknownApiError from pyquil.paulis import sX from pyquil import Program...
9979619
src = Split(''' ota_transport.c ''') component = aos_component('fota_mqtt_transport', src) include_tmp = Split(''' .. ../.. ../../../mqtt/sdk-impl ../../../mqtt/platform ''') for i in include_tmp: component.add_global_includes(i)
9979639
import numpy as np def dict_bgr2rgb(colordict): rgb = dict() keys = colordict.keys() for k in keys: rgb[k] = colordict[k][::-1] return rgb def dict2array(colordict): keys = colordict.keys() colorarray = np.zeros((len(keys), 3)) for ids, k in enumerate(keys): colorarray[i...
9979694
import cv2 face_cascade=cv2.CascadeClassifier("faces.xml") ds_factor=0.6 class VideoCamera(object): def __init__(self): #capturing video self.video = cv2.VideoCapture(0) def __del__(self): #releasing camera self.video.release() def get_frame(self): #ex...
9979754
from .. import util importlib = util.import_importlib('importlib') machinery = util.import_importlib('importlib.machinery') import errno import os import sys import tempfile from types import ModuleType import unittest import warnings import zipimport class FinderTests: """Tests for PathFinder.""" def tes...
9979759
import click from virl.api import VIRLServer from virl.cli.views import flavor_list_table @click.command() @click.option('--flavor', default=None) def ls(**kwargs): """ list all flavors or the details of a specific flavor """ flavor = kwargs.get('flavor') server = VIRLServer(port=80) # Regar...
9979799
from django.contrib.admin.models import CHANGE from django.utils.translation import ugettext as _ from .modelform import ModelFormMixin from .object import ObjectMixin class ObjectFormMixin(ObjectMixin, ModelFormMixin): """Custom form view mixin on an object.""" log_action_flag = CHANGE def get_form_val...
9979824
import itertools from decimal import Decimal as D from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.conf import settings from pecomsdk import pecom from ...