id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1710151 | from astropy.coordinates import SkyCoord, Distance
import astropy.units as u
from astropy.time import Time
from astroquery.ned import Ned
from astroquery.simbad import Simbad
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import os
import numpy as np
from spectractor import parameters
from spe... |
1710187 | from django.urls import reverse
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.utils import timezone
from rest_framework import status
from datetime import timedelta
from mock import patch
import random
import string
import binascii
import os
import hashlib
import ti... |
1710189 | import os
import time
from collections import namedtuple
class SourceFile(namedtuple('SourceFile', 'destination source process prefix')):
def __new__(cls, destination, source, process=True, prefix=None):
return super(SourceFile, cls).__new__(cls,
source=source... |
1710194 | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Watchers(models.Model):
"""Watcher objects table"""
wid = models.AutoField(primary_key=True)
name = models.TextField()
class WatcherLogs(models.Model):
"""Watcher logs table"""
class Meta:
unique_togeth... |
1710277 | import json
import os
import six
import time
from sh import chmod
from os_brick.initiator import connector
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
from oslo_utils import netutils
from oslo_utils import units
from twisted.python.filepath import FilePath
impor... |
1710330 | from .util import *
## unify function that will bind variables in the search to their counterparts in the tree
## it takes two pl_expr and try to match the uppercased in lh or lh.domain with their corresponding
## values in rh itself or its domain
def unify(lh, rh, lh_domain = None, rh_domain = None):
if rh_domain... |
1710340 | from api.utils.helpers import stubify
def test_stubify_empty():
"""Stubify logic must return None if it doesn't have a name"""
assert stubify("") is None
assert stubify(" ") is None
|
1710360 | from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(field, css):
class_old = field.field.widget.attrs.get('class', '')
if class_old:
class_new = class_old + ' ' + css
else:
class_new = css
return field.as_widget(attrs={"class": class_new... |
1710399 | import click
import logging
from . import commands
logger = logging.getLogger(__name__)
@click.group(context_settings={"help_option_names": ["--help", "-h"]})
@click.option("--verbose", "-v", is_flag=True, help="Set log level to DEBUG.")
def docketparser_cli(verbose):
"""Parsing structured information from PACE... |
1710402 | import matplotlib.pyplot as plt
import matplotlib.cm as cm
import fiona
# STEP 2
COUNTRIES_POPULATION = {
'Spain': 47.2,
'Portugal': 10.6,
'United Kingdom': 63.8,
'Ireland': 4.7,
'France': 64.9,
'Italy': 61.1,
'Germany': 82.6,
'Netherlands': 16.8,
'Belgium': 11.1,
'Denmark': 5.6... |
1710411 | from twisted.application.service import ServiceMaker
TxFixClient = ServiceMaker(
'txfixclient',
'txfixclient.tap',
'Run the Fix Client service',
'txfixclient'
)
|
1710459 | import numpy as np
import os
import torch
import cv2
from torch.utils.data import Dataset
class OnTheFlySMPLTrainDataset(Dataset):
def __init__(self,
poses_path,
textures_path,
backgrounds_dir_path,
params_from='all',
grey_tex_pr... |
1710484 | import glob,os
dirlist = glob.glob('../data/N_*')
for dirname in dirlist:
flist = glob.glob(dirname+'/20140418_seqs*_d_0.5.dat')
for fname in flist:
print fname
os.remove(fname)
|
1710499 | import unittest
from datetime import datetime
import pandas as pd
import numpy as np
from msticpy.analysis.anomalous_sequence.utils.data_structures import Cmd
from msticpy.analysis.anomalous_sequence import anomalous
class TestAnomalous(unittest.TestCase):
def setUp(self) -> None:
self.sessions1 = [
... |
1710542 | class Console(object):
""" Represents the standard input,output,and error streams for console applications. This class cannot be inherited. """
@staticmethod
def Beep(frequency=None,duration=None):
"""
Beep(frequency: int,duration: int)
Plays the sound of a beep of a specified frequency and duration t... |
1710552 | text = "This is some generic text"
index = 0
while index < len(text):
print(text[index])
index += 1
for character in text:
print(character)
print("\n".join(text))
|
1710553 | import os
from typing import List, Union
import numpy as np
from ConfigSpace.configuration_space import Configuration
from smac.runhistory.runhistory import RunHistory
from cave.analyzer.base_analyzer import BaseAnalyzer
from cave.plot.scatter import plot_scatter_plot
from cave.utils.helpers import get_cost_dict_for_... |
1710560 | from newspaper import Article
from sqlalchemy.orm.exc import NoResultFound
from .base import BaseCrawler
from ...models import Entity, Author, AuthorType
class GenericCrawler(BaseCrawler):
def offer(self, url):
""" Can this crawler process this URL? """
return True
def crawl(self, doc):
... |
1710630 | import unittest
from mox3.mox import MoxTestBase, IsA
import gevent
from gevent.pywsgi import WSGIServer as GeventWSGIServer
from slimta.http.wsgi import WsgiServer, log
class TestWsgiServer(MoxTestBase, unittest.TestCase):
def test_build_server(self):
w = WsgiServer()
server = w.build_server(('... |
1710634 | import multiprocessing
import importlib
import sys
import os
class State:
''' Handles the Unicorn HAT state'''
def __init__(self, is_hd=True):
self._process = None
self.set_model(is_hd)
def set_model(self, is_hd):
self.is_hd = is_hd
if self.is_hd is True:
imp... |
1710652 | import glob
import os
import random
import numpy as np
from PIL import Image
from datasets.BaseDataset import VideoDataset, INFO, IMAGES_, TARGETS
from utils.Resize import ResizeMode
class Davis(VideoDataset):
def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num... |
1710728 | import os
from ..models import DocumentType
from ..permissions import (
permission_document_properties_edit,
permission_document_type_create, permission_document_type_delete,
permission_document_type_edit, permission_document_type_view,
)
from .base import GenericDocumentViewTestCase
from .literals import... |
1710741 | import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 20, 30], 'C': [100, 200, 300]},
index=['One', 'Two', 'Three'])
print(df)
# A B C
# One 1 10 100
# Two 2 20 200
# Three 3 30 300
print(df.reindex(index=['Two', 'Three', 'One']))
# A B C
# Two 2 2... |
1710801 | import numpy as np
import scipy as sp
import matplotlib
matplotlib.use('Agg')
from math import ceil
import matplotlib.pyplot as plt
from sys import exit
from scipy.stats import gaussian_kde
import sklearn
import pandas as pd
from scipy.integrate import simps
sklearn_major_version = float(sklearn.__version__.split('.')[... |
1710818 | def sort_k(arr, k):
arr = sorted(arr[:k]) + arr[k:]
for i in range(k, len(arr)):
start, end = i-k+1, i+1
p, n = arr[:start], arr[end:]
sub = sorted(arr[start:end])
arr = p + sub + n
return arr
# Test
assert sort_k([1, 0, 2, 4, 3], 2) == [0, 1, 2, 3, 4]
|
1710825 | import os
import os.path
from unittest.mock import patch
from programy.rdf.collection import RDFCollection
from programy.storage.stores.file.config import FileStorageConfiguration
from programy.storage.stores.file.config import FileStoreConfiguration
from programy.storage.stores.file.engine import FileStorageEngine
fro... |
1710826 | import gossip
@gossip.register('slash.session_start')
def session_start():
raise KeyboardInterrupt()
def test_1():
pass
|
1710835 | import nltk
from collections import defaultdict
class PcfgEstimator:
"""
Estimates the production probabilities of a PCFG
"""
def __init__(self):
self._counts = defaultdict(nltk.FreqDist)
def add_sentence(self, sentence):
"""
Add the sentence to the dataset
"""... |
1710870 | def pytest_addoption(parser):
parser.addoption("--corpus-file", action="store", default="Corpus to test")
parser.addoption("--morphem-file", action="store", default="Morphem dict to test")
def pytest_generate_tests(metafunc):
option_value = metafunc.config.option.corpus_file
if 'corpus_file' in metafu... |
1710886 | class Topology:
def is_circular(self):
"""
Is the path circular? In this case the number of CIGARs must be
equal to the number of segments.
Returns
-------
bool
"""
return len(self.overlaps) == len(self.segment_names)
def is_linear(self):
"""
Is the path linear? This is th... |
1710889 | import numpy as np
import pytest
import scico.scipy.special as ss
from scico.random import randn
# these are functions that take only a single ndarray as input
one_arg_funcs = [
ss.digamma,
ss.entr,
ss.erf,
ss.erfc,
ss.erfinv,
ss.expit,
ss.gammaln,
ss.i0,
ss.i0e,
ss.i1,
ss... |
1710904 | import pandas as pd
from sklearn.model_selection import KFold
if __name__ == "__main__":
train_df = pd.read_csv("./crohme-train/train.csv")
kfold = KFold(n_splits=10, shuffle=True, random_state=1337)
train_idx, val_idx = list(kfold.split(train_df))[0]
train_df, val_df = (
train_df.iloc[train_i... |
1710981 | from __future__ import unicode_literals
from django.apps import AppConfig
class ThreadsConfig(AppConfig):
name = 'threads'
|
1711011 | import os
import sys
root_path = os.path.dirname(os.path.dirname(os.getcwd()))
if root_path not in sys.path: sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from DeepSparseCoding.tf1x.data.dataset import Dataset
import DeepSparseCoding.tf1x.utils.data_processing as dp
import DeepSparseCoding.tf... |
1711028 | pv = NXPlotView('Chopper Plots')
phi=np.linspace(5.,95.,10)
chopper.entry.data[phi[0]:phi[0]+10].sum(0).plot(xmin=1900,xmax=2600,ymax=6000)
for i in range(10):
(chopper.entry.data[phi[i]:phi[i]+10].sum(0)+500*i).oplot()
|
1711031 | import boto3
import paramiko
import json
import os
import random
import sys
import time
client = boto3.client('ec2')
# if len(sys.argv) != 2:
# print 'usage: {} <number_of_instances>'.format(sys.argv[0])
# sys.exit(1)
# BEGIN CONFIGURABLE
# config stuff
port = 2720
# num_instances = int(sys.argv[1])
c... |
1711037 | import RutishauserLabtoNWB.events.newolddelay.python.analysis.helper as helper
import scipy.stats as stats
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
def plot_behavioral_graphs(NWBFilePath):
"""
Behavioral analysis, plotting six graphs:
1. Probability of responses
2. RO... |
1711058 | import cv2
import numpy as np
# we will use linear_assignment to quickly write experiments,
# later a customerized KM algorithms with various optimization in c++ is employed
# see https://github.com/berhane/LAP-solvers
# This is used for "Complete Matching" and we can remove unreasonable "workers" first and then appl... |
1711064 | from cloudaux.gcp.iam import get_iam_policy, get_serviceaccount, get_serviceaccount_keys
from cloudaux.decorators import modify_output
from flagpole import FlagRegistry, Flags
registry = FlagRegistry()
FLAGS = Flags('BASE', 'KEYS', 'POLICY')
@registry.register(flag=FLAGS.KEYS, key='keys')
def get_keys(service_accou... |
1711079 | import hashlib
import hmac
def sign_payload(payload: str, key: str):
return hmac.new(
key=key.encode(), msg=payload.encode(), digestmod=hashlib.sha256
).hexdigest()
|
1711105 | from os import listdir
from os.path import isfile, join
import pickle
import numpy as np
TASK_DICT = {'MRPC': 'mrpc', 'STS-B': 'STSBenchmark', 'SST-2': 'SST2'}
class BaseEncoder():
def __init__(self, model_name, encode_capacity, path_cache):
self.model_name = model_name
self.encode_capacity = e... |
1711119 | from flask import Flask, Response, request, render_template, send_from_directory
import re
import subprocess
import urllib
from markupsafe import Markup
from gen import get_profiles
app = Flask(__name__)
@app.route('/')
def index():
clothing_items = get_profiles()
return render_template("index.html", clothing... |
1711155 | import collections
from torch import nn
import torch as th
from ..base import NodeClassifierBase
from FeedForwardNNLayer import FeedForwardNNLayer
class FeedForwardNN(NodeClassifierBase):
r"""Specific class for node classification task.
Parameters
----------
input_size : int
The le... |
1711161 | from django.conf import settings
# Getting project settings
PROJECT_PROVIDER_SETTINGS = getattr(settings, "NOTIFICATIONS", {})
# Internal module settings be merged with project settings
PROVIDERS_SETTINGS = {
**{
"telegram": {
"enabled": False,
"max_retries": 5,
},
... |
1711167 | import warnings
#from ethereum import utils
#from ethereum.abi import encode_abi, decode_abi
from octopus.platforms.ETH.constants import DEFAULT_GAS_PER_TX, DEFAULT_GAS_PRICE, BLOCK_TAGS, BLOCK_TAG_LATEST
from octopus.platforms.ETH.util import hex_to_dec, clean_hex, validate_block
from octopus.engine.explorer import... |
1711170 | from plugins.adversary.app.commands import wmic
from plugins.adversary.app.operation.operation import Step, OPUser, OPDomain, OPFile, OPCredential, OPHost, OPRat, OPVar
class WMIRemoteProcessCreate(Step):
"""
Description:
This step starts a process on a remote machine, using the Windows Management Int... |
1711174 | class StarData:
def __init__(self, ra, dec, mag, label=None):
self.ra = ra
self.dec = dec
self.mag = mag
self.label = label
self.ra_angle = None
self.dec_angle = None
self.x = None
self.y = None
class StarDataList:
def __init__(self, dat... |
1711211 | import xcffib
import struct
import six
_events = {}
_errors = {}
class ClientMessageData(xcffib.Union):
def __init__(self, unpacker):
if isinstance(unpacker, xcffib.Protobj):
unpacker = xcffib.MemoryUnpacker(unpacker.pack())
xcffib.Union.__init__(self, unpacker)
self.data8 = xcff... |
1711254 | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SwitchPortFwdRemote(RemoteModel):
"""
The switch forwarding table entries per device, per switch port.
| ``SwitchPortFwdID:`` The internal NetMRI identifier for this switch port forwarding entry.
|... |
1711291 | from typing import List
from collections import deque
from sys import stdin
class Solution:
def tomato(self, M: int, N: int, H: int, graph: List[List[List[int]]]):
queue = deque()
count = 0
answer = 0
visited = [[[False] * (M + 1) for i in range(N + 1)] for j in range(H + 1)]
... |
1711352 | import torch
import numpy as np
from skimage import io
from .fit import forward_pass
from .notebook_utils import draw_pcd_bg, show_nb
from utils.common import tti, to_sigm, itt, dict2device
def infer_pid(dataloader, outfit_codes_dict, image_paths_dict,
draping_network, converter, ndesc_stack, rendere... |
1711399 | import os
import math
import pandas as pd
import sys
import numpy as np
src=sys.argv[1]
dest=sys.argv[2]
for subdir, dirs, files in os.walk(src):
for file in files:
df = pd.DataFrame()
try:
df = pd.read_table(src+file, sep='\t', names=['id', 'position', 'depth'])
except:
... |
1711407 | from django import db
from django.apps import AppConfig
from orchestra.core import administration
from orchestra.utils.db import database_ready
class ResourcesConfig(AppConfig):
name = 'orchestra.contrib.resources'
verbose_name = 'Resources'
def ready(self):
if database_ready():
... |
1711434 | import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from codecs import open
if sys.version_info[:3] < (3, 0, 0):
print("Requires Python 3 to run.")
sys.exit(1)
with open("README.md", encoding="utf-8") as file:
readme = file.read()
setup(
name="com... |
1711477 | import pytest
import os.path
import subprocess
import sys
import os
import conftest
from herbstluftwm.types import Rectangle
def test_example(hlwm):
# test the example.py shipped with the bindings
example_py = os.path.join(os.path.dirname(__file__), '..', 'python', 'example.py')
# make 'herbstclient' bina... |
1711480 | from typing import Iterator, Optional, Union as TypingUnion
from genpy import (
Function as FunctionOriginal,
Generable,
Suite,
Class as BrokenClass,
FromImport,
Assign,
)
class Class(BrokenClass):
def generate(self) -> Iterator[str]:
bases = self.bases
if not bases:
... |
1711505 | import numpy as np
from sklearn.preprocessing import normalize
from utils.data_utils import convert_dir_vec_to_pose, dir_vec_pairs
def convert_pose_to_line_segments(pose):
line_segments = np.zeros((len(dir_vec_pairs) * 2, 3))
for j, pair in enumerate(dir_vec_pairs):
line_segments[2 * j] = pose[pair[0... |
1711557 | import random
from ledger.util import has_nth_bit_set
def test_nth_bit_set():
"""
Check if bits of randomly chosen integers are set or unset and compare
with the binary representation.
"""
for _ in range(0, 10000):
number = random.randint(0, 100000000)
bits = bin(number)[2:]
... |
1711594 | from django.urls import path, re_path
from .views import (MessageCreateView, ThreadDetailView, ThreadListView,
SantaThreadDetailView, SanteeThreadDetailView)
app_name = 'inbox'
urlpatterns = [
re_path(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
name='thread-detail... |
1711602 | import mnist
training_images, training_labels, test_images, test_labels = mnist.load()
print("We have successfully loaded the MNIST data!")
|
1711611 | from tljh.yaml import yaml
def test_no_empty_flow(tmpdir):
path = tmpdir.join("config.yaml")
with path.open("w") as f:
f.write("{}")
# load empty config file
with path.open("r") as f:
config = yaml.load(f)
# set a value
config["key"] = "value"
# write to a file
with pat... |
1711617 | import numpy as np
from . import _librootnumpy
__all__ = [
'array',
]
def array(arr, copy=True):
"""Convert a ROOT TArray into a NumPy array.
Parameters
----------
arr : ROOT TArray
A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS
copy : bool, optional (default=True)
If ... |
1711632 | from itertools import zip_longest
import itertools
import tensorflow as tf
from functools import reduce
from operator import mul
import numpy as np
import re
VERY_BIG_NUMBER = 1e30
VERY_SMALL_NUMBER = 1e-30
VERY_POSITIVE_NUMBER = VERY_BIG_NUMBER
VERY_NEGATIVE_NUMBER = -VERY_BIG_NUMBER
def add_summary_zero_fraction(t... |
1711643 | import os
PYLIBJUJU_DEV_FEATURE_FLAG = "PYLIBJUJU_DEV_FEATURE_FLAGS"
DEFAULT_VALUES_FLAG = "default_values"
def feature_enabled(name):
flags = os.environ.get(PYLIBJUJU_DEV_FEATURE_FLAG)
if flags is not None:
parts = [s.strip() for s in flags.split(",")]
return name in parts
return False... |
1711674 | from plugin.preferences.options.o_sync.lists.liked import SyncListsLikedOption, SyncListsLikedPlaylistsOption
from plugin.preferences.options.o_sync.lists.personal import SyncListsPersonalOption, SyncListsPersonalPlaylistsOption
from plugin.preferences.options.o_sync.lists.watchlist import SyncListsWatchlistOption, Syn... |
1711681 | import json
import multiprocessing
import pickle
from argparse import ArgumentParser
def collect_stats(line):
local_terminal_types = set()
local_nonterminal_types = set()
local_possible_children = {}
obj = json.loads(line)
relative_paths = obj['relative_paths']
head_root_path = obj['head_root_p... |
1711682 | from pathlib import Path
BASE_DIR = Path(__file__).resolve(strict=True).parents[1]
GODOT_PROJECT = BASE_DIR / 'script_runner' / 'project'
PYTHON_PACKAGE = 'script_runner'
GDNATIVE_LIBRARY = 'script_runner.gdnlib'
|
1711696 | import cv2
import cv2.aruco as aruco
import numpy as np
import os
from pathlib import Path
import math
def findArucoMarkers(img, arucoDict, arucoParam, intrinsics, distortion):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bboxs, ids, rejected = aruco.detectMarkers(gray, arucoDict, parameters=arucoParam,
... |
1711727 | from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase
from herald.contrib.auth.forms import HeraldPasswordResetForm
class ContribAuthTests(TestCase):
def test_save_form(self):
User = get_user_model()
User.objects.create_user(username='<EMAIL>... |
1711740 | import copy
import logging
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import gui
from settings.config_objs.constants import NotSet
logger = logging.getLogger(__name__)
class AbstractConfigWidget:
def get_value(self):
raise NotImplementedError()
def set_value(self, value):
rai... |
1711776 | from .utils.compatibility import *
from .utils.der import fromPem, removeSequence, removeObject, removeBitString, toPem, encodeSequence, encodeOid, encodeBitString
from .utils.binary import BinaryAscii
from .point import Point
from .curve import curvesByOid, supportedCurves, secp256k1
class PublicKey:
def __init... |
1711788 | from time import sleep
from typing import List, Union, Dict
from privex.loghelper import LogHelper
from tests.base import PrivexBaseCase
from privex.helpers import thread as modthread, LockConflict, random_str, OrderedDictObject
from privex.helpers.thread import BetterEvent, event_multi_wait_all, event_multi_wait_any... |
1711807 | passes = """
const char* PrimitiveCoordinatesPass::NAME = "PrimitiveCoords";
const char* MapCoordsPass::NAME = "MapCoords";
const char* GeometryNormalPass::NAME = "NormalsGeometry";
const char* ShadingNormalPass::NAME = "NormalsShading";
const char* DotProductPass::NAME = "NormalsDotProduct";
const char* OpacityColorP... |
1711826 | import copy
from datetime import *
from DyCommon.DyCommon import *
from ..DyStockBackTestingCommon import *
from ...Trade.DyStockTradeCommon import *
from ...Trade.AccountManager.DyStockPos import *
from ...Trade.AccountManager.StopMode.DyStockStopLossMaMode import *
from ...Trade.AccountManager.StopMode.DyStockStopPr... |
1711838 | import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("Configuration.StandardSequences.GeometryRecoDB_cff")
process.load("Configuration/StandardSequences/MagneticField_cff")
process.load("Configuration/StandardSequences/FrontierConditions_GlobalTag_cff")
process.load("Configuration/Standa... |
1711942 | import torch
def swinTransformerObjectDetectionToCustomerModel(num_class=2,model_path='mask_rcnn_swin_tiny_patch4_window7.pth',model_save_dir=""):
pretrained_weights = torch.load(model_path)
pretrained_weights['state_dict']['roi_head.bbox_head.fc_cls.weight'].resize_(num_class + 1, 1024)
pretrained_weight... |
1711946 | from PIL import Image
from .detector import detect_faces
from .align_trans import get_reference_facial_points, warp_and_crop_face
import numpy as np
import os
from tqdm import tqdm
def face_align(data=None, dest='None', crop_size=112):
source_root = data
dest_root = dest
crop_size = crop_size
scale = ... |
1711973 | from autogluon_utils.benchmarking.evaluation.runners import run_generate_clean_openml_full, run_generate_clean_kaggle_full
from autogluon_utils.benchmarking.evaluation.runners import run_evaluation_openml_core, run_evaluation_openml_core10fold, run_evaluation_openml_orig10fold, run_evaluation_openml_orig_vs_core10fold,... |
1712109 | import configparser
import dataclasses
import io
from typing import Type, TypeVar
_HAS_PREFIX = 'has_'
@dataclasses.dataclass(frozen=True)
class IniField:
section: str
name: str = ''
class _IniDescriptor:
def __init__(self, field: IniField):
self._section = field.section
self._name = ... |
1712140 | import argparse
import os
import os.path as osp
import torch
import mmcv
from mmaction.apis import init_recognizer
from mmcv.parallel import collate, scatter
from mmaction.datasets.pipelines import Compose
from mmaction.datasets import build_dataloader, build_dataset
from mmcv.parallel import MMDataParallel
import nump... |
1712152 | from __future__ import print_function
import pickle
import os.path as path
import sklearn.utils
def dump_list(input_list, file_path):
"""
Dump list to file, either in "txt" or binary ("pickle") mode.
Dump mode is chosen accordingly to "file_path" extension.
Parameters
----------
input_lis... |
1712175 | from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import (
presence_of_element_located,
title_is,
)
def getWaits(driver):
"""Inspection methods that need a wait
We define methods to get an element and to verify the window title.
They will ... |
1712225 | import os
import numpy as np
import fnmatch
import PIL.Image
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
NCOLS = 5
def check_folder(dir):
'''
create a new directory if it doesn't exist
:param dir:
:return:
'''
if not os.path.exists(dir):
... |
1712262 | import numpy as np
def log_sum_exp_sample(lnp):
"""
Sample uniformly from a vector of unnormalized log probs using
the log-sum-exp trick
"""
assert np.ndim(lnp) == 1, "ERROR: logSumExpSample requires a 1-d vector"
lnp = np.ravel(lnp)
N = np.size(lnp)
# Use logsumexp trick to calculate... |
1712306 | import os
import shutil
import torch
import scipy.io as scio
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from data.folder_new import ImageFolder_new
from data.Uniform_folder import ImageFolder_uniform
from data.Uniform_sampler import UniformBatchSampler
import numpy as np
import ... |
1712351 | from unittest.mock import create_autospec, ANY
import pytest
from stack.commands import DatabaseConnection
from stack.commands.list.firmware import Command
from stack.commands.list.firmware.make.plugin_basic import Plugin
class TestListFirmwareMakeBasicPlugin:
"""A test case for the list firmware make basic plugin.""... |
1712362 | import os
import os.path
import cv2
import util
from tqdm import tqdm
def main(in_path, Q=25):
# scan image file path
names_hr = sorted(util._get_paths_from_images(os.path.expanduser(in_path)))
base_name = os.path.expanduser(in_path).split('/')[-1]
base_name_q = base_name+'Q{}'.format(Q)
out_path_b... |
1712403 | import os
import random
import logging
import ray
from pathlib import Path
from tqdm import tqdm
from .io.video_io import VideoFrameReader, write_img_files_to_vid_ffmpeg, \
resize_and_write_video_ffmpeg, convert_vid_ffmpeg
from .utils.serialization_utils import save_json
from .dataset import GluonCVMotionDataset, ... |
1712420 | from django.conf import settings
from django.template import defaultfilters
from django.utils.translation import gettext_lazy as _
from django.views.generic import ListView
from django_cradmin import javascriptregistry
from django_cradmin.viewhelpers import listbuilder
from django_cradmin.viewhelpers.mixins import Com... |
1712430 | from django.test import TestCase
from django.urls import reverse
from django.contrib.messages import constants
from petition.models import Organization, Petition, PytitionUser, Signature, Permission
from .utils import add_default_data
class PetitionViewTest(TestCase):
"""Test index view"""
@classmethod
d... |
1712468 | from __future__ import annotations
import numpy as np
from PIL import Image
_ptrtypestr = np.dtype(np.uintp).str
class _ArrayInterfaceForObject:
__slots__ = ('__array_interface__', 'owner_object')
def __init__(self, array_intf, obj=None):
self.__array_interface__ = array_intf
self.owner_objec... |
1712498 | import datetime
import ckan.tests.factories as factories
import ckanext.hdx_theme.tests.hdx_test_with_inds_and_orgs as hdx_test_with_inds_and_orgs
class TestFreshness(hdx_test_with_inds_and_orgs.HDXWithIndsAndOrgsTest):
def test_is_fresh_flag(self):
dataset_1 = self._get_action('package_show')({}, {'id... |
1712568 | import json
from typing import List, Dict
from .api_constants import LABEL, CONFIDENCE, PREDICTIONS
from .signature_constants import (
PREDICTED_LABEL_COMPAT, LABEL_CONFIDENCES, LABEL_CONFIDENCES_COMPAT, SUPPORTED_EXPORT_VERSIONS
)
from .utils import dict_get_compat
class ClassificationResult:
"""
Data s... |
1712602 | from django import forms
from django.urls import reverse_lazy
from django_filters import CharFilter
from django_filters import MultipleChoiceFilter
from common.filters import MultiValueCharFilter
from common.filters import TamatoFilter
from common.filters import TamatoFilterBackend
from quotas import models
from quota... |
1712604 | import re
test_string = '"the" is the most used word in the English language'
def word_count(s: str) -> int:
"""
>>> word_count(test_string)
10
"""
s = re.sub('[^A-Za-z0-9 ]+', '', s)
return len(s.lower().split())
def unique_word_count(s: str) -> int:
"""
>>> unique_word_count(test_... |
1712605 | import pytest
import cupy
if cupy.cuda.runtime.is_hip:
pytest.skip('HIP sparse support is not yet ready',
allow_module_level=True)
|
1712614 | from typing import Iterable, Optional
from unittest.mock import patch
# This import verifies that the dependencies are available.
import cx_Oracle # noqa: F401
import pydantic
from pydantic.fields import Field
from sqlalchemy import event
from sqlalchemy.dialects.oracle.base import OracleDialect
from sqlalchemy.engin... |
1712642 | import argparse
import numpy as np
import pandas as pd
import pyproj
from netCDF4 import Dataset
from make_proj_grids import read_ncar_map_file, make_proj_grids
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--start_date", required=True, help="Start date in YYYY-MM-DD format")
... |
1712667 | from pylabnet.utils.helper_methods import load_device_config, get_ip
from pylabnet.network.core.service_base import ServiceBase
from pylabnet.network.core.generic_server import GenericServer
from pylabnet.network.core.client_base import ClientBase
import os
class Dummy:
pass
class Client(ClientBase):
pass
... |
1712672 | import numpy as np
import pandas as pd
def long_to_short_transformation(df, idx, icds):
"""
Summary:
Used for processing a dataframe from a long format where you want to roll up many claims into an episode for example,
but aggregate all of the possible icd codes. This is a usual preprocessing s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.