id
stringlengths
3
8
content
stringlengths
100
981k
140190
from subprocess import Popen from subprocess import PIPE, STDOUT from scripts.os_check import ADB, SUC, SEP print("Removing lockscreen ...") Popen([ADB, 'shell', SUC, 'rm', '/data/system/*.key'], stdout=PIPE, stderr=STDOUT).stdout.read().decode('UTF-8') Popen([ADB, 'shell', SUC, 'rm', '/data/system/locksetting...
140206
from django.contrib import messages from django.db import IntegrityError from django.shortcuts import redirect from .models import Subscriber from .tasks import async_send_newsletter def subscribe(request): if request.method == 'POST': email = request.POST.get('email') subscriber = Sub...
140214
from django.urls import path from .schema import schema from .views import AsyncGraphQLView urlpatterns = [path("graphql", AsyncGraphQLView.as_view(schema=schema))]
140216
from fints2ledger.transaction_retriever import TRetriever from fints.client import FinTS3PinTanClient from fints2ledger.csv_converter import CsvConverter from mt940.models import Date class Fints2Csv: def __init__(self, config): self.config = config def retrieveAndSave(self): client = FinTS3P...
140232
import time import numpy as np import tensorflow as tf import awesome_gans.image_utils as iu import awesome_gans.segan.segan_model as segan from awesome_gans.datasets import MNISTDataSet results = {'output': './gen_img/', 'checkpoint': './model/checkpoint', 'model': './model/SEGAN-model.ckpt'} train_step = { 'g...
140243
N_ITER_CHEAP = 10 N_ITER_EXACT = 50 EM_ITER_CHEAP = 1 DEFAULT_LAMBDA = (.1, .001) MAX_CLD_SIZE = 150 MAX_TRAJ_LEN = 100 EXACT_LAMBDA = (10, .001) DATA_DIM = 3 #DS_SIZE = 0.03 # for fig8 DS_SIZE = 0.025 # for overhand N_STREAMS = 10 DEFAULT_...
140244
def policy_threshold(threshold, belief, loc): """ chooses whether to switch side based on whether the belief on the current site drops below the threshold Args: threshold (float): the threshold of belief on the current site, when the belief is lower than the threshold, switch si...
140261
from enum import Enum from .fileEntryData import FileEntryData class eFileTypes(Enum): NOTHING = 0 MY_FOLDER = 1 PUBLIC = 2 COMPANY = 3 MODELS_PATH = 4 SHARED_WITH_ME = 5 class FileEntry(object): def __init__(self, show=True, text="", type=eFileTypes.NOTHING, data=FileEntryData()): ...
140270
import os import time import unittest from numpy.testing import assert_almost_equal from supervised.tuner.time_controller import TimeController class TimeControllerTest(unittest.TestCase): def test_to_and_from_json(self): tc = TimeController( start_time=time.time(), total_time_lim...
140313
description = 'minimal NICOS startup setup' group = 'lowlevel' sysconfig = dict( cache = 'tofhw.toftof.frm2:14869', )
140359
import numpy as np import json # with open("pattern.json", "r") as fh: # patterns = json.load(fh) class Pat_Match(object): def __init__(self, config, label_to_id, filt=None): self.config = config self.label_to_id = label_to_id self.patterns = config.patterns if filt is not No...
140363
import collections import dominoes import unittest class TestSeries(unittest.TestCase): def test_init(self): s1 = dominoes.Series() self.assertEqual(len(s1.games), 1) self.assertEqual(len(s1.games[0].board), 1) self.assertEqual(s1.games[0].board.left_end(), 6) self.assertEq...
140365
import os from typing import NamedTuple, Sequence import subprocess class UnoOfficePaths(NamedTuple): uno_path: str uno_python_path: str class EnvironmentVariables: UNO_PATH = 'UNO_PATH' UNO_PYTHON_PATH = 'UNO_PYTHON_PATH' UNO_OFFICE_BINARY_PATH = 'UNO_OFFICE_BINARY_PATH' class DefaultValues:...
140395
from mjcf import elements as e def main(): ######################### # Level 1 mujoco = e.Mujoco( model="tendon" ) ######################### # Level 2 compiler = e.Compiler( coordinate="global", ) default = e.Default() visual = e.Visual() worldbody = e.Worl...
140460
import numpy as np import teaserpp_python from Config import Config import gtsam as gt from gtsam import (Cal3_S2, GenericProjectionFactorCal3_S2, NonlinearFactorGraph, NonlinearISAM, Pose3, PriorFactorPoint3, PriorFactorPose3, Rot3, PinholeCameraCal3_S2, Values,...
140499
from __future__ import print_function import torch import torch.utils.data as data import torchvision from torchvision import transforms import random import os import numpy as np from PIL import Image class Base_Dataset(data.Dataset): def __init__(self, root, partition, target_ratio=0.0): super(Base_Datas...
140532
import os import json import requests import networkx as nx from urllib import parse from itertools import chain from multiprocessing import Pool def link_to_title(link): return link["title"] def clean_if_key(page, key): if key in page.keys(): return map(link_to_title, page[key]) else: r...
140547
import asyncio import mqttools async def subscriber(): client = mqttools.Client('localhost', 1883) await client.start() # Subscribe to two topics in parallel. await asyncio.gather( client.subscribe('$SYS/#'), client.subscribe('/test/mqttools/foo') ) print('Waiting for messa...
140553
from django import forms from apps.Testings.models import Phase from .models import Argument, Source, Command from django.utils.safestring import mark_safe class ArgumentForm(forms.ModelForm): class Meta: model = Argument fields = '__all__' widgets = { 'command' : forms.HiddenI...
140555
import argparse import torch from stereo import MinSumStereo, BlockMatchStereo, RefinedMinSumStereo import data import imageio import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser() parser.add_argument('--im0', action='store', required=True, type=str) parser.add_argument('--im1', acti...
140560
from test.functional.test_framework import BitcoinTestFramework class TestCaseBase(BitcoinTestFramework) : def set_test_params(self) : pass def run_test(self) : key_list = dir(self) for name in key_list : if name.startswith("initialize") : print('In...
140570
import re from ja_timex.extract_filter import DecimalFilter, NumexpFilter, PartialNumFilter from ja_timex.pattern.place import Pattern from ja_timex.tag import Extract def make_extract(target, original, type_name="abstime"): return Extract( type_name=type_name, re_match=re.search(target, original...
140574
from __future__ import absolute_import import collections from huskar_sdk_v2.consts import OVERALL from huskar_api import settings from huskar_api.models.const import ROUTE_DEFAULT_INTENT RouteKey = collections.namedtuple('RouteKey', 'application_name intent') def make_route_key(application_name, intent=None): ...
140580
expected_output = { "Mgmt-intf": { "address_family": { "ipv4 unicast": { "flags": "0x0", "table_id": "0x1", "vrf_label": {"allocation_mode": "per-prefix"}, } }, "cli_format": "New", "flags": "0x1808", "in...
140601
from .model import VLG ARCHITECTURES = {"VLG": VLG} def build_model(cfg): return ARCHITECTURES[cfg.MODEL.ARCHITECTURE](cfg)
140640
import copy import logging from datetime import datetime from http.client import IncompleteRead from typing import Dict import pika from requests.exceptions import (ConnectionError as ReqConnectionError, ReadTimeout, ChunkedEncodingError, MissingSchema,...
140661
from html.parser import HTMLParser from urllib import request import os.path import re import json import sys class ImgListScraper( HTMLParser ): IMG_URL = "http://i.imgur.com/{hash}{ext}" def __init__( self, *args, **kwargs ): super().__init__( *args, **kwargs ) self.in_javascript = False ...
140693
from abc import ABCMeta, abstractmethod from tgt_grease.core import Logging, GreaseContainer from datetime import datetime import sys import os import traceback class Command(object): """Abstract class for commands in GREASE Attributes: __metaclass__ (ABCMeta): Metadata class object purpose (...
140721
import torch import torch.onnx from models.slim import Slim x = torch.randn(1, 3, 160, 160) model = Slim() model.load_state_dict(torch.load("../pretrained_weights/slim_160_latest.pth", map_location="cpu")) model.eval() torch.onnx.export(model, x, "../pretrained_weights/slim_160_latest.onnx", input_names=["input1"], ou...
140742
import sys from set_up import Setup from estimator import CommonEstimator import json import h5py #from utils import get_memory_usage import numpy as np SEED = 12939 #from random.org np.random.seed(SEED) print('python main.py fpType fpSize estimators.json dataset') fpType = sys.argv[1] fpSize = int(sys.argv[2]) tr...
140766
from six.moves.urllib.parse import quote_plus from . import get_cookies def setup_session(openid, password, username=None, check_url=None, session=None, verify=False): """ A special call to get_cookies.setup_session that is tailored for ESGF credentials. username s...
140812
import json from telethon import events, Button from asyncio import exceptions from .. import jdbot, chat_id, BOT_SET_JSON_FILE_USER, BOT_SET, ch_name from .utils import split_list, logger, press_event @jdbot.on(events.NewMessage(from_users=chat_id, pattern='^/set$')) async def bot_set(event): SENDER = event.send...
140821
import json import numpy as np import os from photogrammetry_importer.types.camera import Camera from photogrammetry_importer.types.point import Point from photogrammetry_importer.file_handlers.utility import ( check_radial_distortion, ) from photogrammetry_importer.blender_utility.logging_utility import log_repor...
140826
from pymtl3 import * class RegisterFile( Component ): def construct( s, Type, nregs=32, rd_ports=1, wr_ports=1, const_zero=False ): addr_type = mk_bits( max( 1, clog2( nregs ) ) ) s.raddr = [ InPort( addr_type ) for i in range( rd_ports ) ] s.rdata = [ OutPort( Type ) for i in range( ...
140832
from typing import List, Dict import numpy as np import torch from tqdm import tqdm from utils.fov_expansion import Expander from inversion.video.video_config import VideoConfig from utils.common import tensor2im, get_identity_transform def postprocess_and_smooth_inversions(results: Dict, net, opts: VideoConfig): ...
140863
import FWCore.ParameterSet.Config as cms #Tracks without extra and hits #AOD content RecoTrackerAOD = cms.PSet( outputCommands = cms.untracked.vstring( 'keep recoTracks_ctfWithMaterialTracksP5_*_*', 'keep recoTracks_ctfWithMaterialTracksP5LHCNavigation_*_*', 'keep recoTracks_rsWithMaterialTracksP5...
140890
from django.conf import settings from mapentity.registry import registry from . import models app_name = 'maintenance' urlpatterns = registry.register(models.Intervention, menu=settings.INTERVENTION_MODEL_ENABLED) urlpatterns += registry.register(models.Project, menu=settings.PROJECT_MODEL_ENABLED)
140901
import logging from urllib.parse import urlparse from dbas.database import DBDiscussionSession from dbas.database.discussion_model import StatementReference, User, Statement, Issue from dbas.input_validator import is_integer from dbas.lib import get_profile_picture, get_enabled_arguments_as_query, \ get_enabled_pr...
140911
import torch class AlphaFoldLRScheduler(torch.optim.lr_scheduler._LRScheduler): """ Implements the learning rate schedule defined in the AlphaFold 2 supplement. A linear warmup is followed by a plateau at the maximum learning rate and then exponential decay. Note that the initial...
140927
import time import PyQt5.QtCore from nn_sandbox.backend.algorithms import RbfnAlgorithm from . import Bridge, BridgeProperty from .observer import Observable class RbfnBridge(Bridge): ui_refresh_interval = BridgeProperty(0.0) dataset_dict = BridgeProperty({}) training_dataset = BridgeProperty([]) te...
140947
import tempfile from pathlib import Path from typing import List import numpy as np from .lib.indexing import IndexCreate from .embed import SentenceEncoder, EncodeFile from .lib.text_processing import Token, BPEfastApply def lines_to_index(lang: str, lines: List, model_path: str, bpe_code_path: str, use_cpu: bool ...
141034
from toga_cocoa.libs import NSObject, objc_method class TogaData(NSObject): @objc_method def copyWithZone_(self): # TogaData is used as an immutable reference to a row # so the same object can be returned as a copy. self.retain() return self
141099
from typing import Optional from botocore.client import BaseClient from typing import Dict from typing import Union from botocore.paginate import Paginator from datetime import datetime from botocore.waiter import Waiter from typing import List class Client(BaseClient): def can_paginate(self, operation_name: str ...
141131
import os from abc import abstractmethod from time import sleep from typing import TYPE_CHECKING from pyramid.httpexceptions import HTTPBadGateway from weaver.formats import CONTENT_TYPE_APP_JSON from weaver.utils import get_cookie_headers, get_settings, request_extra from weaver.wps.utils import get_wps_output_dir, ...
141132
import os import cv2 import numpy as np def convert(size, box): ''' convert (xmin, ymin, xmax, ymax) to (cx/w, cy/h, bw/w, bw/h) param: size: tuple (im_width, im_height) box: list [xmin, ymin, xmax, ymax] return: tuple (cx/w, cy/h, bw/w, bw/h) ''' dw = 1. / size[0] d...
141152
import torch def reference_orgqr(v, tau, checks=True): """ Unoptimized differentiable implementation of ORGQR. Memory consumption linear in matrix rank. Intended for use only within the test suite. """ if checks: assert torch.is_tensor(v) and torch.is_tensor(tau) assert v.dim()...
141167
import hooks import logging from rpc.jsonrpc import Dsuccess, Derror log = logging.getLogger('social.network') from util import try_this, Storage from common import AccountBase, profile, UpdateMixin, FromNetMixin, pref class SocialNetwork(UpdateMixin, AccountBase, FromNetMixin): filters = {} header_...
141173
import boto3 import pandas as pd import numpy as np # user analysis def get_user_log(): s3 = boto3.resource('s3', region_name='us-east-2') bucket = s3.Bucket('nlprankings') logs = pd.DataFrame(columns=['datetime','IP','startYear','endYear','num_uni','num_author','CL','TACL','ACL_C','NAACL_C','EMNLP_C', ...
141193
import tensorflow as tf import argparse def load_graph(frozen_graph_filename): # We load the protobuf file from the disk and parse it to retrieve the # unserialized graph_def with tf.gfile.GFile(frozen_graph_filename, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read())...
141207
import argparse import warnings from pytorch_lightning.models.trainer import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from test_tube import Experiment import models warnings.filterwarnings('ignore') def main(): parser = argparse.ArgumentParser() parser.add_argument('--model', choices...
141223
import numpy as np ########################## method used - "1env_1jet", or "1env_njet" ################################################## method='1env_1jet' ########################## nature of neural network - "mlp", "mlp_shared" or "cnn" ################################################## policy_name='mlp' ####...
141229
import numpy as np from sklearn.preprocessing import Imputer # Represent the unknown value by np.nan in numpy data_origin = [[30, 100], [20, 50], [35, np.nan], [25, 80], [30, 70], [40, 60]] # Imputation with the mean value imp_mean = Imputer(m...
141231
from pprint import pprint from deutschland import autobahn from deutschland.autobahn.api import default_api autobahn_api_instance = default_api.DefaultApi() try: # Auflistung aller Autobahnen api_response = autobahn_api_instance.list_autobahnen() pprint(api_response) # Details zu einer Ladestation ...
141233
import torch from manopth.demo import generate_random_hand def test_generate_random_hand(): batch_size = 3 hand_info = generate_random_hand(batch_size=batch_size, ncomps=6) verts = hand_info['verts'] joints = hand_info['joints'] assert verts.shape == (batch_size, 778, 3) assert joints.shape =...
141247
add_library('opencv_processing') src = loadImage("test.jpg") size(src.width, src.height, P2D) opencv = OpenCV(this, src) opencv.findCannyEdges(20, 75) canny = opencv.getSnapshot() opencv.loadImage(src) opencv.findScharrEdges(OpenCV.HORIZONTAL) scharr = opencv.getSnapshot() opencv.loadImage(src) opencv.findSobelEdge...
141279
mx = 0 for i in xrange(1, 100): j = 1 while True: num = i * j s = str(num) if s.count('1') + s.count('0') == len(s): mx = max(mx, j) break j += 1 print mx
141297
import inspect import os from pathlib import Path from typing import Any, Dict, List, cast import schema_salad.metaschema as cg_metaschema from schema_salad import codegen from schema_salad.avro.schema import Names from schema_salad.schema import load_schema from .test_java_codegen import cwl_file_uri, metaschema_fil...
141319
import numpy as np import tensorflow as tf import scipy import lib_gcnn.graph as graph class GraphCNN(object): """ A graph CNN for text classification. Composed of graph convolutional + max-pooling layer(s) and a softmax layer. filter_name = Filter name (i.e. "chebyshev", "spline", "fourier") L...
141342
import unittest import pandas as pd from osu.local.beatmap.beatmapIO import BeatmapIO from analysis.osu.std.map_data import StdMapData class TestStdMapData(unittest.TestCase): @classmethod def setUpClass(cls): cls.beatmap = BeatmapIO.open_beatmap('unit_tests\\maps\\osu\\test\\abraker - unknown (abr...
141361
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from sklearn.decomposition import FastICA from ..utils.parallel import ParallelBackend, get_backend from ..utils.kde import kde from ..utils.cubic import cubic_spline from ..utils.sobol import multivariate_normal from ..utils.random import ...
141371
from __future__ import absolute_import from __future__ import division # ** This is the file quisk_conf_defaults.py which contains defaults for Quisk. ** # # Please do not change this configuration file quisk_conf_defaults.py. # Instead copy one of the other quisk_conf_*.py files to your own # configuration file and...
141373
import threading from data import config import method from script.x_developer import developer_tools class interface(threading.Thread): scriptLibrary = None; developerTools = None; SCA = [ "ONLINE", "OFFLINE", ]; TERMINAL_COMMAND = [ "sca.exit", ...
141390
from dataclasses import dataclass from typing import Any, Literal, Optional from aiohttp import ClientSession @dataclass class Response: status: int body: Any class Request: def __init__(self, client_session: Optional[ClientSession] = None) -> None: self.client_session = client_session asy...
141437
from pathlib import Path import abc import logging import io import importlib import time from _collections import OrderedDict import traceback import pandas as pd import numpy as np import shutil from graphviz import Digraph from ibllib.misc import version import one.params from one.alf.files import add_uuid_string ...
141446
from odoo import fields, models class Tag(models.Model): _name = 'todo.task.tag' _description = 'To-do Tag' name = fields.Char('Name', translate=True) # Many2many inverse relationship task_ids = fields.Many2many( 'todo.task', string='Tasks') # Hierarchic relationships: _...
141471
from streamlink.plugins.ard_mediathek import ARDMediathek from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlARDMediathek(PluginCanHandleUrl): __plugin__ = ARDMediathek should_match = [ 'http://mediathek.daserste.de/live', 'http://www.ardmediathek.de/tv/Sportschau/' ...
141504
import unittest from orderbook.src.common.order import Order from orderbook.src.common.priceTree import PriceTree from orderbook.src.common.ptreeIterator import ComplexIterator class TestPriceTree(unittest.TestCase): def test_PriceTreeInsert(self): num_elements = 5 price_tree = TestPriceTree.pop...
141532
import functools import statistics # 3.8 新版功能. # 将一个类方法转换为特征属性,一次性计算该特征属性的值,然后将其缓存为实例生命周期内的普通属性。 类似于 property() 但增加了缓存功能。 # class DataSet: # def __init__(self, sequence_of_numbers): # self._data = sequence_of_numbers # # @functools.cached_property # def stdev(self): # return statistics.stde...
141542
import math import os import re import numpy as np from BluPrintTriboSys import TriboSys from Constants import PltOpts, SubDir, TexTempl, UnitTex, Unit, PrintOpts, \ PreSol from cartesian_plot_functions import plt_profile, plt_contact, plt_3d, \ plt_2d_scatt_line, \ plt_energy_ring_on_ring, plt...
141567
import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) import re import dateparser try: from local_extractor.utils import common_utils from local_extractor.utils.table_concatenation import concatenate_tables except ImportError: import sys, os, pathlib path = pathlib.Path(__file__).absolute().p...
141624
from typing import Dict import numpy as np from gym import spaces from stable_baselines3.common.vec_env import VecEnv, VecEnvWrapper class ObsDictWrapper(VecEnvWrapper): """ Wrapper for a VecEnv which overrides the observation space for Hindsight Experience Replay to support dict observations. :param e...
141649
import time import sys import board import busio import digitalio from adafruit_mcp9600 import MCP9600 SENSOR_ADDR = 0X67 i2c = busio.I2C(board.SCL, board.SDA,frequency=200000) try: sensor = MCP9600(i2c,SENSOR_ADDR,"K") except ValueError as e: print(e) print("Unable to connect to the thermocouple sensor."...
141657
import time print("OwO What's This!!!") print("Here's my favorite activity in Japoneeese: プログラミング (yes google translate is good)") furry = "Rawr x3 nuzzles how are you pounces on you you're so warm o3o notices you have a bulge o: someone's happy ;) nuzzles your necky wecky~ murr~ hehehe rubbies your bulgy wolgy you're...
141723
from helium._impl import TextImpl from helium._impl.selenium_wrappers import WebDriverWrapper from tests.api import BrowserAT class TextImplTest(BrowserAT): def get_page(self): return 'test_text_impl.html' def test_empty_search_text_xpath(self): xpath = TextImpl(WebDriverWrapper(self.driver))._get_search_text_xp...
141758
from hijri_converter import helpers def test_julian_to_ordinal(): assert helpers.jdn_to_ordinal(2447977) == 726552 def test_ordinal_to_julian(): assert helpers.ordinal_to_jdn(726552) == 2447977 def test_julian_to_reduced_julian(): assert helpers.jdn_to_rjd(2456087) == 56087 def test_reduced_julian_t...
141759
import ctypes import pytest import pyradamsa import sys import unittest def test_lib_present(): assert len(pyradamsa.Radamsa.lib_path()) > 0, 'library not found' def test_lib_symbols(): lib = ctypes.CDLL(pyradamsa.Radamsa.lib_path()) assert hasattr(lib, 'init') assert hasattr(lib, 'radamsa') asser...
141762
class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ seen = [False] * len(rooms) seen[0] = True stack = [0, ] while stack: roomIdx = stack.pop() for key in rooms[roomIdx]: ...
141773
import os import argparse import time import gc # spark imports from pyspark.sql import SparkSession, Row from pyspark.sql.functions import col, lower from pyspark.ml.evaluation import RegressionEvaluator from pyspark.ml.recommendation import ALS class AlsRecommender: """ This a collaborative filtering recom...
141777
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer ecalBarrelSimHitsValidation = DQMEDAnalyzer("EcalBarrelSimHitsValidation", moduleLabelG4 = cms.string('g4SimHits'), verbose = cms.untracked.bool(False), ValidationCollection = cms.string('EcalValidInfo'), ...
141781
import fileinput import math from matplotlib import pyplot as plt import numpy as np import pandas as pd import re from scipy import interpolate # strait up linear interpolation, nothing fancy import scipy.signal as signal yaw_interp = None pitch_interp = None roll_interp = None north_interp = None east_interp = None ...
141802
import os import tempfile import subprocess import logging import uuid import time import socket import numpy as np import cclib import rdkit from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import PeriodicTable from rdkit.Chem.rdMolTransforms import GetBondLength logging.getLogger("cclib").setL...
141810
import doctest import json from django.core.management import call_command from django.contrib.auth.models import User from django.test import TestCase from django_comments_xtd.models import XtdComment from wagtail.core.models import Page import responses from .models import ( BlogPage, BlogTag, BlogPageT...
141833
import os import unittest from uavcan.dsdl import common class TestCRC16FromBytes(unittest.TestCase): def test_str(self): self.assertEqual(common.crc16_from_bytes('123456789'), 0x29B1) def test_bytes(self): self.assertEqual(common.crc16_from_bytes(b'123456789'), 0x29B1) def test_bytearra...
141843
import json from functools import wraps from django.contrib.auth import SESSION_KEY from django.contrib.messages import api, constants from django.db import models from django.utils import timezone from django.utils.functional import SimpleLazyObject def _positional(count): """ Only allows ``count`` position...
141913
from django import forms class PaymentHiddenInputsPostForm(forms.Form): def __init__(self, fields, *args, **kwargs): super().__init__(*args, **kwargs) for key in fields: self.fields[key] = forms.CharField( initial=fields[key], widget=forms.HiddenInput )
141935
import FWCore.ParameterSet.Config as cms from HLTriggerOffline.Higgs.hltHiggsValidator_cfi import * HiggsValidationSequence = cms.Sequence( hltHiggsValidator ) #HLTHiggsVal_FastSim = cms.Sequence( # recoHiggsValidationHLTFastSim_seq + # hltHiggsValidator # )
141940
from mltoolkit.mldp.steps.transformers import BaseTransformer import numpy as np from logging import getLogger import os logger_name = os.path.basename(__file__) logger = getLogger(logger_name) class RatingProp(BaseTransformer): """Computes the rating deviation property for reviews. And that each batch conta...
141947
import random import torch from torch.autograd import Variable class TensorPool(): def __init__(self, pool_size): self.pool_size = pool_size if self.pool_size > 0: self.num_imgs = 0 self.images = [] def query(self, tensors): if self.pool_size == 0: re...
141956
from random import choice from CybORG.Shared import Observation from .Monitor import Monitor from CybORG.Shared.Actions import Action from CybORG.Shared.Actions.ConcreteActions.StopProcess import StopProcess from CybORG.Simulator.Session import VelociraptorServer from CybORG.Simulator.State import State class Remove...
142013
import json __all__ = ( "QuillParseError", "Quill", ) class QuillParseError(Exception): def __init__(self, value): self.value = value def __str__(self): return "Failed to parse value(%s)" % self.value class Quill: def __init__(self, json_string): try: self.j...
142029
import pytest from certbot_dns_loopia import LoopiaAuthenticator, DnsRecord, split_domain from unittest.mock import MagicMock # This config just sets all parameters to some value. It's just to make sure # that the DNSAuthenticator constructor has all the parameters it might need class PluginConfig: verb = "certon...
142074
from django.db.backends.mysql.base import * from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper from django.contrib.gis.db.backends.mysql.creation import MySQLCreation from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection from django.contrib.gis.db.backends.mysq...
142089
import vcellapi import sys def main(argv): if (len(argv)!=5): print("usage: testapi host port clientID userid") sys.exit(1) host = argv[1] # "vcellapi.cam.uchc.edu" port = argv[2] # 8080 clientID = argv[3] # "85133f8d-26f7-4247-8356-d175399fc2e6" ...
142147
import sys import random import FormulaSolidityPort import FormulaNativePython from decimal import Decimal from decimal import getcontext getcontext().prec = 80 # 78 digits for a maximum of 2^256-1, and 2 more digits for after the decimal point def singleHopTestFixed(balance1, weight1, balance2, weight2, amount): ...
142156
import htfe as ht import pickle as pic import math import random ############################## HTFE Init ############################## cs = ht.ComputeSystem() cs.create(ht._gpu) prog = ht.ComputeProgram() if not prog.loadFromFile("htfe.cl", cs): print("Could not load program!") h = ht.HTFE() minNote = 21 #...
142169
import unittest from pathlib import Path from cif.cif_file_io import CifContainer from tests.test_utils import current_file_path class CifFileCRCTestCase(unittest.TestCase): def setUp(self) -> None: current_file_path() self.cif = CifContainer(Path('tests/examples/1979688.cif')) def test_calc...
142210
import math import random import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from memory_replay import Transition use_cuda = torch.cuda.is_available() FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor LongTensor = to...
142242
import pylab as plt import matplotlib import numpy as np import pylab as plt import matplotlib from itertools import product import numpy as np import pandas as pd import os from sklearn.metrics.pairwise import pairwise_distances from matplotlib.ticker import ScalarFormatter, FuncFormatter matplotlib.style.use('bmh')...
142287
import numpy as np import tvm from tvm.contrib import graph_runtime import topi import nnvm.symbol as sym import nnvm.compiler from nnvm.testing.config import ctx_list def helper(symbol, inputs, dtype, np_forward, np_backward=None, need_input=True, need_head_grads=True): ishapes = {} input_syms = [...
142291
import requests as rq from requests.exceptions import HTTPError from bs4 import BeautifulSoup import warnings def get_dom(url): """returns document from url as a BS DOM""" response = rq.get(url) response.raise_for_status() return BeautifulSoup(response.content, "html.parser") def _abs_link(link, bas...