id
stringlengths
3
8
content
stringlengths
100
981k
11592797
from vergeml import ModelPlugin, model, train, predict, option, VergeMLError from vergeml.display import DISPLAY import numpy as np import os import os.path import random import csv _TEMPLATE = """\ model: imagenet # Uncomment for better ml list output: # list: # columns: # - model # - status # - num-samples...
11592842
import base64 import datetime import hmac import hashlib import requests from requests.auth import AuthBase from bitcoin_arbitrage.monitor import settings from bitcoin_arbitrage.monitor.currency import CurrencyPair from bitcoin_arbitrage.monitor.exchange import Exchange, BTCAmount from bitcoin_arbitrage.monitor.log i...
11592867
import asyncio from discord.ext import commands, tasks from IreneUtility.util import u_logger as log import datetime import pytz import discord import typing from IreneUtility.Utility import Utility # noinspection PyBroadException,PyPep8 class Reminder(commands.Cog): def __init__(self, ex): self.ex: Util...
11592882
from __future__ import unicode_literals class PreindexNotFinished(Exception): """Thrown when a preindex of the database is not finished in a certain time period""" class NoHostsMatch(Exception): pass
11592895
import numpy as np import pytest from pandas.core.arrays import TimedeltaArray class TestTimedeltaArrayConstructor: def test_only_1dim_accepted(self): # GH#25282 arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]") with pytest.raises(ValueError, match="Only 1-dimensional"): ...
11592907
import numpy as np from ..constants import LEN_CONV class XSF(object): xsf_units = 'Angstrom' def __init__(self, filexsf): self.filexsf = filexsf self.title = '' self.cutoffvars = {} def write(self, system, field=None): """ Write a system object into an xsf file....
11592956
import handlers from router import any_method routes = [(any_method, "*.py", handlers.python_script_handler), ("GET", "*.asis", handlers.as_is_handler), ("GET", "*", handlers.file_handler), ]
11593021
load("@bazel_gazelle//:deps.bzl", "go_repository") def kube_state_metrics_dependencies(): go_repository( name = "com_github_kubernetes_kube_state_metrics", commit = "4c0e83b3407e489eda34c26f7794ec69856ccd76", # v1.7.2 importpath = "k8s.io/kube-state-metrics", )
11593078
import logging import threading from contextlib import closing, contextmanager from datetime import datetime from io import BytesIO import dropbox import six from dropbox import Dropbox from dropbox.exceptions import ApiError from dropbox.files import (DownloadError, FileMetadata, FolderMetadata, ...
11593084
import itertools import Image from xml.dom import minidom from xml.parsers.expat import ExpatError def clear_logo_space(array, size, filename): if filename is None: return # remove any data where logo is try: logo = Image.open(filename) logo_size = logo.size logo_array = l...
11593089
from reaver.models.sc2.policy import SC2MultiPolicy from reaver.models.sc2.fully_conv import build_fully_conv
11593090
import pyglet from pyglet.gl import * # from pyglet import clock from pyglet.window import key import pyshaders import win32gui # Window creation style = pyglet.window.Window.WINDOW_STYLE_BORDERLESS window = pyglet.window.Window(width=960, height=540, style=style, resizable=False) windo...
11593121
import os import sys from PyQt5.QtCore import QUrl, QObject from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine from UI import classres os.environ['QT_QUICK_CONTROLS_STYLE'] = "Imagine" app = QApplication(sys.argv) # Create QML engine engine = QQmlApplicationEngine() # Load th...
11593211
import click from graviteeio_cli.exeptions import GraviteeioError from graviteeio_cli.http_client.apim.api import ApiClient from graviteeio_cli.services import lint_service from graviteeio_cli.lint.types.document import DocumentType from graviteeio_cli.core.config import GraviteeioConfig @click.command(short_help="C...
11593258
from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView from django.views.generic import UpdateView from django.views.generic import DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy f...
11593274
import sys import os sys.path.append(os.getcwd()) from models.config import Config from models.resunet_conv8_vocals.modules import * import torch.utils import torch.utils.data import torch.nn.functional as F from utils.f_helper import FDomainHelper from torchlibrosa.stft import magphase import numpy as np import pytor...
11593281
from database.main import session from models.misc.levelup_stats import LevelUpStatsSchema from models.misc.level_xp_requirement import LevelXpRequirementSchema from decorators import run_once from utils.helper import parse_int @run_once def load_character_level_stats() -> dict: """ Return a dictionary holdin...
11593291
import pytest from cloudify.models_states import BlueprintUploadState from cloudify_rest_client.exceptions import CloudifyClientError from integration_tests import AgentlessTestCase from integration_tests.tests.utils import get_resource as resource from packaging.version import parse as parse_version pytestmark = p...
11593309
def bin_search(A, left, right, k): while(left<=right): mid=(left+right)//2 if A[mid]==k: return mid elif A[mid]>k: right=mid-1 else: left=mid+1 return -1 n=int(input()) arr=list(map(int, input().strip().split(' '))) x=int(input()) prin...
11593324
import click import yaml import json from ckan_cloud_operator import logs from ckan_cloud_operator.providers.ckan.db import migration as db_migration_manager from ckan_cloud_operator.providers.ckan import manager from .storage import cli as ckan_storage_cli from .deployment import cli as ckan_deployment_cli from .ins...
11593335
import re from enum import unique from pycsp3.classes.auxiliary.ptypes import auto, AbstractType, TypeXML from pycsp3.classes.main.constraints import ConstraintUnmergeable from pycsp3.classes.main.variables import Variable from pycsp3.tools.inspector import checkType from pycsp3.tools.utilities import flatten @uniqu...
11593349
import unittest, random, sys, time, re, getpass sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util import h2o_print as h2p, h2o_gbm, h2o_summ DO_PLOT = getpass.getuser()=='kevin' DO_MEDIAN = False MAX_QBINS = 1000 MULTI_PASS = 1 DO_SCIPY_COMPARE = Fals...
11593389
import base64 import io import json import os import sys from google.cloud import storage from google.cloud import vision from google.cloud.vision import types from google.cloud import firestore db = firestore.Client() from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods = [...
11593394
import time from artemis.plotting.live_plotting import LiveStream, LivePlot, LiveCanal from artemis.plotting.matplotlib_backend import MovingImagePlot, MovingPointPlot, LinePlot, ImagePlot, HistogramPlot from itertools import count from six.moves import xrange __author__ = 'peter' import numpy as np def test_streami...
11593408
import pytest from djangocities.utils.validation.html.tags import HTML_TAGS from djangocities.utils.validation.html.exceptions import UnsupportedHtmlTag class TestHtmlTagClass: def test_doctype_is_banned(self): doctype = HTML_TAGS["!doctype"] with pytest.raises(UnsupportedHtmlTag): do...
11593410
from flask import Blueprint, g, render_template, request from gitmostwanted.app import app, db from gitmostwanted.models.user import UserAttitude from gitmostwanted.models.repo import Repo repo_rating = Blueprint('repo_rating', __name__) @repo_rating.route('/', defaults={'page': 1, 'sort_by': 'wanted', 'filter_worth...
11593434
import logging from pprint import pformat from pymongo import MongoClient from pymongo.errors import OperationFailure from pymongo import monitoring from logger import get_logger from config import get_config config = get_config() logger = get_logger(__name__, log_level=("MONGODB", "LOGLEVEL")) class CommandLogger(mo...
11593444
import unittest from jnpr.jsnapy.operator import Operator from jnpr.jsnapy.notify import Notification import os import yaml from jnpr.jsnapy.check import Comparator from mock import patch, MagicMock from nose.plugins.attrib import attr @attr('unit') class TestCheck(unittest.TestCase): def setUp(self): sel...
11593447
import numpy as np __all__ = ['crossover_1point', 'crossover_2point', 'crossover_2point_bit', 'crossover_pmx', 'crossover_2point_prob'] def crossover_1point(self): Chrom, size_pop, len_chrom = self.Chrom, self.size_pop, self.len_chrom for i in range(0, size_pop, 2): n = np.random.randint(0, self.len_...
11593461
from invoke import task, run @task def release(version): """ Version should be a string like '0.4' or '1.0' """ run('git tag -s "{}"'.format(version)) run('python setup.py sdist bdist_wheel') run('twine upload -s dist/alchimia-{}*'.format(version))
11593544
import os import re import urllib import uuid from datetime import datetime from cgi import FieldStorage from ofs import get_impl from pylons import request, response from pylons.controllers.util import abort, redirect_to from pylons import config from paste.fileapp import FileApp from paste.deploy.converters import a...
11593566
import warnings import numpy as np import matplotlib.pyplot as plt import matplotlib.transforms as transforms import matplotlib.dates as mdates import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.patheffects as pe from obspy.geodetics import gps2dist_azimuth from .stack import get_peak_coord...
11593627
import os os.environ['APP_DEBUG'] = 'true' import unittest from tests.settings import SAMPLES_LIST_DIR, SAMPLES_DETAIL_DIR from tests.test_base import TestBase from gerapy_auto_extractor.classifiers.detail import is_detail, probability_of_detail class TestClassifyDetail(TestBase): def test_china_news1(self...
11593679
from abc import ABC from abc import abstractmethod from contextlib import contextmanager from typing import TYPE_CHECKING from typing import Any from typing import Dict from typing import Union import numpy as np import pandas as pd from etna.core.mixins import BaseMixin if TYPE_CHECKING: from etna.datasets impo...
11593680
import pytz from django.forms.widgets import Widget from leaflet.forms.widgets import LeafletWidget as StockLeafletWidget class TimezoneWidget(Widget): template_name = 'osmcal/partials/event_form_timezone.html' def get_context(self, *args, **kwargs): ctx = super().get_context(*args, **kwargs) ...
11593682
from __future__ import with_statement import unittest from flask import url_for from .fixtures import app, feature_setup, FEATURE_NAME, FEATURE_IS_ON, NullFlagHandler, AlwaysOnFlagHandler, AlwaysOffFlagHandler, FLAG_CONFIG class TestAddRemoveHandlers(unittest.TestCase): def setUp(self): app.config[FLAG_CONFI...
11593695
from activepapers.storage import ActivePaper import numpy as np paper = ActivePaper("internal_files.ap", "w") script = paper.create_calclet("write", """ from activepapers.contents import open with open('numbers', 'w') as f: for i in range(10): f.write(str(i)+'\\n') """) script.run() script = paper.creat...
11593706
import os import yaml from .config import TEMP_DIR from .models import AcousticModel, G2PModel, IvectorExtractor, LanguageModel from .exceptions import ArgumentError def get_available_acoustic_languages(): pretrained_dir = os.path.join(TEMP_DIR, 'pretrained_models', 'acoustic') os.makedirs(pretrained_dir, exi...
11593728
class ToolStripArrowRenderEventArgs(EventArgs): """ Provides data for the System.Windows.Forms.ToolStripRenderer.RenderArrow event. ToolStripArrowRenderEventArgs(g: Graphics,toolStripItem: ToolStripItem,arrowRectangle: Rectangle,arrowColor: Color,arrowDirection: ArrowDirection) """ def __getitem__(self...
11593784
import copy import logging import os import subprocess import tempfile from .. import util from .common import Endpoint class SSHEndpoint(Endpoint): def __init__(self, hostname, port=None, username=None, ssh_opts=None, ssh_sudo=False, **kwargs): super(SSHEndpoint, self).__init__(**kwargs...
11593802
import os, re, sys from cupcake.io import GFF from Bio import SeqIO from collections import defaultdict from bx.intervals.cluster import ClusterTree from Cogent import BioReaders """ # BLASTN 2.6.0+ # Query: Domino_testis_i0_HQ_sampled07afe|c338324/f2p10/426 # Database: /pbi/dept/secondary/siv/gconcepcion/db/ncbi/nt #...
11593806
from loggers import Actions from stopping_decision_makers.base_decision_maker import BaseDecisionMaker class FixedDepthDecisionMaker(BaseDecisionMaker): """ A concrete implementation of a decision maker. Returns True iif the depth at which a user is in a SERP is less than a predetermined value. """ ...
11593842
from typing import Optional from botocore.client import BaseClient from typing import Dict from typing import Union from botocore.paginate import Paginator from botocore.waiter import Waiter from typing import IO class Client(BaseClient): def can_paginate(self, operation_name: str = None): pass def d...
11593882
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField, SelectField from wtforms.validators import DataRequired, InputRequired class ReminderForm(FlaskForm): title = StringField('title', validators=[DataRequired()]) body = TextAreaField('body', validators=[DataRequired()]...
11593931
from operator import attrgetter class Solver: def checkvalidpuzzle(self, arr): subsquarestartingpoints = [[0, 0], [0, 3], [0, 6], [3, 0], [3, 3], [3, 6], [6, 0], [6, 3], [6, 6]] # Checking row validity of every row for row in range(9): has = set() for col in range(9...
11593940
import math import copy import numpy as np import basis.robot_math as rm import robot_sim._kinematics.jlchain_mesh as jlm import robot_sim._kinematics.jlchain_ik as jlik class JLChain(object): """ Joint Link Chain, no branches allowed Usage: 1. Inherit this class and overwrite self._initjntlnks()/self...
11593943
import sys import time import json import yaml import psycopg2 from pprint import pprint from datetime import datetime from .helper import * date_format = '%Y-%m-%dT%H:%M:%SZ' class APIListener(): """ """ def __init__(self, event, query_type, config_f, ...
11594023
from torch.optim.lr_scheduler import _LRScheduler class WarmupScheduler(_LRScheduler): def __init__(self, optimizer, iters, last_epoch=-1): self.iters = iters super(WarmupScheduler, self).__init__(optimizer, last_epoch) def get_lr(self): if self.iters > 0: lr = [base_lr *...
11594042
import kivy from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock from kivy.core.window import Window from random import randint, choice import kivent_core from kivent_core.gameworld import GameWorld from kivent_core.systems.position_systems import PositionSystem2D from kivent_core.s...
11594053
from flask import Blueprint, jsonify, request, redirect, url_for from critiquebrainz.db import users as db_users from critiquebrainz.db.user import User from critiquebrainz.decorators import crossdomain from critiquebrainz.ws.exceptions import NotFound from critiquebrainz.ws.oauth import oauth from critiquebrainz.ws.p...
11594056
from bge import logic from link_scripts.PlayerConstants import PlayerState from link_scripts.states.Attack import start_basicSwordAttack1State from link_scripts.states.Ledge import start_climbLedgeState from link_scripts.states.Door import start_openDoorState from link_scripts.states.Hits import start_hitState from lin...
11594076
import os import shutil import datetime import yaml import pyccl import cosmosis import sacc from ._version import __version__ def write_metadata(analysis_id, output_dir, config_file): """Write run metadata to an output path. Parameters ---------- analysis_id : str A unique id for this anal...
11594081
from datetime import datetime, timezone import uuid import humanize import requests import spdx from modelforge.environment import collect_environment_without_packages LICENSES = {l["id"]: l for l in spdx.licenses()} LICENSES["Proprietary"] = {"sources": [""]} def check_license(license: str): """ Ensure th...
11594087
import torch import argparse import cv2 import numpy as np import os from skimage import transform as trans import torch.multiprocessing as mp def parse_args(): parser = argparse.ArgumentParser( description="fake add headband img generation tool") parser.add_argument('--input', dest='input_file', ...
11594111
import os import sys from abc import abstractproperty from functools import lru_cache from importlib import import_module from detect_secrets.plugins.base import BasePlugin from detect_secrets.util import get_root_directory @lru_cache(maxsize=1) def get_mapping_from_secret_type_to_class_name(plugin_filenames=None): ...
11594113
import sublime, sublime_plugin from ..libs import util class JavascriptEnhancementsSurroundWithCommand(sublime_plugin.TextCommand): def run(self, edit, **args): view = self.view selections = view.sel() case = args.get("case") if case == "if_else_statement" : if len(selections) != 2 : re...
11594128
from model import SampleRNN, Predictor, Generator import torch import re import sys import numpy as np import argparse from librosa.output import write_wav import os from interpolate import interpolation import random default_params = { # model parameters 'n_rnn': 1, 'dim': 1024, 'learn_h0': True, ...
11594159
from stdc.app import runThermoCalculator from stdc.flaskapp import create_app import pytest import os import json THIS_DIR = os.path.dirname(os.path.abspath(__file__)) TEST_DIR = os.path.join(THIS_DIR,'refData') @pytest.fixture def client(): app = create_app({'TESTING': True}) with app.test_client() as client...
11594180
from django.core.management.base import BaseCommand from django.core.management import call_command class Command(BaseCommand): help = "Initial migration." def handle(self, *args, **options): call_command("migrate", "contenttypes") call_command("migrate", "auth") call_command("migrate...
11594203
import re import numpy as np def get_timesteps_per_episode(env): """Returns a best guess as to the maximum number of steps allowed in a given Gym environment""" if hasattr(env, "_max_episode_steps"): return env._max_episode_steps if hasattr(env, "spec"): return env.spec.tags.get("wrapper_c...
11594240
import numpy as np import pandas as pd import scipy from numereval.scores import * def neutralize( df, columns, extra_neutralizers=None, proportion=1.0, normalize=True, era_col="era" ): # need to do this for lint to be happy bc [] is a "dangerous argument" if extra_neutralizers is None: extra_neu...
11594242
from CommonServerPython import * # IMPORTS import dns.resolver import re from typing import List, Dict, Callable, Tuple, Any # Disable insecure warnings requests.packages.urllib3.disable_warnings() # CONSTANTS GOOGLE_BASE_DNS = "_cloud-netblocks.googleusercontent.com" def fetch_cidr(dns_address: str) -> List[Dict]...
11594299
import os from skimage.data import chelsea from skimage.io import imsave here = os.path.dirname(__file__) img = chelsea() imsave(os.path.join(here, '..', '_static', 'generated_images', 'chelsea.png'), img)
11594322
NUM_STAGES = 4 def get_stages(): stages = [] for i in range(1, NUM_STAGES + 1): stages.append("stage_" + str(i)) return stages def get_init_args(): return { "kwargs": { "project": "custom_stages", "stages": get_stages(), } } def get_jobs(): jobs...
11594345
import numpy as np import os,sys,time import torch import options,util import model_pretrain print(util.yellow("=======================================================")) print(util.yellow("main_pretrain.py (pretraining with AtlasNet reimplementation)")) print(util.yellow("=============================================...
11594364
from unittest import TestCase import numpy as np from sklearn import datasets from sklearn.linear_model import LogisticRegression from robustnessgym.active import ais # Get labels and probabilities from trained sklearn model def get_labels_and_probs(X_test, clf, rank_prob=False): if hasattr(clf, "predict_proba"...
11594484
def main(): price = float(input("price($): ")) tip_rate = float(input("tip rate(%): ")) tip = round(price * tip_rate / 100, 2) total = price + tip if price < 0: if tip_rate < 0: print("price and tip rate can't be a negative number") else: print("price can't ...
11594504
import unittest from app import app class TestConfig(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def tearDown(self): pass def test_config(self): config = app.config['USER_CONFIG'] self.assertTrue(isinstance(config, dic...
11594505
import sys from PyQt5.QtWidgets import QDialog, QApplication from demoProgressBar import * class MyForm(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.ui.pushButtonStart.clicked.connect(self.updateBar) self.show() def...
11594569
import time import pytest from django.conf import settings from pymongo import MongoClient from node.blockchain.utils.lock import create_lock, lock from node.core.database import get_database from node.core.exceptions import BlockchainIsNotLockedError, BlockchainLockingError, BlockchainUnlockingError def has_lock(n...
11594574
from django.core.handlers.base import BaseHandler from freezegun import freeze_time from ..jwt import ( JWT_REFRESH_TOKEN_COOKIE_NAME, JWT_REFRESH_TYPE, create_refresh_token, jwt_encode, jwt_user_payload, ) @freeze_time("2020-03-18 12:00:00") def test_jwt_refresh_token_middleware(rf, customer_use...
11594575
from pathlib import Path import pytest from tempfile import TemporaryDirectory import numpy as np import pandas as pd from deepnog.data import ProteinIterableDataset from deepnog.learning import fit, predict from deepnog.utils import create_df, get_config DEEPNOG_ROOT = Path(__file__).parent.parent.parent.absolute() ...
11594578
import copy import logging import os from rest_framework import status from rest_framework.test import APITestCase from human_lambdas.user_handler.models import Organization from human_lambdas.workflow_handler.models import Task, Workflow from human_lambdas.workflow_handler.tests.constants import ( REGISTRATION_D...
11594602
import os import unittest import shlex from click.testing import CliRunner from cloudsplaining.command.expand_policy import expand_policy class ExpandPolicyClickTest(unittest.TestCase): def setUp(self): self.runner = CliRunner() def test_click_expand_policy_wildcards(self): """cloudsplaining....
11594710
from pyradioconfig.calculator_model_framework.interfaces.icalculator import ICalculator from pyradioconfig.parts.lynx.calculators.calc_demodulator import CALC_Demodulator_lynx from pyradioconfig.calculator_model_framework.Utils.CustomExceptions import CalculationException from enum import Enum from pycalcmodel.core.var...
11594751
from datetime import datetime, timedelta, timezone import logging import random from django.core.exceptions import ValidationError from app_ccf.models import VoucherCode LOGGER = logging.getLogger(__name__) def import_voucher_codes(filename, batch): LOGGER.info('Uploading codes...') num_valid_codes = 0 ...
11594783
import random def problem2_5(): lst = [] random.seed(171) # don't remove when you submit for grading """ Simulates rolling a die 10 times.""" for i in range(10): # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. ...
11594801
from fence.errors import AuthError, InternalError class JWTError(AuthError): def __init__(self, message, code=401): super(JWTError, self).__init__(message) self.message = str(message) self.code = code class JWTPurposeError(JWTError): pass class JWTSizeError(InternalError): """ ...
11594834
import cv2 import numpy as np from scipy.spatial.transform import Rotation as R # Dictionary that maps from joint names to keypoint indices. KEYPOINT_DICT = { 'nose': 0, 'left_eye': 1, 'right_eye': 2, 'left_ear': 3, 'right_ear': 4, 'left_shoulder': 5, 'right_shoulder': 6, 'left_elbow': ...
11594901
import requests def test_load(): response = requests.post( "http://127.0.0.1:5000/data/load", json={"File": "/mols_data/test_100.smi"} ) assert response.status_code == 200 assert response.json() == {'status': True, 'msg': "Successfully loaded data!"} def test_progress(): response ...
11594922
from pymtl import * from lizard.util.rtl.interface import Interface, UseInterface from lizard.util.rtl.method import MethodSpec from lizard.util.rtl.types import canonicalize_type from lizard.bitutil import clog2, clog2nz class OverlapCheckerInterface(Interface): def __init__(s, base_width, max_size): s.Base =...
11594974
from typing import Dict, Any, List import attr import cassis from cassis import load_cas_from_xmi, load_typesystem # Types JsonDict = Dict[str, Any] # Data classes @attr.s class PredictionRequest: cas: cassis.Cas = attr.ib() layer: str = attr.ib() feature: str = attr.ib() project_id: str = attr.i...
11594985
from yacs.config import CfgNode def get_cfg() -> CfgNode: from .default import _C return _C.clone() def update_config(cfg, args): cfg.defrost() cfg.merge_from_file(args.cfg) cfg.merge_from_list(args.opts) cfg.freeze() return cfg
11595001
from boto.auth_handler import AuthHandler from boto.auth_handler import NotReadyToAuthenticate import oauth2_client import oauth2_helper class OAuth2Auth(AuthHandler): capability = ['google-oauth2', 's3'] def __init__(self, path, config, provider): if (provider.name == 'google' and config.has_option...
11595037
from setuptools import setup, find_packages setup( name='FogLAMP', python_requires='~=3.5', version='0.1', description='FogLAMP', url='http://github.com/foglamp/FogLAMP', author='OSIsoft, LLC', author_email='<EMAIL>', license='Apache 2.0', # TODO: list of excludes (tests) packag...
11595055
import numpy as np # function to evaluate IOU between two boxes def iou(bbox1, bbox2): # shape of both tensor is (num_box, 4) # value in format (xmin, ymin, xmax, ymax) xmin_inter = np.maximum(bbox1[..., 0], bbox2[..., 0]) ymin_inter = np.maximum(bbox1[..., 1], bbox2[..., 1]) xmax_inter = n...
11595057
from __future__ import unicode_literals import json import time from .common import InfoExtractor from ..compat import compat_urllib_parse_urlencode from ..utils import ( ExtractorError, sanitized_Request, ) class HypemIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?hypem\.com/track/(?P<id>[^/]+)/'...
11595091
if __name__ == '__main__': from yapkernel import kernelapp as app app.launch_new_instance()
11595093
from floem import * Inject1 = create_inject("inject1", "int", 10, "gen_func") Inject2 = create_inject("inject2", "int", 10, "gen_func") add = Add(configure=[Int]) inject1 = Inject1() inject2 = Inject2() inject1 >> add.inp1 inject2 >> add.inp2 t = APIThread("run", [], "int") t.run(add) t1 = InternalThread("t1") t1....
11595104
import random from collections import namedtuple, deque import torch import numpy as np from .Replay_Buffer import Replay_Buffer class Action_Balanced_Replay_Buffer(Replay_Buffer): """Replay buffer that provides sample of experiences that have an equal number of each action being conducted""" def __init__(self...
11595113
import json from matrix.lambdas.daemons.notification import NotificationHandler def notification_handler(event, context): notification = json.loads(event["Records"][0]["body"]) assert ('bundle_uuid' in notification and 'bundle_version' in notification and 'event_type' in notification) bundle_uuid = noti...
11595119
from .encoder import CKKSEncoder # noqa: F401 from .encrypter import CKKSEncrypter # noqa: F401 from .plaintext import CKKSPlaintext # noqa: F401
11595188
def test(): if foo in bar: do_something() if foo not in bar: do_something_else() if foo or bar: good() if foo and bar: bad()
11595200
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import requests import os # disable insecure warnings requests.packages.urllib3.disable_warnings() if not demisto.params().get('useProxy', False): del os.environ['HTTP_PROXY'] del os.environ['H...
11595205
import json from vcx.api.connection import Connection from utils import init_vcx, run_coroutine_in_new_loop from connection import BaseConnection class Inviter(BaseConnection): async def start(self): await init_vcx() print("Create a connection to alice and print out the invite details") c...
11595219
import sys sys.path.append('..') import unittest import random from armoryengine.ALL import * class SigningTester(unittest.TestCase): def testLowSig(self): sbdPrivKey = SecureBinaryData(b'\x01'*32) pub = CryptoECDSA().ComputePublicKey(sbdPrivKey).toBinStr() for i in range(100): msg = ...
11595223
from types import MethodType import onnx import torch from torch.onnx import OperatorExportTypes from onnxsim import simplify import argparse import io import sys import torch.nn as nn sys.path.insert(0, '.') from configs import add_centernet_config from detectron2.config import get_cfg from inference.centernet import...
11595264
import os from pathlib import Path project_dir = os.path.split(os.path.dirname(__file__))[0] project_dir_path = Path(project_dir) src_dir = os.path.join(project_dir, "src") src_dir_path = Path(src_dir) ch_src_dir = lambda: os.chdir(src_dir)
11595281
import socket, ssl from binascii import hexlify, unhexlify dump = open("everything.dump", "wb") serverDump = open("fromserver.dump", "wb") clientDump = open("fromclient.dump", "wb") listensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listensocket.bind(("127.0.0.1", 5222)) listensocket.listen(1) # 1...
11595290
import h5py import json import sys import cv2 import os.path as osp import numpy as np from tools import Timer from config import CAFFE_ROOT, DATA_ROOT sys.path.insert(0, osp.join(CAFFE_ROOT, 'python')) import caffe BS = 1 def cnn_patch_feature(net, transformer, image, bbox, include_whole_image=False): im_list ...