id
stringlengths
3
8
content
stringlengths
100
981k
1609690
from datetime import date from django.test import TestCase from nablapps.accounts.models import FysmatClass, NablaUser class ClassesTest(TestCase): def setUp(self): now = date.today() years = [now.year - y for y in range(7)] self.classes = [ FysmatClass.objects.create(name=f"...
1609691
from datetime import datetime, timedelta import binascii from modules import logger class System_Service_Information: par_id = '' case_id = '' evd_id = '' service_name = '' service_type = '' start_type = '' service_location = '' groups = '' display_name = '' dependancy = '' ...
1609712
import shutil import pytest from saltfactories.bases import SaltDaemon from saltfactories.exceptions import FactoryNotStarted @pytest.fixture def config_dir(pytester): _conf_dir = pytester.mkdir("conf") try: yield _conf_dir finally: shutil.rmtree(str(_conf_dir), ignore_errors=True) @py...
1609825
import os from django.test import SimpleTestCase from corehq.apps.app_manager.models import ReportAppConfig, ReportModule from corehq.apps.callcenter import const from corehq.apps.callcenter.app_parser import ( ParsedIndicator, _get_indicators_used_in_forms, _get_indicators_used_in_modules, get_call_c...
1609845
class Matrix: """ <class Matrix> struktur matrix """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> >>> a = Matrix(2, 3, 1) >>> a Matriks terdiri dari 2 baris dan 3 kolom [1, 1, 1] [1, 1, 1] ...
1609920
import pytest from tf_yarn._env import ( gen_pyenv_from_existing_archive, CONDA_CMD, CONDA_ENV_NAME ) test_data = [ ("/path/to/myenv.pex", "./myenv.pex", "myenv.pex"), ("/path/to/myenv.zip", f"{CONDA_CMD}", CONDA_ENV_NAME) ] @pytest.mark.parametrize( "path_to_archive,expected...
1609937
import os import json import pandas as pd import configparser import logging logging.basicConfig(level=logging.DEBUG, format='[ConfigurationManager] %(asctime)s %(levelname)s %(message)s') class ConfigurationManager(object): """ Configuration Manager Class that manages the configurat...
1609968
import os class Config(): SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32)) POSTGRES_USER = os.environ['POSTGRES_USER'] POSTGRES_PASS = os.environ['POSTGRES_PASS'] POSTGRES_HOST = os.environ['POSTGRES_HOST'] POSTGRES_PORT = int(os.environ.get('POSTGRES_PORT', 5432)) POSTGRES_DB = os...
1609983
from ..utils import choose_weighted_option from ..classes import * from ..meta_classes import DataSetProperties, PersonStyleWeightDistribution, ProductStyleWeightDistribution def product_style_function(product_styles_distribution: ProductStyleWeightDistribution) -> ProductStyleVector: return choose_weighted_optio...
1609987
import sys import pytest from io import StringIO from django.core.management import call_command from awx.main.management.commands.update_password import UpdatePassword def run_command(name, *args, **options): command_runner = options.pop('command_runner', call_command) stdin_fileobj = options.pop('stdin_f...
1610021
import time from collections import OrderedDict import os import lasagne import numpy as np # specifying the gpu to use # import theano.sandbox.cuda # theano.sandbox.cuda.use('gpu1') import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from theano.sc...
1610023
import argparse import os import time import matplotlib.pyplot as plt import numpy as np import PIL import torch import torch.optim as optim import torchvision from PIL import Image from torch import nn from torch.nn import functional as F from models.vanilla_vae_q import QuaternionVanillaVAE from models.vanilla_vae ...
1610050
import os.path as osp import shutil import progressbar import torch from torch_geometric.data import InMemoryDataset, extract_zip from torch_geometric.io import read_ply class FAUST(InMemoryDataset): r"""The FAUST humans dataset from the `"FAUST: Dataset and Evaluation for 3D Mesh Registration" <http://fi...
1610060
import collections import json import os import warnings import copy import attr import numpy as np from functools import lru_cache import torch from transformers import AutoModel, AutoTokenizer, AutoConfig from text2qdmr.model.modules import abstract_preproc from text2qdmr.model.modules import encoder_modules from ...
1610072
import torch.nn.functional as F import torchbearer from torchbearer.callbacks import Callback from fmix import sample_mask, FMixBase import torch def fmix_loss(input, y, index, lam, train=True, reformulate=False, bce_loss=False): r"""Criterion for fmix Args: input: If train, mixed input. If not train...
1610125
PONG = "pong" # API Descriptions API_GET_HEALTH_STATUS = "Get health status" API_GET_ALL_WORKSPACES = "Get all workspaces" API_GET_WORKSPACE_BY_ID = "Get workspace by Id" API_CREATE_WORKSPACE = "Create a workspace" API_DELETE_WORKSPACE = "Delete workspace" API_UPDATE_WORKSPACE = "Update an existing workspace" API_GE...
1610126
class CreditCardNumbers(object): class CardTypeIndicators(object): Commercial = "4111111111131010" DurbinRegulated = "4111161010101010" Debit = "4117101010101010" Healthcare = "4111111510101010" Payroll = "4111111114101010" Prepaid = "4111111111111210" Issuin...
1610135
from django.urls import path from extras.views import ObjectChangeLogView from .models import ASN, BGPSession, Community, RoutingPolicy, BGPPeerGroup from .views import ( ASNListView, ASNView, ASNBulkDeleteView, ASNEditView, ASNBulkEditView, ASNDeleteView, CommunityListView, CommunityEditView, CommunityView, ...
1610190
from vtkmodules.vtkIOImage import vtkPNGReader from vtkmodules.vtkCommonCore import vtkFloatArray, vtkUnsignedCharArray from vtkmodules.vtkCommonDataModel import vtkImageData from vtkmodules.vtkIOLegacy import vtkDataSetWriter from vtkmodules.web.camera import normalize, vectProduct, dotProduct from vtkmodules.web imp...
1610198
import logging import gpxpy import gpxpy.gpx from wkz.gis.geo import get_total_distance_of_trace from wkz.io.parser import Parser log = logging.getLogger(__name__) class GPXParser(Parser): def __init__(self, path_to_file: str, md5sum: str): super(GPXParser, self).__init__(path_to_file, md5sum) ...
1610199
import sys import os import numpy as np import cv2 import torch from model import * from scipy.ndimage.filters import gaussian_filter from loss import kldiv, cc, nss import argparse from torch.utils.data import DataLoader from dataloader import DHF1KDataset from utils import * import time from tqdm import tqdm from to...
1610227
from typing import List from .dataset import Dataset from .formatters import Formatter from .writers import Writer class ExportApplicationService: def __init__(self, dataset: Dataset, formatters: List[Formatter], writer: Writer): self.dataset = dataset self.formatters = formatters self.wr...
1610231
from .joystickpad import JoystickPad from .touchdata import TouchData from kivy.uix.widget import Widget from kivy.properties import(BooleanProperty, NumericProperty, ListProperty, ReferenceListProperty) import math OUTLINE_ZERO = 0.00000000001 # replaces user's 0 value for outlines, avoids...
1610276
import torch import torchvision from torch.optim import Adam, SGD _opt_dict = {"Adam": Adam, "SGD": SGD} def get_opt(name): return _opt_dict[name] def config_to_str(config): attrs = vars(config) string_val = "Config: -----\n" string_val += "\n".join("%s: %s" % item for item in attrs.items()) string_val +...
1610280
import glob import os import sys from setuptools import find_packages, setup from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.sdist import sdist as _sdist from setuptools.extension import Extension from setupext import check_for_openmp def get_version(filename): """ G...
1610288
from asynctest import ( mock as async_mock, TestCase as AsyncTestCase, ) from ......connections.models.conn_record import ConnRecord from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder from ......transport.inbound.receipt import MessageReceipt from .....
1610297
from pyspark.sql import Row from chispa.number_helpers import nan_safe_equality def are_rows_equal(r1: Row, r2: Row) -> bool: return r1 == r2 def are_rows_equal_enhanced(r1: Row, r2: Row, allow_nan_equality: bool) -> bool: if r1 is None and r2 is None: return True if (r1 is None and r2 is not No...
1610343
from typing import List class Solution: def gameOfLife(self, board: List[List[int]]) -> None: def get_neighbor_count(i, j, board): top = max(0, i - 1) bottom = min(len(board) - 1, i + 1) left = max(0, j - 1) right = min(len(board[0]) - 1, j + 1) ...
1610366
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import numpy as np import logging from constant import * import utility from synset2vec_hier import get_synset_encoder logger = logging.getLogger(__file__) logging.basicConfig( format...
1610384
import pytest from landlab import HexModelGrid, RasterModelGrid from landlab.components import ChiFinder, FlowAccumulator def test_route_to_multiple_error_raised(): mg = RasterModelGrid((10, 10)) z = mg.add_zeros("topographic__elevation", at="node") z += mg.x_of_node + mg.y_of_node fa = FlowAccumulat...
1610395
from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def diffsize(edit): if type(edit) == int: diffsize = edit else: diffsize = edit['newlength'] - edit['oldlength'] diffs...
1610402
import numpy as np import matplotlib.pyplot as plt from FEM.PlaneStress import PlaneStress from FEM.Mesh.Geometry import Geometry # 11.7.1 Ed 3 b = 120 h = 160 t = 0.036 E = 30*10**(6) v = 0.25 gdls = [[0, 0], [b, 0], [0, h], [b, h]] elemento1 = [0, 1, 3] elemento2 = [0, 3, 2] dicc = [elemento1, elemento2] tipos = ['T...
1610412
import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() employee_project = sa.Table( "employee_project", Base.metadata, sa.Column("project_id", sa.Integer, sa.ForeignKey("project.id")), sa.Column("employee_id", sa.Integer, sa.ForeignKey("employee.id")...
1610426
from decimal import Decimal from django.conf import settings from django.utils.safestring import mark_safe def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False, use_l10n=None): """ Get a number (as a number or string), and return it as a string, u...
1610427
from abc import ABC, abstractmethod from typing import List, Optional import sc2 from sc2.ids.buff_id import BuffId from sharpy.general.component import Component from sc2 import AbilityId, Race, UnitTypeId from sc2.position import Point2 from sc2.unit import Unit, UnitOrder from sc2.unit_command import UnitCommand f...
1610457
import csv import io import time from typing import Tuple, List, Optional, IO, Iterable import boto3 ATHENA_POLL_INTERVAL = 1 # In seconds ATHENA_STATE_SUCCEEDED = {'SUCCEEDED'} ATHENA_STATE_WAIT = {'QUEUED', 'RUNNING'} ATHENA_STATE_ERROR = {'FAILED', 'CANCELLED'} def _split_s3_path(s3_path: str) -> Tuple[str, str...
1610462
alist = [] def app(env, start_response): ''' print 'foo!' print type(start_response) print dir(start_response) c = start_response.__class__ try: c() except: import traceback; traceback.print_exc() try: class x(c): pass except: import traceback; traceb...
1610506
def parse_cookie_full(cookie): cookiedict = {} for chunk in cookie.split(';'): if '=' in chunk: key, val = chunk.split('=', 1) else: key, val = '', chunk key, val = key.strip(), val.strip() if key or val: cookiedict[key] = val return cookie...
1610516
from .ConnectionMapBuilder import ConnectionMapBuilder from .DBConnectionBuilder import DBConnectionBuilder
1610529
from flask import Flask, render_template from flask_nav import Nav from flask_nav.elements import * nav = Nav() # registers the "top" menubar nav.register_element( 'top', Navbar( View('Widgits, Inc.', 'index'), View('Our Mission', 'about'), Subgroup('Products', View('W...
1610622
from typing import Optional import numpy as np import scipy.special as sp from arch.univariate.distribution import GeneralizedError as GE from scipy.stats import gamma from ._base import DistributionMixin, _format_simulator class GeneralizedError(GE, DistributionMixin): def __init__(self, random_state=None): ...
1610696
import json import tests import turing import pytest from urllib3_mock import Responses responses = Responses('requests.packages.urllib3') @responses.activate @pytest.mark.parametrize('num_projects', [10]) def test_list_projects(turing_api, projects, use_google_oauth): responses.add( method="GET", ...
1610714
import os import re import subprocess import sys from functools import partial from threading import Thread from gooey.gui import events from gooey.gui.pubsub import pub from gooey.gui.util.casting import safe_float from gooey.gui.util.taskkill import taskkill from gooey.util.functional import unit, bind ...
1610732
import os import sys import warnings from eth_tester.utils.module_loading import ( get_import_path, import_string, ) from .mock import ( # noqa: F401 MockBackend, ) from .pyethereum.v16 import ( PyEthereum16Backend, is_pyethereum16_available, ) from .pyethereum.v20 import ( PyEthereum21Backe...
1610733
from typing import List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app import crud from app.api.utils.db import get_db from app.api.utils.security import get_current_active_user from app.db_models.user import User as DBUser from app.models.item import Item, ItemCreat...
1610735
import robotoc_sim import pybullet class ANYmalSimulator(robotoc_sim.LeggedSimulator): def __init__(self, path_to_urdf, time_step, start_time, end_time): super().__init__(path_to_urdf, time_step, start_time, end_time) @classmethod def get_state_from_pybullet(self, pybullet_robot, q, v): #...
1610741
import unittest import tempfile import shutil from os import path from symstore import cab from tests.cli import util class TestNewStore(util.CliTester): """ Test publishing files to a new symstore. """ def setUp(self): self.recordStartTime() # set test's symstore path to a non-exist...
1610748
import numpy as np import random class rps_game(): def __init__(self): self.number_of_players = 2 #self.state = np.zeros(2) self.reward = np.zeros(2) self.done = False def step(self, action): #self.state = action#np.array((action[0]*action[1],action[0]*action[1])) ...
1610785
from gym_kuka_mujoco.utils.kinematics import * from gym_kuka_mujoco.utils.quaternion import subQuat, mat2Quat import os import mujoco_py def test_forwardKinPosJacobian(): # Build the model path. model_filename = 'full_kuka_no_collision.xml' model_path = os.path.join('..', '..', 'envs', 'assets', model_fi...
1610807
from django.core.management.base import BaseCommand, CommandError from api import models import sys def generate_release_dates(opt): cards = models.Card.objects.all().order_by('id') release_date = None for card in cards: if card.release_date: release_date = card.release_date els...
1610923
from __future__ import annotations import atexit import copy import dataclasses import enum import json import logging import os import sys import time import tkinter from pathlib import Path from tkinter import messagebox, ttk from typing import Any, Callable, Iterator, List, Type, TypeVar, overload import dacite fr...
1610942
from setuptools import setup setup( name="querystring_parser", version="1.2.4", description="QueryString parser for Python/Django that correctly handles nested dictionaries", author="bernii", author_email="<EMAIL>", url="https://github.com/bernii/querystring-parser", packages=["que...
1610988
import torch import torch.nn as nn from torch.autograd import Function from torch.autograd.function import once_differentiable from . import feature_refine_cuda class FeatureRefineFunction(Function): @staticmethod def forward(ctx, features, best_rbboxes, spatial_scale, points=1): ctx.spatial_scale = ...
1611039
import sys import h5py import torch from torch import nn from torch import cuda import string import re from collections import Counter import numpy as np def to_device(x, gpuid): if gpuid == -1: return x.cpu() if x.device != gpuid: return x.cuda(gpuid) return x def has_nan(t): return torch.isnan(t).sum() == ...
1611042
import os from typing import List from pydantic import BaseModel from rdkit import Chem from copy import deepcopy from icolos.utils.execute_external.omega import OMEGAExecutor from icolos.core.workflow_steps.step import _LE, _CTE from icolos.utils.general.molecules import get_charge_for_molecule from icolos.core.cont...
1611053
import pytest from thefuck.types import Command from thefuck.rules.brew_uninstall import get_new_command, match @pytest.fixture def output(): return ("Uninstalling /usr/local/Cellar/tbb/4.4-20160916... (118 files, 1.9M)\n" "tbb 4.4-20160526, 4.4-20160722 are still installed.\n" "Remove all...
1611056
import torch from torch_scatter import scatter_add from torch_geometric.utils import softmax from ..inits import reset class GlobalAttention(torch.nn.Module): r"""Global soft attention layer from the `"Gated Graph Sequence Neural Networks" <https://arxiv.org/abs/1511.05493>`_ paper .. math:: \ma...
1611108
from direct.distributed.DistributedObjectGlobalUD import DistributedObjectGlobalUD from direct.directnotify import DirectNotifyGlobal class PCPlayerFriendsManagerUD(DistributedObjectGlobalUD): notify = DirectNotifyGlobal.directNotify.newCategory('PCPlayerFriendsManagerUD') def __init__(self, air): Dis...
1611114
import asyncio import os import signal import time from dataclasses import dataclass, field from typing import Any, List, Optional import gevent import gevent.util import structlog from gevent._tracer import GreenletTracer from gevent.hub import Hub from raiden.exceptions import RaidenUnrecoverableError LIBEV_LOW_PR...
1611117
from __future__ import print_function import csv import json import io import re from collections import namedtuple try: from shutil import get_terminal_size except ImportError: from .libs.get_terminal_size import get_terminal_size from .utils import encode_str, decode_bytes from .libs import w...
1611118
import numpy as np from biterm.biterm.btm import oBTM from sklearn.feature_extraction.text import CountVectorizer from biterm.biterm.utility import vec_to_biterms, topic_summuary def categorize(tweets_list, number_of_topics=3): # vectorize texts vec = CountVectorizer(stop_words="english") X = vec.fit_tra...
1611133
import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(ROOT_DIR) import numpy as np from embedding_net.models import EmbeddingNet, TripletNet, SiameseNet from tensorflow.keras.callbacks import TensorBoard, LearningRateScheduler from tensorflow.k...
1611145
import torch from torchvision import transforms from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True from utils.utils import * import json import cv2 import copy import numpy as np import os from tool.darknet2pytorch import * from tqdm import tqdm from skimage import measure from argparse import ArgumentPa...
1611200
import argparse import collections import os import os.path import re import sys INDENT = 2 LINE_WRAP_CHARS = ', ' NON_NAME_PATTERN = re.compile(r'[^A-Za-z0-9_]') SCALE_SIZE_PATTERN = re.compile(r'@[0-9]+') Entry = collections.namedtuple('Entry', ['name', 'data', 'cname']) STRUCT_DECL = '''struct {0} {{ {1}{0}(const c...
1611208
import os.path import inspect import sys # completion types. TYPE_IMPORT = '0' TYPE_CLASS = '1' TYPE_FUNCTION = '2' TYPE_ATTR = '3' TYPE_BUILTIN = '4' TYPE_PARAM = '5' def _imp(name, log=None): try: return __import__(name) except: if '.' in name: sub = name[0:name.rfind('.')] ...
1611250
from enum import Enum class Stage(Enum): """ Entrypoint stage """ request = 'request' response = 'response' class Status(Enum): """ Entrypoint result status """ success = 'success' error = 'error' LOGGER_NAME = 'nameko_tracer' """ Name of the logger used for entrypoint logging Use...
1611263
import datetime import logging from abc import ABCMeta import six from defusedxml.lxml import fromstring from onelogin.saml2.utils import OneLogin_Saml2_Utils from core.exceptions import BaseError from core.util.datetime_helpers import from_timestamp, utc_now class SAMLFederatedMetadataValidationError(BaseError): ...
1611360
import tvm import numpy as np dtype = "float32" A = tvm.te.placeholder([4, 4], dtype=dtype, name="A") B = tvm.te.compute([4, 4], lambda i, j: A[i, j] + 1, name="B") C = tvm.te.compute([4, 4], lambda i, j: A[i, j] * 2, name="C") target = "llvm" s1 = tvm.te.create_schedule(B.op) s2 = tvm.te.create_schedule(C.op) ...
1611370
import resnet2 as net import numpy as np import cv2 import scipy.io as sio import os from os import listdir import random def Average(inp): a = inp/np.linalg.norm(inp, axis=1, keepdims=True) a = np.sum(a, axis=0) a = a/np.linalg.norm(a) return a path = r'O:\[FY2017]\MS-Challenges\code\evaluation_a...
1611393
import pytest from tests.common import get_response @pytest.mark.asyncio async def test_titlehub_titlehistory(aresponses, xbl_client): aresponses.add( "titlehub.xboxlive.com", response=get_response("titlehub_titlehistory") ) ret = await xbl_client.titlehub.get_title_history(987654321) await x...
1611420
import os from pathlib import Path from typing import List, Tuple from sklearn.model_selection import train_test_split from termcolor import colored from deepclustering import DATA_PATH from deepclustering.augment import SequentialWrapper from deepclustering.dataset.segmentation import ( MedicalImageSegmentationD...
1611431
from __future__ import division from nose.tools import * import numpy as np import causalinference.causal as c from utils import random_data def test_est_propensity(): D = np.array([0, 0, 0, 1, 1, 1]) X = np.array([[7, 8], [3, 10], [7, 10], [4, 7], [5, 10], [9, 8]]) Y = random_data(D_cur=D, X_cur=X) causal = c....
1611476
import os from typing import List, NamedTuple import numpy as np import torch from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from mcp.config.evaluation import BestWeightsMetric from mcp.data.dataloader.dataloader import DataLoader, FewShotDataLoader from mcp.model.base import Mode...
1611487
import numpy from shapely.geometry import Point import geopandas def simulated_geo_points(in_data, needed, seed) -> geopandas.GeoDataFrame: """ Simulate points using a geopandas dataframse with geometry as reference. Parameters ---------- in_data: geopandas.GeoDataFrame the geodataframe c...
1611504
from __future__ import division, print_function from .json_ import ParseJson from .nested_dict import SelectFromNestedDict from .unique_id import AssignUniqueId
1611514
import gym import gym.spaces import numpy as np class NormalizeActionSpace(gym.ActionWrapper): """Normalize a Box action space to [-1, 1]^n.""" def __init__(self, env): super().__init__(env) assert isinstance(env.action_space, gym.spaces.Box) self.action_space = gym.spaces.Box( ...
1611550
from django import forms from django.conf import settings from django.core.mail import send_mail from .models import CorporateMember class CorporateMemberSignUpForm(forms.ModelForm): amount = forms.IntegerField( label='Donation amount', help_text='Enter an integer in US$ without the dollar sign.'...
1611606
from hypothesis import strategies from gon.base import Vector from tests.strategies import (angles, coordinates_strategies, coordinates_to_points, coordinates_to_vectors, invalid_points, ...
1611619
import math import random import matplotlib.pyplot as plt import numpy as np from collections import deque, namedtuple from PIL import Image from th10.game import TH10 from config import * import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as ...
1611637
from mvc.controllers.ddpg import DDPGController class SACController(DDPGController): def _register_metrics(self): self.metrics.register('step', 'single') self.metrics.register('pi_loss', 'queue') self.metrics.register('v_loss', 'queue') self.metrics.register('q1_loss', 'queue') ...
1611645
from linked_list_class import LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending order - Recursively divide the linked list into sublists containing a single node -Repeatedly merge the sublists to produce sorted sublists until one remains Returns a sorted linked list ...
1611667
from argparse import ArgumentParser import statistics import os import re import matplotlib.pyplot as plt def get_avg_from_file(file_path): with open(file_path) as f: avg_line = f.readlines()[-1] match = re.match(r"Avg: (.*)", avg_line) return float(match.group(1)) def get_stdev_from_file...
1611684
import torch from torch.nn import Parameter import torch.nn.functional as F from src.inits import glorot, zeros class DenseGSDNEFConv(torch.nn.Module): def __init__(self, in_channels, out_channels, alpha, K, improved=False, bias=True): super(DenseGSDNEFConv, self).__init__() self.in_channels = in...
1611697
from __future__ import division import pytest from pandas import Interval import pandas.util.testing as tm class TestInterval(object): def setup_method(self, method): self.interval = Interval(0, 1) def test_properties(self): assert self.interval.closed == 'right' assert self.interval...
1611701
import copy import json from collections import OrderedDict import warnings def getdictorlist(crawler, name, default=None): value = crawler.settings.get(name, default) if value is None: return {} if isinstance(value, str): try: return json.loads(value, object_pairs_hook=Ordered...
1611750
from .. import register_map from pynwb.icephys import SweepTable, VoltageClampSeries, IntracellularRecordingsTable from hdmf.common.io.table import DynamicTableMap from hdmf.common.io.alignedtable import AlignedDynamicTableMap from .base import TimeSeriesMap @register_map(SweepTable) class SweepTableMap(DynamicTable...
1611782
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( js_to_json, remove_end, determine_ext, ) class HellPornoIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?hellporno\.(?:com/videos|net/v)/(?P<id>[^/]+)' _TESTS = [{ 'url': 'http:/...
1611813
class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: bfs, t, m, n = [(i, j) for i, row in enumerate(grid) for j, val in enumerate(row) if val == 2], 0, len(grid), len(grid[0]) while bfs: new = [] for i, j in bfs: for x, y in ((i - 1, j), (i ...
1611863
import asyncio from collections.abc import Iterable from functools import partial import zmq from aiozmq import create_zmq_connection from .base import ( NotFoundError, ParametersError, Service, ServiceClosedError, _BaseProtocol, _BaseServerProtocol, ) from .log import logger async def conn...
1611945
from django.urls import path, include from django.views.static import serve from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = [ path("", include("autodo.urls")), path("static/", serve, {"document_root": settings.STATIC_ROOT}), path("admin/", admin.site.ur...
1611962
import mxnet as mx import mxnet.gluon.nn as nn def get_shape(x): if isinstance(x, mx.nd.NDArray): return x.shape elif isinstance(x, mx.symbol.Symbol): _, x_shape, _ = x.infer_shape_partial() return x_shape[0] class Dense(nn.HybridBlock): def __init__(self, output, drop_rate=0, a...
1611994
from tests.test_actions import * from ltk.actions.filters_action import * import unittest from io import StringIO import sys from unittest.mock import patch import re class TestFilters(unittest.TestCase): @classmethod def setUpClass(cls): create_config() @classmethod def tearDownClass(cls): ...
1612050
import os def parseargs(p): """ Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser """ p.set_defaults(func=func) p.description = "Create the DIRECTORY(ies), if they do not already " + "exist." p.add_argument("directory", nargs="+") p.add_argument( ...
1612057
import shlex import subprocess from django.core.management.base import BaseCommand from django.utils import autoreload # Celery autoreload workaround inspired by: # https://avilpage.com/2017/05/how-to-auto-reload-celery-workers-in-development.html def restart_celery(): cmd = "pkill -9 celery" subprocess....
1612075
import asyncio import logging """ Buffering event queue with merging of events. """ class EventQueue: def __init__(self, callback): self._callback = callback self._events = [] self._loop = asyncio.get_event_loop() self._timer = None self._start = 0 self._chain = as...
1612093
from rest_framework.exceptions import ValidationError from rest_framework.fields import UUIDField from open.core.betterself.models.activity import Activity from open.core.betterself.models.activity_log import ActivityLog from open.core.betterself.serializers.mixins import ( BaseCreateUpdateSerializer, BaseMode...
1612140
import jinja2 import flask_themes2 def get_global_theme_template(cache): @cache.memoize() def _get_templatepath(theme, templatename, fallback): templatepath = '_themes/{}/{}'.format(theme, templatename) if (not fallback) or flask_themes2.template_exists(templatepath): return templa...
1612171
from ..service import Service from ..exception import AppwriteException class Avatars(Service): def __init__(self, client): super(Avatars, self).__init__(client) def get_browser(self, code, width = None, height = None, quality = None): """Get Browser Icon""" if code is None: ...
1612184
from datetime import datetime import pytest from pytest import approx import msise00 def test_past(): t = datetime(2013, 3, 31, 12) altkm = 150.0 glat = 65.0 glon = -148.0 try: atmos = msise00.run(t, altkm, glat, glon) except ConnectionError: pytest.skip("unable to download R...
1612189
import json from ...plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format'] def format_body(self, body: str, mime: str) -> str: maybe_json = [ 'json...