id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4833857 | from __future__ import absolute_import, division, print_function
import os,sys
from cctbx.examples.merging import test_levenberg_sparse as test
import libtbx.load_env
import math
# test script assumes that you get the data files directly from the author (NKS) and
# install them in the directory "xscale_reserve" at the... |
4833884 | from .dataset_layout import PanoCorBonDataset
from .dataset_s2d3d_sem import S2d3dSemDataset
from .dataset_depth import CorruptMP3dDepthDataset, MP3dDepthDataset, S2d3dDepthDataset
|
4833887 | import logging
import numpy as np
import torch
from torch import nn
from anchor_based import anchor_helper
from anchor_based.dsnet import DSNet
from anchor_based.losses import calc_cls_loss, calc_loc_loss
from evaluate import evaluate
from helpers import data_helper, vsumm_helper, bbox_helper
logger = logging.getLog... |
4833891 | import numpy as np
import re
import cv2
import sys
import os
""" check the filename path can be loaded"""
def data_load_check(data_path, filenames_file):
print ('load {} and {}'.format(data_path, filenames_file))
with open(filenames_file) as f:
lines = f.readlines()
split_line = [l.rstrip().spl... |
4833914 | import cntk as C
from cntk.io import MinibatchSource, HTKFeatureDeserializer, HTKMLFDeserializer, HTKMLFBinaryDeserializer, StreamDef, StreamDefs
from cntk.layers import Recurrence, Dense, LSTM, Sequential, For
import os
abs_path = os.path.dirname(os.path.abspath(__file__))
data_path = os.path.join(abs_path, "..", "..... |
4833918 | from ._wind_turbines import WindTurbines, WindTurbine
from .wind_turbines_deprecated import DeprecatedOneTypeWindTurbines as OneTypeWindTurbines
|
4833920 | from rxbp.acknowledgement.stopack import StopAck
from rxbp.acknowledgement.continueack import ContinueAck
from rxbp.observers.connectableobserver import ConnectableObserver
from rxbp.testing.testcasebase import TestCaseBase
from rxbp.testing.tobserver import TObserver
from rxbp.testing.tscheduler import TScheduler
cl... |
4833939 | from .aleph_alpha_client import AlephAlphaClient, QuotaError, POOLING_OPTIONS
from .image import ImagePrompt
from .utils import load_base64_from_url, load_base64_from_file
|
4833944 | from scipy.sparse import csc_matrix, _sparsetools
from .matrix_ops import zeros_like
from .serializer import serialize, deserialize
class MatrixSum(object):
"""
Provides an optimised (for our use case) routine for summing matrices
Note the `step` and `finalize` methods are what allow this class to be us... |
4833948 | from conans.errors import InvalidNameException
import re
class Username(str):
base_er = "[a-zA-Z][a-zA-Z0-9_]{1,49}"
pattern = re.compile("^%s$" % base_er)
def __new__(cls, name, validate=True):
"""Simple name creation.
@param name: string containing the desired name
@par... |
4833963 | import numpy as np
import torch
def decode_seg_map_sequence(label_masks):
if label_masks.ndim == 2:
label_masks = label_masks[None, :, :]
rgb_masks = []
for label_mask in label_masks:
rgb_mask = decode_segmap(label_mask)
rgb_masks.append(rgb_mask)
rgb_masks = torch.from_num... |
4833967 | import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
string_types = (str, unicode)
text_type = unicode
def as_text(v):
return v
else:
string_types = (str,)
text_type = str
def as_text(v):
if v is None:
return None
elif isinsta... |
4833978 | import adafruit_ssd1306
import board
import busio
BLACK = 0
WHITE = 1
def animate_pixel(oled, x, y, step_x, step_y, count):
for i in range(count):
x += step_x
y += step_y
oled.pixel(x, y, WHITE)
oled.show()
def zig_zag(oled):
animate_pixel(oled, x=0, y=0, step_x=1, step_y=1,... |
4834034 | from openprocurement.api.models import ListType
from openprocurement.api.roles import RolesFromCsv
from openprocurement.tender.core.models import EUDocument
from openprocurement.tender.openua.models import Cancellation as BaseCancellation
from schematics.types.compound import ModelType
class Cancellation(BaseCancell... |
4834041 | import os
import pytest
import shutil
import logging
import json
from click.testing import CliRunner
from a2ml.api.utils.context import Context
@pytest.fixture
def ctx():
# load config(s) from the test app
return Context(debug=True)
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture(scope... |
4834046 | import asyncio
from typing import Optional, NoReturn
from aiofcm.connection import FCMConnectionPool
from aiofcm.common import Message, MessageResponse
from aiofcm.logging import logger
class FCM:
def __init__(self, sender_id, api_key, max_connections=10, loop=None):
# type: (int, str, int, Optional[asyn... |
4834047 | from ..compound import Compound
from ..placeholder import Placeholder
from ..primitive import Primitive
from .navstate import NavState
from .horz import Horz
class VertFolder(NavState):
"""
A vertical state transitioner, that also holds recursive children.
VertFolder instances are toggled between by pre... |
4834061 | from .regioned_memory_mixin import RegionedMemoryMixin
from .region_category_mixin import RegionCategoryMixin
from .static_find_mixin import StaticFindMixin
from .abstract_merger_mixin import AbstractMergerMixin
from .region_meta_mixin import MemoryRegionMetaMixin
from .regioned_address_concretization_mixin import Regi... |
4834088 | from ctypes import memmove, memset, addressof, sizeof
from watsor.stream.share import Detection
from watsor.stream.work import WorkPassthroughPublish
from watsor.stream.share import FrameBuffer, FramesPerSecond
class DetectionSieve(WorkPassthroughPublish):
"""Filters detections right after inference, modifying de... |
4834108 | from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.urls import path
site = admin.AdminSite(name="custom_user_admin")
class CustomUserAdmin(UserAdmin):
def log_change(self, request, obj, message):
# LogEntry.user colu... |
4834113 | from django.http import (
HttpResponse, HttpResponseBadRequest, HttpResponseNotFound,
)
from django.views.decorators.http import require_POST
from .fieldsetup import fieldsetups
from .forms import SendForm
from .utils import send_code
@require_POST
def send(request, fieldsetup_id):
try:
fieldsetup = ... |
4834125 | from tkinter import *
# --- functions ---
def addtolist():
global List
List = []
for item in varList:
if item.get() != "":
List.append(item.get())
print(List)
# --- main ---
List = []
varList = []
myApp = Tk()
myApp.title("GUI app")
myApp.geometry("300x500")
var1 = StringVar()... |
4834137 | from __future__ import division
from builtins import object
from past.utils import old_div
import pytest
import numpy as np
try:
import cupy as cp
try:
cp.cuda.Device(0).compute_capability
except cp.cuda.runtime.CUDARuntimeError:
pytest.skip("GPU device inaccessible", allow_module_level=Tru... |
4834163 | from __future__ import unicode_literals
from django.conf import settings
from django.utils import six
from django.utils.functional import cached_property
from jsonmask import parse_fields, should_include_variable
from rest_framework import exceptions
from . import constants
from .utils import collapse_includes_exclud... |
4834170 | import wtforms_json
from flask import Flask, jsonify
from agent import di
from agent.api.routes.alerts import alerts
from agent.api.routes.data_extractors.cacti import cacti
from agent.api.routes.data_extractors.snmp import snmp
from agent.modules import logger
from agent.api.routes.monitoring import monitoring_bp
fro... |
4834175 | import numpy as np
"""
DBSCAN.py
detail: Clustering Algorithm
author: <NAME>
see others in repository : sadlearn
in URL: https://github.com/sajjjadayobi/sadlearn/
date : 10/5/2018
"""
class DBSCAN:
"""
DBSCAN is a Algorithm for clustering also can find Noise in data
Good for data whi... |
4834210 | import csv
import inspect
import sys
from argparse import RawTextHelpFormatter
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand
from corehq.apps.users.models import CouchUser
from corehq.util.argparse_types import validate_range
from cu... |
4834211 | from django.apps import AppConfig
from django.db.models.signals import post_migrate
from share.signals import post_migrate_load_sources
class ShareConfig(AppConfig):
name = 'share'
def ready(self):
post_migrate.connect(post_migrate_load_sources, sender=self)
|
4834218 | import anna.client as client
import anna.lattices as lattices
import time
from datetime import datetime
import argparse
from multiprocessing import Process
import random
parser = argparse.ArgumentParser(description='Client to SIGCOMM demo')
parser.add_argument('ip', type=str, help='IP address of the client.')
parser.a... |
4834259 | import unittest
from palindrome_products import (
largest,
smallest,
)
# Tests adapted from `problem-specifications//canonical-data.json`
class PalindromeProductsTest(unittest.TestCase):
def test_finds_the_smallest_palindrome_from_single_digit_factors(self):
value, factors = smallest(min_factor=... |
4834294 | from __future__ import division
import numpy as np
from matplotlib import animation
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.artist import setp
plt.switch_backend('tkagg')
from mpl_toolkits.mplot3d.axes3d import Axes3D
from scipy.sparse import spdiags, coo_matrix, bmat, identity
fr... |
4834316 | from todo.constants import COMMANDS
from todo.parser.base import BaseParser
class InitializeConfigParser(BaseParser):
"""
usage: td init-config
td ic
initialize config
optional arguments:
-h, --help show this help message and exit
"""
command = COMMANDS.INITIALIZE_C... |
4834317 | import uuid
from retrying import retry
from module.config import api_pixiv
import hashlib
import requests
import json
import time
from loguru import logger
from datetime import datetime
import threading
# import socket
# import socks
# socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 10808)
# socket.socket = sock... |
4834346 | import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('Publisher')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
class Publisher(object):
#======================== public ==========================================
def run(self)... |
4834391 | from __future__ import absolute_import
from __future__ import print_function
import math
import functools
from collections import OrderedDict
import veriloggen.core.vtypes as vtypes
import veriloggen.types.axi as axi
from veriloggen.fsm.fsm import FSM
from veriloggen.optimizer import try_optimize as optimize
from .t... |
4834409 | import torch
import cv2
from tqdm import tqdm
# Project imports
from utils import *
from options import TestOptions
from data_loaders import create_dataloader
from methods import BaseMethod
class Tester:
"""
Tests the performance of models in saved_models//
Initialize the trainer using a set of ... |
4834427 | import sys
import math
import scipy
import pylab
import scipy.io.wavfile as wav
import wave
from scipy import signal
from itertools import product
import numpy
def readWav():
"""
Reads a sound wave from a standard input and finds its parameters.
"""
# Read the sound wave from the input.
sound... |
4834516 | from .handler_registry import Handlers, ConfigureHandlers
from .executor import ProcessEvents
from .args import AddArgs
|
4834526 | import sys,os
curr_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在绝对路径
parent_path = os.path.dirname(curr_path) # 父路径
sys.path.append(parent_path) # 添加路径到系统路径
import gym
import torch
import numpy as np
import datetime
from common.utils import plot_rewards
from common.utils import save_results,make_dir
from ... |
4834553 | import re
import subprocess
import sys
from pathlib import Path
import pytest
DATADIR = Path(__file__).parent / "data"
def generate_testdata():
for path in sorted(DATADIR.glob("*.py")):
yield path
def generate_test_id(path):
return path.stem
@pytest.mark.parametrize("path", generate_testdata(), ... |
4834576 | import unittest
import os
from mltoolkit.mlutils.tools import ExperimentsPathController
from shutil import rmtree
import time
from datetime import datetime
class TestEPC(unittest.TestCase):
"""Tests ExperimentsPathController class."""
def setUp(self):
self.base_path = 'tmp'
try:
o... |
4834577 | import os
import random
import argparse
import numpy as np
from datasets import LJSpeech, DataBaker, TFRecordWriter
from configs import LJHPS, DataBakerHPS
dataset_hps = {'ljspeech': LJHPS, 'databaker': DataBakerHPS}
dataset_extractor = {'ljspeech': LJSpeech, 'databaker': DataBaker}
def main():
par... |
4834643 | import os
import animalai
from animalai.envs.gym.environment import AnimalAIGym
from pytorchrl.envs.common import FrameStack, FrameSkip, DelayedReward
from pytorchrl.envs.animal_olympics.wrappers import RetroEnv, FilterActionEnv, LabAnimal, RewardShaping
def animal_train_env_factory(
index_col_worker, index_g... |
4834662 | import unittest
from pyreinforce.acting import EpsGreedyPolicy, DecayingEpsGreedyPolicy
from pyreinforce.distributed import ExperienceBuffer
from pyreinforce.distributed.td import AsyncTdAgent, TdWorker
from tests import TestEnv as DummyEnv, GridWorld, assert_grid_world_policy
from tests.distributed import DummyQBrai... |
4834684 | import cvxpy as cvx
class SCProblem:
"""
Defines a standard Successive Convexification problem and adds the model specific constraints and objectives.
:param m: The model object
:param K: Number of discretization points
"""
def __init__(self, m, K):
# Variables:
self.var = di... |
4834685 | import unittest
from typing import Generator, List
from bs4 import BeautifulSoup as Soup
from eksi.eksi import Eksi
class TestEksi(unittest.TestCase):
def setUp(self):
self.base_url = "https://eksisozluk.com/"
self.eksi = Eksi()
def test_get_soup(self):
soup_obj = self.eksi.get_soup... |
4834690 | import py
import sys
from rpython.rtyper.lltypesystem import lltype
from rpython.rlib import rawstorage
from rpython.rlib.rawstorage import alloc_raw_storage, free_raw_storage,\
raw_storage_setitem, raw_storage_getitem, AlignmentError,\
raw_storage_setitem_unaligned, raw_storage_getitem_unaligned
from rpython... |
4834759 | from datetime import timedelta
from feast import Entity, FeatureView, Field
from feast.infra.offline_stores.contrib.postgres_offline_store.postgres_source import (
PostgreSQLSource,
)
from feast.types import Float32, Int64
driver = Entity(name="driver_id", join_keys=["driver_id"],)
driver_stats_source = Postgre... |
4834766 | import os
import json
import re
from jinja2 import Template
from jinja2 import FileSystemLoader
from jinja2.environment import Environment
def to_c_macro(name):
macro = re.sub('\W', '_', name)
macro = macro + ('_' if macro[0].isdigit() else '')
return macro.upper()
class SIGModel(object):
def __init... |
4834769 | from uuid import uuid4
import pytest
from pluggy import HookimplMarker
from flaskbb.core.changesets import ChangeSetPostProcessor, ChangeSetValidator
from flaskbb.core.exceptions import (PersistenceError, StopValidation,
ValidationError)
from flaskbb.core.user.update import Passwo... |
4834794 | import sys
import socket
import threading
import ssl
def send_msg(sock, msg):
""" Send a string over a socket, preparing it first """
msg += '\0'
data = msg.encode('utf-8')
sock.sendall(data)
def parse_recvd_data(data):
""" Break up raw received data into messages, delimited
by null byte """
parts = dat... |
4834828 | from __future__ import unicode_literals
from django.apps import AppConfig
class VMMemoryConfig(AppConfig):
name = 'vmmemory'
|
4834857 | import nose
import archinfo
from pyvex import IRSB, lift, ffi
from pyvex.lifting.util import Instruction, GymratLifter, JumpKind
from pyvex.errors import PyVEXError
def test_partial_lift():
"""This tests that gymrat correctly handles the case where an
instruction is longer than the remaining input.
"""
... |
4834874 | import numpy as np
import os
import shutil
from pytracking.evaluation.environment import env_settings
from pytracking.evaluation.datasets import get_dataset
def pack_trackingnet_results(tracker_name, param_name, run_id=None, output_name=None):
""" Packs trackingnet results into a zip folder which can be directly ... |
4834880 | from attr import attrs, attrib
from aioalice.types import AliceObject, MediaButton
from aioalice.utils import ensure_cls
@attrs
class CardFooter(AliceObject):
"""This object represents a card's footer"""
text = attrib(type=str)
button = attrib(default=None, converter=ensure_cls(MediaButton))
|
4834938 | import dash_bootstrap_components as dbc
from dash import html
import apps.dcc_component_gallery as dcc_gallery
import apps.dbc_component_gallery as dbc_gallery
import util
dbc_gallery_div = html.Div(
[
dbc_gallery.intro,
dbc_gallery.alerts,
dbc_gallery.badges,
dbc_gallery.buttons,... |
4834969 | from twisted.internet import reactor
from scrapy.crawler import Crawler, CrawlerRunner
from scrapy.settings import Settings
from crawlerflow.contrib.spiders.web import InvanaBotSingleWebCrawler
from crawlerflow.contrib.spiders.xml import GenericXMLFeedSpider
from crawlerflow.contrib.spiders.api import GenericAPISpider
... |
4834979 | import json
import logging
import re
import urlparse
import ckanext.hdx_package.helpers.custom_validator as vd
from ckanext.hdx_package.exceptions import NoOrganization
from ckanext.hdx_package.helpers.caching import cached_group_iso_to_title
from ckanext.hdx_package.helpers.constants import UPDATE_FREQ_LIVE
from ckan... |
4834990 | import os
from expects import equal, expect, start_with, contain
from mamba import before, context, description, it
from sdcclient import SdSecureClient
from specs import be_successful_api_call
with description("Custom Rules", "integration") as self:
with before.each:
self.client = SdSecureClient(sdc_url... |
4834995 | from __future__ import print_function, division
import os
import torch
from torch import nn
import numpy as np
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import scale
import torch.utils
from sklearn.metrics import confusion_matrix
import itertools
from utils import get_meta, get_len, sa... |
4835061 | import pandas as pd
import numpy as np
from framework.util import save_tsv, no_zeros_formatter
from main.data import SETTINGS, IN_PAPER_NAMES, VAD, BE5, VA, SHORT_COLUMNS
import datetime
df=pd.read_excel('../shr.xlsx', sheet_name=None, index_col=0)
# print(df)
def undo_spearman_brown(x):
'''
Reverts Spearman-Bro... |
4835085 | import logging
from pyats import aetest
logger = logging.getLogger(__name__)
class common_setup(aetest.CommonSetup):
@aetest.subsection
def sample_subsection_1(self):
logger.info("Aetest Common Setup ")
@aetest.subsection
def sample_subsection_2(self, section):
logger.info("Inside %... |
4835095 | import datetime
from freezegun import freeze_time
from taxi.commands.types import Date
def get_date(date):
return Date().convert(date, None, None)
def test_date_today():
assert get_date('today') == datetime.date.today()
def test_date_yesterday():
assert get_date('yesterday') == datetime.date.today()... |
4835126 | from django.urls import re_path
from . import views
from .api import API
urlpatterns = [
re_path(r"discover/$", views.discover, name="api_discover"),
re_path(
r"call/(?P<version>.+)/(?P<namespace>\w+)/(?P<call_name>\w+)/$",
views.call,
name="api_call",
),
re_path(
r"(?P... |
4835127 | import dataclasses
import re
from datetime import date
from string import Formatter
from typing import Any, Dict, Optional, Union
from mnamer.language import Language
from mnamer.types import MediaType
from mnamer.utils import (
fn_pipe,
is_subtitle,
normalize_container,
parse_date,
str_fix_padding... |
4835143 | from armulator.armv6.opcodes.abstract_opcodes.ldrt import Ldrt
from armulator.armv6.opcodes.opcode import Opcode
class LdrtA1(Ldrt, Opcode):
def __init__(self, instruction, add, post_index, t, n, imm32):
Opcode.__init__(self, instruction)
Ldrt.__init__(self, add, False, post_index, t, n, imm32=imm... |
4835156 | import pandas as pd
import pytest
from pyextremes.models import get_model
def test_get_model():
with pytest.raises(ValueError, match=r"invalid value.*'model' argument"):
get_model(
model="BAD MODEL", extremes=pd.Series([1, 2, 3]), distribution="genextreme"
)
|
4835163 | import tensorflow as tf
import pdb
def l1_loss(y_true, y_pred):
return tf.reduce_mean(tf.abs(tf.cast(y_true,tf.float32) - tf.cast(y_pred, tf.float32)))
def l1_loss_weighted(y_true, y_pred, mask_true):
masked_true = tf.multiply(y_true, mask_true)
makes_pred = tf.multiply(y_pred, mask_true)
l1 = tf.abs(... |
4835207 | from datetime import datetime, date, timedelta
import calendar
def get_month_range(start_date=None):
if start_date is None:
start_date = date.today().replace(day=1)
days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]
end_date = start_date + timedelta(days=days_in_month)
re... |
4835220 | from __future__ import absolute_import, unicode_literals
from datetime import datetime
import types
from django.utils import timezone
import pytest
from souvenirs.utils import (adjust_to_calendar_month,
adjust_to_subscription_start,
iter_days, iter_months, iter... |
4835226 | import os
import time
from logging import raiseExceptions
import numpy as np
import pandas as pd
import scipy.sparse as ssp
import scipy.stats as stats
import statsmodels.sandbox.stats.multicomp
from ete3 import Tree
from matplotlib import pyplot as plt
from scipy.cluster import hierarchy
# from plotnine import *
fro... |
4835233 | def brute_dlp(g, y, p):
"""
Brute Force algorithm to solve DLP. Use only if the group is very small.
Includes memoization for faster computation
:parameters:
g : int/long
Generator of the group
y : int/long
Result of g^x % p
p : int/long
... |
4835307 | from django.contrib import admin
# RegisterView your models here.
from openbook_auth.models import User, UserProfile
class UserProfileInline(admin.TabularInline):
model = UserProfile
def has_delete_permission(self, request, obj=None):
return False
class UserAdmin(admin.ModelAdmin):
inlines = [... |
4835329 | import sys
sys.path.append("../flowchart/generate")
import asyncflow
import Flowchart_AI
import Flowchart_Subchart
import time
import asyncflow
from io import StringIO
import pytest
class EventId():
Event0Arg = 3
Event1Arg = 4
Event2Arg = 5
class Character:
allCharacter = []
def __init__(self... |
4835352 | from copy import deepcopy
from typing import Any, List, Optional, Union
from fedot.core.dag.graph_node import GraphNode
from fedot.core.pipelines.convert import graph_structure_as_nx_graph
class GraphOperator:
def __init__(self, graph=None):
self._graph = graph
def delete_node(self, node: GraphNode)... |
4835379 | import pytest
from scrapy_autoextract.errors import QueryError, summarize_exception
def test_query_error():
exc = QueryError({"foo": "bar"}, "sample error")
assert str(exc) == "QueryError: message='sample error', query={'foo': 'bar'}"
@pytest.mark.parametrize("exception, message", [
(QueryError({}, "do... |
4835386 | import unittest, os, tempfile
from pygromos.files.topology.disres import Disres
from pygromos.utils import bash
from pygromos.tests.test_files.general_file_functions import general_file_tests
from pygromos.tests.in_testfiles import in_test_file_path
root_in =in_test_file_path+"/disres"
in_path = root_in+"/in_disres.d... |
4835399 | import numpy as np
import pytest
import hoomd
import hoomd.conftest
@pytest.fixture(
params=[
(hoomd.md.force.Active, {
"filter": hoomd.filter.All()
}),
(
hoomd.md.force.ActiveOnManifold,
{
"filter": hoomd.filter.All(),
#... |
4835461 | import time
from multiprocessing import Process
from typing import Dict
import pytest
from filelock import FileLock
from mmpy_bot import (
Bot,
ExamplePlugin,
Message,
Plugin,
Settings,
WebHookExample,
listen_to,
)
from mmpy_bot.driver import Driver
OFF_TOPIC_ID = "ahzqezf33jny9mpst758dna... |
4835463 | import unittest
from typing import Mapping, Sequence
from unittest.mock import Mock, patch
import numpy as np
import torch
from rising.loading.dataset import Dataset
from rising.loading.loader import (
BatchTransformer,
DataLoader,
SampleTransformer,
_MultiProcessingDataLoaderIter,
_seed_npy_befor... |
4835478 | import numpy as np
import torch
import torch.nn as nn
class line_order_frame_pipe:
def __init__(self, tot_length=21, max_time=18):
self.tot_length = tot_length
self.max_time = max_time
self.time_count = dict()
self.img_pipe = dict()
def saving_frame(self, new_img_id, ne... |
4835494 | from . import tree
class Node:
def __init__(self, container, parent, value=None):
self._node = tree.Node(container, parent, value)
@property
def _container(self):
return self._node._container
@property
def id(self):
return self._node.id
@property
def value(self):... |
4835509 | from raptiformica.shell.execute import run_critical_unbuffered_command_print_ready
from raptiformica.utils import retry
WGET_TIMEOUT = 15
@retry(attempts=3, expect=(TimeoutError,))
def wget(url, host=None, port=22, failure_message='Failed retrieving file'):
"""
Download a file on the remote host
The wget... |
4835524 | import sys
import numpy as np
import pandas as pd
import os
from PIL import Image
max_res_h = 1080
max_res_w = 500
if __name__ == "__main__":
fmaps = [os.path.join(sys.argv[1], f) for f in os.listdir(sys.argv[1])]
all_fmaps = []
for fmap_path in fmaps:
all_fmaps.append(pd.read_csv(fmap_path, delimit... |
4835526 | from dal.copo_da import DataFile, Annotation
import pandas
from django.http import HttpResponse
import json
from bson import json_util
from dal.copo_da import TextAnnotation
import numpy as np
from web.apps.web_copo.utils import ajax_handlers
from Bio import Entrez
# how many rows of each sheet should be shown to the ... |
4835555 | import argparse
import os
import sys
import requests
import shutil
from urlparse import urlparse
from osgeo import ogr, osr
import gdal
import numpy as np
from gdalconst import *
PLANET_KEY = os.environ.get('PLANET_KEY')
if not PLANET_KEY:
raise Exception('PLANET_KEY environment variable not set!')
def downloa... |
4835569 | import subprocess
import re
def networksetup(*arguments):
"""
Wraps the networksetup CLI
"""
return subprocess.check_output(['/usr/sbin/networksetup'] +
list(arguments))
def get_webproxy(service):
return networksetup('-getwebproxy', service)
def set_webpr... |
4835587 | from kafka import KafkaConsumer
consumer = KafkaConsumer(bootstrap_servers=['10.1.0.13:9092','10.1.0.11:9092'],auto_offset_reset='earliest',api_version=(0, 10, 1))
consumer.subscribe(['vesseltopic'])
for msg in consumer:
print (msg)
consumer = KafkaConsumer(bootstrap_servers=['10.1.0.13:9092','10.1.0.11:9092'],... |
4835608 | uctable = [ [ 194, 173 ],
[ 216, 128 ],
[ 216, 129 ],
[ 216, 130 ],
[ 216, 131 ],
[ 216, 132 ],
[ 216, 133 ],
[ 216, 156 ],
[ 219, 157 ],
[ 220, 143 ],
[ 225, 160, 142 ],
[ 226, 128, 139 ],
[ 226, 128, 140 ],
[ 226, 128, 141 ],
[ 226, 128, 142 ],
[ 226, 128, 143 ],
[ 226, 128, 170 ],
[... |
4835635 | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['AlexNet', 'alexnet']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
def load_pretrained_model(model, url):
pretrained_state = model_zoo.load_url(model_urls[url])
model_state = model.s... |
4835645 | import pytest
from spafe.utils import vis
from spafe.fbanks import mel_fbanks
from spafe.utils.exceptions import ParameterError
@pytest.mark.test_id(101)
@pytest.mark.parametrize('nfilts', [12, 24])
@pytest.mark.parametrize('nfft', [256, 512, 1024])
@pytest.mark.parametrize('fs', [8000, 16000])
@pytest.mark.parametri... |
4835682 | import numpy as np
from scipy.ndimage.filters import maximum_filter
def check_common_points(kpts, mask):
idx_valid_points = []
for idx, ktp in enumerate(kpts):
if mask[int(round(ktp[0])), int(round(ktp[1]))]:
idx_valid_points.append(idx)
return np.asarray(idx_valid_points)
def sel... |
4835713 | class User2():
def __init__(self,first_name,last_name,phone,years):
#"""Initialize name and age attributes."""
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.years = years
self.login_attempts = 0
def describe_user(self):
p... |
4835719 | expected_output = {
"index": {
1: {
"name": "Chassis",
"descr": "Cisco Catalyst 9500 Series Chassis",
"pid": "C9500-32QC",
"vid": "V01",
"sn": "CAT2242L6CG",
},
2: {
"name": "Power Supply Module 0",
"descr": ... |
4835754 | import numpy as np
from scipy import linalg
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from min2net.utils import butter_bandpass_filter
# Note that we modify CSP function using MNE-Python package (version 0.20).
# Reference:
# - https://github.com/mne-tools/mne-python
# - <NAME>, <NAME>, <... |
4835766 | import sys
import warnings
import multiprocessing
import numpy as np
import pytest
try:
import torch # skipcq: PYL-W0611
import torchvision # skipcq: PYL-W0611
torch_available = True
except ImportError:
torch_available = False
try:
import imgaug
imgaug_available = True
except ImportErro... |
4835861 | from . import conversions
from . import loadsave
from . import mapping
from . import readers
from . import writers
from .mapping import MappedAffine
from .loadsave import map, load, loadf, save, savef
# Import implementations
from .freesurfer.lta import LinearTransformArray
from .freesurfer.registerdat import Registe... |
4835869 | import torch
import numpy as np
import cv2
import neuron.ops as ops
from neuron.config import registry
from .tracker import Tracker
__all__ = ['TrackerSiamFC']
@registry.register_module
class TrackerSiamFC(Tracker):
def __init__(self, backbone, head, cfg):
super(TrackerSiamFC, self).__init__(
... |
4835905 | import collections
import fastzbarlight
import itertools
import logging
from multiprocessing import pool
import numpy as np
import time
import threading
# import psutil
import sys
from collections import namedtuple
from gym.utils import reraise
import re
from universe import error, pyprofile, spaces
# TODO: prefix th... |
4835918 | class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
dp = [[] for _ in range(target + 1)]
dp[0].append([])
for i in range(1, targe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.