id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3270719 | import torch
import torch.nn as nn
from torch import optim
from graphgallery.nn.models import TorchEngine
from graphgallery.nn.models.pytorch.graphat.utils import *
from graphgallery.nn.layers.pytorch import GCNConv, Sequential, activations
from graphgallery.nn.metrics.pytorch import Accuracy
class DGAT(To... |
3270750 | extract_options_exportFormat = "FieldViewXDB_1.0"
extract_options_writeUsingGroups = 0;
extract_options_writeGroupSize = 1;
def extract_set_options(fmt, writeUsingGroups, groupSize):
extract_options_exportFormat = fmt
extract_options_writeUsingGroups = writeUsingGroups
extract_options_writeGroupSize = grou... |
3270783 | import os
import logging
from flask import Flask
from flask_restful import Api
from jaeger_client import Config
from flask_opentracing import FlaskTracer
from tracingexample.tracer_helper2 import TracerHelper2
logging.getLogger('').handlers = []
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
flask_app... |
3270788 | import datetime
import unittest
import lxml.etree
from clarify.parser import (Parser, ResultJurisdiction)
class TestParser(unittest.TestCase):
def test__underscore_to_camel(self):
self.assertEqual(Parser._underscore_to_camel(""), "")
self.assertEqual(Parser._underscore_to_camel("test"), "test")... |
3270848 | import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings("ignore")
if __name__== "__main__":
df_heart = p... |
3270906 | from os import environ
def assert_in(file, files_to_check):
if file not in files_to_check:
raise AssertionError("{} does not exist in the list".format(str(file)))
return True
def assert_in_env(check_list: list):
for item in check_list:
assert_in(item, environ.keys())
return True
|
3270907 | import enum
class PositionMode(enum.Enum):
KEYFRAME = 'KEYFRAME'
SEGMENT = 'SEGMENT'
TIME = 'TIME'
|
3270910 | import pytest
import time
@pytest.fixture(scope="function")
def app(request):
from pyble import backend
print ""
app = backend.load(shell=False)
while not app.isReady():
pass
return app
@pytest.fixture(scope="function")
def app_noshell(request):
from pyble import backend
print "... |
3270911 | import random as rd
import csv
import argparse
rd.seed(2020)
def read_txt(filename):
dataset = []
with open(filename, 'r', encoding="utf-8", newline='') as f:
for line in f.readlines():
label = line[0]
doc = line[1:].strip()
dataset.append((label, doc))
... |
3270931 | from unittest import TestCase
from unittest.mock import patch
import pytest
from hubblestack.audit import win_auditpol
from hubblestack.exceptions import HubbleCheckValidationError
class TestWinAuditpol(TestCase):
"""
Unit tests for win_auditpol module
"""
def test_invalid_params1(self):
"""... |
3270939 | from django.contrib.auth.base_user import BaseUserManager
class CMSUserManager(BaseUserManager):
def get_queryset(self):
return super(CMSUserManager, self).get_queryset().filter(is_staff=True)
def create(self, **kwargs):
kwargs.update({'is_staff': True})
return super(CMSUserManager, s... |
3270945 | import numpy as np
from sklearn.cluster import KMeans
def ClosestCenter(point, centroids):
# Find the closest center over all centroids
min_index = -1
min_dist = float('inf')
for i in range(len(centroids)):
center = centroids[i]
dist_cur = np.linalg.norm(point - center)
if dist... |
3270961 | import unittest
import inspect
import six
from mock import Mock, patch
class TestWhereIs(unittest.TestCase):
def test_where_is_positive(self):
expected_filename = "navigate.py"
expected_line_no = 17
from extdbg import where_is
location = where_is(where_is)
self.assertTr... |
3271050 | import re
from dcicutils.misc_utils import ignored, is_valid_absolute_uri
from jsonschema_serialize_fork import FormatChecker
from pyramid.threadlocal import get_current_request
from .server_defaults import (
ACCESSION_FACTORY,
ACCESSION_PREFIX,
ACCESSION_TEST_PREFIX,
test_accession,
)
ACCESSION_CODE... |
3271081 | import sys
from rpython.rtyper.lltypesystem import rffi
from rpython.translator.tool.cbuild import ExternalCompilationInfo
from rpython.jit.backend.x86.arch import WORD
if WORD == 4:
extra = ['-DPYPY_X86_CHECK_SSE2']
if sys.platform != 'win32':
extra += ['-msse2', '-mfpmath=sse']
else:
extr... |
3271095 | import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
diracs = np.eye(3)
uniform = np.ones(3)/3
centered_diracs = diracs - uniform
corners2d = np.array([[0, 2/np.sqrt(6)],
[-np.sqrt(2)/2, -1/np.sqrt(6)],
[np.sqrt(2)/2, -1/np.sqrt(6)],])
corners2d /... |
3271114 | from random import Random
from eth2spec.test.context import (
with_all_phases,
spec_test,
spec_state_test,
with_custom_state,
single_phase,
low_balances, misc_balances,
)
import eth2spec.test.helpers.rewards as rewards_helpers
from eth2spec.test.helpers.random import (
randomize_state,
... |
3271117 | import numpy as np
import scipy.constants as cst
from scipy.interpolate import interp1d
import os
def laser_gain_step(J_in, g_in):
"""
Computes one iteration of Frantz-Nodvik gain simulation,
and returns the output normalised fluence and the gain left
in the crystal.
J is a number, g is a number
... |
3271140 | from sensei import *
from vtk import VTK_MULTIBLOCK_DATA_SET, vtkDataObject, VTK_IMAGE_DATA, VTK_DOUBLE, VTK_FLOAT
# test setting and getting the members
md = MeshMetadata.New()
md.GlobalView = True
md.MeshName = "foo"
md.MeshType = VTK_MULTIBLOCK_DATA_SET
md.BlockType = VTK_IMAGE_DATA
md.NumBlocks = 2
md.NumBlocksLoc... |
3271147 | import pandas as pd
from data.sql.sql_syntax import SqlSyntax
import data.labels as lb
import numpy as np
from data.config_reader import config_reader
from typing import List, Dict, Tuple
def get_min_avg_prices(data_start,
data_stop,
sql,
market):
rows = sql.select_min_... |
3271157 | import os
import unittest
from programytest.client import TestClient
class FileMapAIMLTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_storage(self):
super(FileMapAIMLTestClient, self).load_storage()
self.add_default_stores()
self.add_categories... |
3271200 | from collections import namedtuple
import math
import sys
from morton import Morton
try:
from shapely import geometry as shapely_geometry
except ImportError:
shapely_geometry = None
Point = namedtuple('Point', ['x', 'y'])
def is_point_on_line(point, start, end):
if start.x <= point.x and point.x <= end.... |
3271203 | from einsteinpy.symbolic import constants, get_constant
def test_get_constant():
c1 = constants.c
c2 = get_constant("c")
assert c1 - c2 == 0
def test_SymbolicConstant_descriptive_name():
ld = constants.Cosmo_Const
assert ld._descriptive_name == ld.descriptive_name
|
3271212 | from smartystreets_python_sdk.us_zipcode import Result
from smartystreets_python_sdk import Request, Batch
class Client:
def __init__(self, sender, serializer):
"""
It is recommended to instantiate this class using ClientBuilder.build_us_zipcode_api_client()
"""
self.sender = sende... |
3271238 | class DriverError(Exception):
"""Base class for driver-specific errors."""
class ConnectionFailed(DriverError):
"""A Connection error occurred."""
class Timeout(DriverError):
"""The request timed out."""
|
3271289 | from nixui.utils import cache
from nixui.options import parser, nix_eval
import base64
import json
import os
import requests
import tempfile
import re
from github import Github, UnknownObjectException
@cache.cache()
def get_repos_blob_urls(access_token, repo_name):
g = Github(access_token)
user, repo = repo... |
3271316 | import asyncio
import logging
import hummingbot.connector.derivative.binance_perpetual.constants as CONSTANTS
from typing import Optional
from hummingbot.core.api_throttler.async_throttler import AsyncThrottler
from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker
from hummingbot.core.data_type... |
3271344 | import json
import logging
from datetime import datetime, timedelta
from pipelines.pipeline.task import Task, TaskResult
log = logging.getLogger('pipelines')
def class_name(obj):
if isinstance(obj, type):
return obj.__name__
if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
... |
3271356 | import numpy as np
import tensorflow as tf
from config import FLAGS
class RNN(object):
def __init__(self, train=True, ru=False):
with tf.variable_scope("RNN_Network", reuse=ru):
with tf.name_scope("Placeholders"):
self.decoder_input = tf.placeholder(tf.int32,
... |
3271436 | import random
import string
from sqlalchemy import and_
from app.lib.models.api import ApiKeys
from app import db
class ApiManager:
def __init__(self, sessions):
self.sessions = sessions
def create_key(self, user_id, name):
if len(name) == 0:
return False
key = ''.join(ra... |
3271537 | from .rcnn_heads import ORCNNROIHeads
from .mask_heads import (
build_amodal_mask_head,
build_visible_mask_head
)
from .pooler import ROIPooler
|
3271568 | import sys
from rich.traceback import install
from best_buy_bullet_bot.command_line import run_command
def main():
# Stylizes errors and shows more info
install()
try:
run_command()
except KeyboardInterrupt:
# This way we don't get the keyboardinterrupt traceback error
sys.e... |
3271570 | import json
import time
import urllib2
from collections import OrderedDict
from threading import Lock
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
with open("key.txt") as f:
key = f.read()
regionToLocationMap = {
"br" : "br1",
"eune" : "eun1",
... |
3271598 | from django.contrib.sites.models import Site
def get_site_context():
site: Site = Site.objects.get_current()
site_context = {
"domain": site.domain,
"site_name": site.name,
}
return site_context
|
3271630 | print authentication.name;
for authority in authentication.authorities:
print authority
print "Granting access"
allow = 1
|
3271664 | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
from veriloggen import *
def mkLed():
m = Mod... |
3271697 | from decimal import Decimal, getcontext, InvalidOperation
DEFAULT_PRECISION = 28 # 28 is python 3 default
DEFAULT_OUTPUT_PRECISION = 2 # default precision for human readable output
# set decimal precision globally
getcontext().prec = DEFAULT_PRECISION
PRECISIONS = {
'ETH': '5',
'BTC': '5',
}
def remove_... |
3271701 | from django.db import models
from accounts.utils import get_robot_user, is_robot_user
class AnnotationManager(models.Manager):
def update_point_annotation_if_applicable(
self, point, label, now_confirmed, user_or_robot_version):
"""
Update a single Point's Annotation in the database.... |
3271738 | from json import loads, dumps
from typing import Dict, List, Union
from django.db.models import Model, Max
from rest_framework.serializers import Serializer
from imblearn.pipeline import Pipeline
from apps.analysis_and_training.main.significant_terms import (
MarkUpEntities,
BugResolutions,
)
from apps.extrac... |
3271743 | from rest_framework import serializers
from nablapps.qrTickets.models import QrTicket
class QrTicketSerializer(serializers.ModelSerializer):
class Meta:
model = QrTicket
fields = ["registered"]
lookup_field = "ticket_id"
|
3271751 | from unittest import mock
import pytest
from broqer import Value, Publisher, Subscriber, Sink, op
import operator
def test_operator_with_publishers():
v1 = Value(0)
v2 = Value(0)
o = v1 + v2
assert isinstance(o, Publisher)
assert isinstance(o, Subscriber)
assert o.get() == 0
v1.emit(1)
... |
3271752 | import datetime
import os
import pytest
from django.test import override_settings
from django.urls import reverse
from rest_framework.test import APIClient
from .models import FilingList, Filing, Holding
from .factory import (
FilingFactory,
FilingListFactory,
HoldingFactory,
CikFactory,
CusipFact... |
3271777 | from PySide2.QtWidgets import QToolTip
from PySide2.QtWidgets import QMenu
from PySide2.QtGui import QCursor
class Menu(QMenu):
def __init__(self, title, parent='None'):
pass
def handleMenuHovered(self, action):
pass
staticMetaObject = None
|
3271778 | import unittest
from boost_collections.zskiplist.zskiplist_ex import ZskiplistEx
class TestZskiplist(unittest.TestCase):
def setUp(self):
self.zsl = ZskiplistEx()
self.zsl.zsl_insert(10, 'a')
self.zsl.zsl_insert(5, 'b')
def test_zsl_length(self):
zsl = self.zsl
lengt... |
3271804 | class VarSimuError(Exception):
pass
def generate_simulation_list(self, ref_simu=None):
"""Generate all the simulation for the multi-simulation
Parameters
----------
self : VarSimu
A VarSimu object
ref_simu : Simulation
Reference simulation to copy / update
Returns
---... |
3271847 | import os
from abc import ABCMeta
from functools import (
singledispatch,
update_wrapper,
)
PY36 = (3, 6) <= os.sys.version_info < (3, 7)
PY37 = (3, 7) <= os.sys.version_info < (3, 8)
if PY36: # pragma: no cover
from typing import GenericMeta
class GenericABCMeta(GenericMeta, ABCMeta):
""... |
3271858 | import numpy as np
import os
import glob
import xyz_to_clmb as clb
mol_name = [ ]
rev_list = [ ]
for_list = [ ]
ts_list = [ ]
ma = 100
pr, re, ts, nam = [], [], [], []
for f in glob.glob("*.xyz"):
if "rev" in f:
current_split_list = f.split("_")
current_num = str(current_split_list[1])
mol_name = np.array(cu... |
3271870 | from typing import Union
from jsondb.db import Database
from ..crypto import blake160
from ..crypto import generate_private_key
from ..crypto import get_account_id_from_public
from ..crypto import get_public_from_private
from ..crypto import sign_ecdsa
from .errors import ErrorCode
from .errors import KeystoreError
f... |
3271872 | import noteql
import click
@click.command()
@click.option("--tag", default="", help="tag name to extract xml")
@click.option("--table", default="", help="tablename")
@click.option("--schema", default="", help="schema")
@click.option("--field", default="", help="fieldname in table")
@click.option("--dburi", default=""... |
3271892 | from typing import Dict
from typing import List
from botocore.paginate import Paginator
class GetClassifiers(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`Glue.Client.get_classifiers`.
See ... |
3271899 | from socket import *
import random
import time
def server(address):
sock = socket(AF_INET, SOCK_STREAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
while True:
client, addr = sock.accept()
handler(client, addr)
def handler(client, address):
ti... |
3271917 | def add_resource(curr_path, curr_hash, node_uuid):
return ("RESOURCE_ADD", {
"node_uuid": node_uuid,
"curr_path": curr_path,
"curr_hash": curr_hash
})
|
3271923 | import unittest
import torch
from bnn_priors.data import UCI, MNIST, RotatedMNIST, CIFAR10, CIFAR10_C
class _TestDataSet():
def test_shape(self):
assert self.data.norm.X.shape[-len(self.data.in_shape):] == self.data.in_shape
assert self.data.norm.X.shape[0] == self.data.norm.y.shape[0]
a... |
3271927 | import os
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn.modules.loss
def format_metrics(metrics, split):
"""Format metric in metric dict for logging."""
return " ".join(
["{}_{}: {:.8f}".format(split, metric_name, metric_val) for metric_name, metric_val in metric... |
3271932 | import glob
import json
import os
from ozeu.utils.coco import CocoDatasetBuilder
import subprocess
import tempfile
from collections import deque
from os.path import join
import click
import cv2
import numpy as np
import tqdm
import yaml
from ozeu.detection.instance_segmentation import InstanceSegmenter
from ozeu.segme... |
3271935 | from flask import Flask, jsonify, abort, request, make_response
import requests
import json
import time
import datetime
import threading
import os
import sys
import function as fogflow
app = Flask(__name__, static_url_path='')
scorpioBrokerURL = ''
outputs = []
input = {}
scorpioIp = ''
brokerURL = ''
@app.errorh... |
3271939 | CONNECTION_TIMEOUT_SECONDS = 1 * 60 * 60 # Skill debug connection time to live. Set to 1 hour.
PING_INTERVAL_SECONDS = 5 * 60 # Ping duration interval set to 5 minutes.
|
3271949 | from abstract import *
from costar_task_plan.abstract import *
# This connects two different decision points.
class MctsAction(AbstractMctsAction):
penalty = -1e6
def __init__(self, policy=None, id=0, ticks=10, condition=None, tag=None, *args, **kwargs):
super(MctsAction, self).__init__(*args, **kw... |
3272032 | import gfapy
import unittest
class TestGraphopCopyNumber(unittest.TestCase):
def test_delete_low_coverage_segments(self):
for sfx in ["gfa", "gfa2"]:
gfa = gfapy.Gfa.from_file("tests/testdata/copynum.1.{}".format(sfx))
self.assertEqual({"0","1","2"}, set(gfa.segment_names))
gfa.delete_low_cove... |
3272042 | import torch
from ... import cplx
from ..modules.linear import CplxLinear, CplxBilinear
from ..modules.conv import CplxConv1d, CplxConv2d, CplxConv3d
from .base import BaseMasked, MaskedWeightMixin
from ..utils.sparsity import SparsityStats
class _BaseCplxMixin(MaskedWeightMixin, BaseMasked, SparsityStats):
_... |
3272057 | from typing import Union, Optional
import pytest
import scanpy as sc
import cellrank.external as cre
from anndata import AnnData
from cellrank.tl.kernels import ConnectivityKernel
from cellrank.external.kernels._utils import MarkerGenes
from cellrank.external.kernels._wot_kernel import LastTimePoint
import numpy as ... |
3272061 | import numpy as np
import csv
import copy
def parse_csv(file_name: str, column_order=[]):
tot = []
if isinstance(file_name, str):
csvfile = open(file_name, encoding="utf-8-sig")
else:
csvfile = file_name
contents = csv.reader(csvfile, delimiter=",", quotechar='"')
for row in conte... |
3272077 | from typing import Tuple, Union
urwid_Fixed = Tuple[()]
urwid_Flow = Tuple[int]
urwid_Box = Tuple[int, int]
urwid_Size = Union[urwid_Fixed, urwid_Flow, urwid_Box]
|
3272096 | import time
import unittest
from inoft_vocal_engine.audio_editing.audioclip import AudioBlock
from inoft_vocal_engine.speech_synthesis.polly.client import PollyClient
from inoft_vocal_engine.speech_synthesis.polly import VOICES
"""
river_track = Track(is_primary=False, loop_until_primary_tracks_finish=True)
... |
3272102 | import argparse
import json
import math
from argparse import RawTextHelpFormatter
from leaderboard.utils.checkpoint_tools import fetch_dict
import carla
import os
SCENARIO_COLOR = {
"Scenario1": [carla.Color(255, 0, 0), "Red"], # Red
"Scenario2": [carla.Color(0, 255, 0), "Green"], # Green
"Sc... |
3272123 | import logging
from abc import ABC, abstractmethod
class Base(ABC):
name = None
aliases = []
bot = None
@abstractmethod
def execute(self, command):
pass
def reply(self, command, text, parse_mode=None, disable_web_page_preview=True):
logging.debug(f"Reply to command [{command}... |
3272157 | from enum import Enum
class UserRole(Enum):
ALL = "all"
MANAGER = "manager"
PROOFREADER = "proofreader"
TRANSLATOR = "translator"
BLOCKED = "blocked"
|
3272161 | from setuptools import setup, find_packages
setup(
name='OptimalPortfolio',
version='0.0.1',
packages=find_packages(),
url='https://github.com/VivekPa/OptimalPortfolio',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Portfolio Optimisation and Analytics Library',
... |
3272181 | import torch
import torch.nn as nn
import torchvision
import numpy as np
from torch.nn import init
from torch.nn import functional as F
from torch.autograd import Function
import math
from math import sqrt
import random
class InvSigmoid(nn.Module):
def __init__(self):
super().__init__()
def forw... |
3272192 | import FWCore.ParameterSet.Config as cms
from PhysicsTools.Utilities.pileupFilter_cfi import *
pileupFilter.pileupInfoSummaryInputTag = cms.InputTag("addPileupInfo")
pu20to25 = pileupFilter.clone()
pu20to25.minPU = cms.double(20)
pu20to25.maxPU = cms.double(25)
pu25to30 = pileupFilter.clone()
pu25to30.minPU = cms.d... |
3272269 | import json
fh = open("tests/integration/fixtures/evidence.json")
EVENT_FIXTURE = json.loads(fh.read())
fh.close()
class TestEvidenceProcessor(object):
def test_processing_evidence(self):
from lambda_handler.pcap import Analyze
if EVENT_FIXTURE["detail"]["remediation"]["evidence"]["objects"] != ... |
3272299 | import dataclasses
import json
import logging
import os
import time
import yaml
from consul import Timeout
from typing import Any, Dict, List, Set, Tuple
from web3 import HTTPProvider, Web3
from web3.exceptions import MismatchedABI
from web3.middleware import geth_poa_middleware
from polyswarmdconfig.config import Co... |
3272306 | from routeros_api import exceptions
class ExceptionAwareApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
self.exception_handlers = []
def send(self, *args, **kwargs):
try:
return self.inner.send(*args, **kwargs)
except exceptions.RouterOsApiEr... |
3272319 | from dataclasses import dataclass
from rxbp.flowable import Flowable
from rxbp.init.initsubscriber import init_subscriber
from rxbp.multicast.init.initmulticastsubscription import init_multicast_subscription
from rxbp.multicast.mixins.multicastmixin import MultiCastMixin
from rxbp.multicast.multicastobservables.fromfl... |
3272399 | import networkx as nx
import numpy as np
from autode.log import logger
from autode.mol_graphs import is_isomorphic
def get_sum_energy_mep(saddle_point_r1r2, pes_2d):
"""
Calculate the sum of the minimum energy path that traverses reactants (r)
to products (p) via the saddle point (s)::
... |
3272400 | ETH_GATEWAY_STATS_INTERVAL = 60
ETH_GATEWAY_STATS_LOOKBACK = 1
ETH_ON_BLOCK_FEED_STATS_INTERVAL_S = 5 * 60
ETH_ON_BLOCK_FEED_STATS_LOOKBACK = 1
|
3272419 | import numpy as np
from nmtvis.EmbeddingVisualizer import visualize_embedding_tsne,visualize_embedding_pca
e=np.load("../data/embeddings.npy").tolist()
v=np.load("../data/vocab.npy").tolist()
visualize_embedding_tsne(e,v,3)
#visualize_embedding_pca(e,v,3)
|
3272432 | from problog import get_evaluatable
from problog.program import PrologString
from problog.engine import DefaultEngine
from problog.logic import Term
p = PrologString("""
coin(c1). coin(c2).
0.4::heads(C); 0.6::tails(C) :- coin(C).
win :- heads(C).
evidence(heads(c1), false).
query(win).
""")
engine = DefaultEngine()
... |
3272434 | import torch as T
from . import root_logger
__all__ = ['time_cuda_module', 'slack_message']
def time_cuda_module(f, *args, **kwargs):
"""
Measures the time taken by a Pytorch module.
:param f:
a Pytorch module.
:param args:
arguments to be passed to `f`.
:param kwargs:
k... |
3272452 | import importlib
import tensorflow as tf
import numpy as np
import os
import tensorflow.contrib.layers as layers
def rendering_Net(inputs, masks, height, width, n_layers=12, n_pools=2, is_training=True, depth_base=64):
conv_layers = np.int32(n_layers/2) -1
deconv_layers = np.int32(n_layers/2)
# number of layers be... |
3272469 | import json
from pathlib import Path
from collections import defaultdict
import argparse
from metric_test import Metric
from normalize import normalize
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
def flatten(li):
return [item fo... |
3272503 | import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
from rdp import rdp
from utils import hull
FINGER_NAMES = ["Thumb", "Index", "Middle", "Ring", "Pinky(Little)"]
BONE_NAMES = ["PIP", "DIP", "TIP"]
def count_num_in_convex_hull(points_, convex_hull_):
'''
:param points_: points in... |
3272513 | import os
from itertools import repeat
from os.path import join
import numpy as np
from cogspaces.datasets import fetch_mask
from joblib import Parallel, delayed
from matplotlib.colors import LinearSegmentedColormap, rgb_to_hsv, hsv_to_rgb
from nilearn._utils import check_niimg
from nilearn.datasets import fetch_surf_... |
3272521 | import os
import sys
import time
import datetime
import logging
import shutil
import mumaxc as mc
import subprocess as sp
log = logging.getLogger(__name__)
class MumaxRunner:
"""Base class for running mumax3.
Don't use this directly. Use get_mumax_runner() to pick a subclass
of this class.
"""
... |
3272544 | import multiprocessing as mp
def parse_n_jobs(n_jobs):
if n_jobs > 0:
return n_jobs
elif n_jobs < 0:
return mp.cpu_count() + 1 - n_jobs
else:
return 1
def get_chunks(iterable, chunks=1):
# This is from http://stackoverflow.com/a/2136090/2073595
lst = list(iterable)
re... |
3272566 | import json
import boto3
from botocore.exceptions import ClientError
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.exceptions import UnsupportedAlgorithm
SECRETS_CLIENT = boto3.client('secretsmanager')
def a... |
3272586 | from guy import Guy,http
@http(r"/item/(\d+)")
def getItem(web,number):
web.write( "item %s"%number )
def test_hook_with_classic_fetch(runner):
class T(Guy):
__doc__="""Hello
<script>
async function testHook() {
var r=await window.fetch("/item/42")
return await ... |
3272594 | matrix = []
for x in range(6):
matrix.append([int(x) for x in input().split()])
hourglass = []
for i, row in enumerate(matrix):
if i >= (len(matrix) - 2):
break
for j, e in enumerate(row):
if j >= (len(row) - 2):
break
templist = []
templist = templist + [matri... |
3272654 | from __future__ import division
from yolov3.models import *
from utils.utils import *
from utils.datasets import *
from utils.parse_config import *
from my_models import Network, define_yolo, init_yolo
import os
import sys
import time
import datetime
import argparse
import tqdm
import numpy as np
import torch
from t... |
3272658 | pd.concat([df.groupby(df.city.str.lower())[['sale', 'volume_sold']].sum(),
popn.Population], axis=1, join='inner').pipe(sns.pairplot);
|
3272675 | import argparse
import contextlib
import irods.lib
from irods import database_connect, database_interface
from irods.configuration import IrodsConfig
#--------------------------------------
# update_deprecated_database_columns.py
#
# Several columns in R_DATA_MAIN are obsolete/no longer updated as of 4.2:
# resc_... |
3272689 | from direct.distributed.DistributedObjectAI import DistributedObjectAI
from direct.directnotify import DirectNotifyGlobal
class PVPManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('PVPManagerAI')
def __init__(self, air):
DistributedObjectAI.__init__(self, air) |
3272693 | import time
from ..utils import TestCANToolz
class TestCanControl(TestCANToolz):
def test_ecu_commands_and_firewall(self):
self.CANEngine.load_config('tests/configurations/conf_can_control.py')
self.CANEngine.start_loop()
time.sleep(1)
# Call Door - Front Driver status command.
... |
3272840 | from builtins import object
import numpy as np
import numpy.testing as npt
from relaax.common.rlx_message import RLXMessage
from relaax.common.rlx_message import RLXMessageImage
from PIL import Image
class TestRLXMessage(object):
def test_to_wire_and_back(self):
npar1 = np.array([1.001, 2.002, 3.003], d... |
3272864 | import numpy as np
import paddle
import paddle.nn as nn
from libs.tools import change_default_args
from libs.tools import GroupNorm
from libs.nn import Empty
class RPN(nn.Layer):
def __init__(self,
use_norm=True,
num_class=2,
layer_nums=[3, 5, 5],
... |
3272879 | import os
import hypertune
import tensorflow as tf
class HypertuneHook(tf.train.SessionRunHook):
def __init__(self):
self.hypertune = hypertune.HyperTune()
self.hp_metric_tag = os.environ.get('CLOUD_ML_HP_METRIC_TAG', '')
self.trial_id = os.environ.get('CLOUD_ML_TRIAL_ID', 0)
def end(... |
3272950 | from taskipy.exceptions import MalformedTaskError
class Task:
def __init__(self, task_name: str, task_toml_contents: object):
self.__task_name = task_name
self.__task_command = self.__extract_task_command(task_toml_contents)
self.__task_description = self.__extract_task_description(task_to... |
3272966 | import nn
from optim import get_optimizer
from utils.common import GLOBAL, List, Tuple
import nn.functional as F
import nn.objectives
from utils.toolkit import ProgressBar, format_time, SummaryProfile
import time
import pickle
import utils.data as data
from collections import defaultdict
import core.autograd
class _B... |
3272974 | from typing import Callable, cast
from unittest import mock
import pytest
import werkzeug
from _pytest.fixtures import FixtureRequest
from demo.demo import _run_demo_consumer
from demo.settings import OverhaveDemoSettingsGenerator
from overhave import OverhaveRedisStream
from overhave.db import TestReportStatus
from ... |
3273007 | import logging
import random
import numpy as np
import torch
from fastprogress.fastprogress import progress_bar
from torch.utils.data import DataLoader, SequentialSampler
from transformers import ElectraForSequenceClassification, ElectraTokenizer
logger = logging.getLogger(__name__)
class GrandChallengeTextClassifi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.