id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11491504 | import request_generator
class MouseRequest(request_generator.RequestGenerator):
def __init__(self, client):
super(MouseRequest, self).__init__(client)
self.type = 'action'
self.device = 'mouse'
def press(self, mask):
self.action = 'press'
self.params = [mask]
s... |
11491527 | import aiohttp
import asyncio
from typing import Awaitable, Callable
from tests.benchmark.driver_base import *
TestTask = Callable[[aiohttp.ClientSession], Awaitable[int]]
async def run_notify_test(session: aiohttp.ClientSession) -> int:
async with session.post(notify_url(), json=notify_entity()) as response:
... |
11491551 | from amazon.api import AmazonAPI
from ebaysdk.finding import Connection as finding
from ebaysdk.exception import ConnectionError
import csv
from fuzzywuzzy import fuzz
import argparse
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-S','--SearchTerm', help='what you wou... |
11491597 | import functools
import torch
from scipy.linalg import lapack as scll
from falkon.la_helpers import potrf
from falkon.options import FalkonOptions
from falkon.utils.helpers import choose_fn
__all__ = ("check_init", "inplace_set_diag_th", "inplace_add_diag_th",
"lauum_wrapper", "potrf_wrapper")
def check... |
11491620 | import config
import subprocess
from flask import request
from flask_restful import Resource, reqparse
import logging
import base64
from decorators import private_api
from requests import get
import json
import shlex
logger = logging.getLogger("api")
class Jobs(Resource):
@private_api
def get(self):
"... |
11491621 | from .c11type import C11Type
class C11TypeBool(C11Type):
def __init__(self):
C11Type.__init__(self)
self.typeName = u'bool'
def setSchema(self, schemaName, schemaValue):
C11Type.setSchema(self, schemaName, schemaValue)
@classmethod
def codeDefaultValue(cls, schemaDefaultValue)... |
11491622 | import setuptools
pkg_name="theiapod"
setuptools.setup(
name=pkg_name,
version="0.1.0",
author="<NAME>",
author_email="<EMAIL>",
description="Self-host gitpod-style workspaces for github repositories using theia",
url="https://github.com/magland/theiapod",
packages=setuptools.find_packages... |
11491635 | import pytest
import os
from tests.examples import TestExample as base_class
from pandas.testing import assert_frame_equal
from yggdrasil.components import create_component
class TestExampleConditionalIO(base_class):
r"""Test the conditional_io example."""
@pytest.fixture(scope="class")
def example_name(... |
11491639 | import os
from tqdm import trange
import torch
from im2mesh.common import chamfer_distance
from im2mesh.training import BaseTrainer
from im2mesh.utils import visualize as vis
class Trainer(BaseTrainer):
r''' Trainer object for the Point Set Generation Network.
The PSGN network is trained on Chamfer distance.... |
11491681 | from plugin.core.constants import GUID_SERVICES
import logging
log = logging.getLogger(__name__)
class SyncMap(object):
def __init__(self, task):
self.task = task
self._by_guid = {}
self._by_key = {}
def add(self, p_section_key, p_key, guids):
if not guids or not p_key:
... |
11491702 | import unittest
import os
import_error = False
try:
from .. import common
except ImportError:
import_error = True
common = None
class TestCase00(unittest.TestCase):
def test_import(self):
self.assertFalse(import_error)
class TestCase01(unittest.TestCase):
def setUp(self):
if imp... |
11491734 | import FWCore.ParameterSet.Config as cms
from DQMOffline.JetMET.metDQMConfig_cfi import *
#correction for type 1 done in JetMETDQMOfflineSource now
METDQMAnalyzerSequence = cms.Sequence(caloMetDQMAnalyzer*pfMetDQMAnalyzer*pfChMetDQMAnalyzer*pfMetT1DQMAnalyzer)
METDQMAnalyzerSequenceMiniAOD = cms.Sequence(pfMetDQMAna... |
11491737 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import yaml
from ansible.plugins.action import ActionBase
from ansible.errors import AnsibleActionFail
from ansible.utils.vars import isidentifier
from ansible.plugins.filter.core import combine
from ansible.plugins.loader import l... |
11491760 | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from textwrap import dedent as d
import pandas as pd
#df = pd.read_hdf(r'..\examples\algae\MC\mc_out_allyears_sigma1.h5')
df = pd.read_csv(r'..\examples\algae\MC\mc_out_allyears_sigma1.dat', ... |
11491761 | import numpy as np
import matplotlib.pyplot as plt
from pactools.utils.testing import assert_equal, assert_array_almost_equal
from pactools.utils.testing import assert_greater, assert_raises
from pactools.utils.testing import assert_array_not_almost_equal
from pactools.dar_model import DAR, AR, HAR, StableDAR
from pac... |
11491778 | import face_alignment
import numpy as np
import cv2
import threading
import cv2
class VideoCaptureThreading:
def __init__(self, src=0, width=640, height=480):
self.src = src
self.cap = cv2.VideoCapture(self.src)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.cap.set(cv2.CAP_P... |
11491792 | import numpy as np
from scipy.stats import mode, itemfreq
from scipy import delete
import matplotlib.pylab as plt
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC as SVM
from missing_data_imputation import Imputer
# declare csv ... |
11491834 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from utils.utils import decode_mu_law
from models.layers import (
UpsampleNetwork
)
from models.subscale import (
CondintionNetwork,
Subscaler
)
from hparams import create_hparams
HPARAMS = create_hpa... |
11491841 | import torch as th
from typing import Optional, Tuple
from tpp.utils import batch as bu
from tpp.utils.events import Events
from tpp.utils.utils import smallest_positive
from tpp.utils.index import take_2_by_2
from tpp.utils.history_bst import get_prev_times as get_prev_times_bst
def _get_rank(x: th.Tensor) -> int:... |
11491859 | import os
import pathlib
from pytest_notebook.nb_regression import NBRegressionFixture
EXEC_CWD = str(pathlib.Path(__file__).resolve().parent.parent)
fixture = NBRegressionFixture(
exec_timeout=120,
exec_cwd=EXEC_CWD,
diff_color_words=True,
diff_ignore=(
"/cells/*/outputs/*/data/text/plain",
... |
11491983 | from toee import *
from utilities import *
from py00439script_daemon import *
from combat_standard_routines import *
def san_start_combat( attachee, triggerer ):
if (attachee.leader_get() != OBJ_HANDLE_NULL and not npc_get(attachee,2)):
leader = attachee.leader_get()
if (group_pc_percent_hp( attachee, leader ) <... |
11491984 | import os
import textwrap
class CodeGenerator():
def __init__(self):
self.layers = []
def addLayer(self, weights, biases, activation):
self.layers.append((weights, biases, activation))
def save(self, name):
lines = []
lines.append('// Auto generated model data')
li... |
11491987 | import argparse
import subprocess
import time
def track(wait_time=60):
# In the following, a select set of parameters that are passed to ffmpeg is
# described:
# -vframes -> Number of frames to output.
# -q:v -> (alias: qscale) Quality of the output, 100 means as lossy as
# possible (resulting i... |
11491990 | import collections
from setuptools import Extension
from buildtools import *
import torch
import os
# ~~~ libnitorch files
# Note that sources are identical between libnitorch_cpu and libnitorch_cuda.
# The same code is compiled in two different ways to generate native and cuda
# code. This trick allows to minimize c... |
11492066 | from typing import Optional
import re
from collections import OrderedDict
from requests import Response as ServerResponse
from instagram_api.response.mapper import ApiResponse
from .account_disabled import AccountDisabledException
from .bad_request import BadRequestException
from .challenge_required import Challeng... |
11492073 | import pytest
import fuzz_lightyear
from fuzz_lightyear.exceptions import ConflictingHandlers
from fuzz_lightyear.supplements.abstraction import get_abstraction
class TestMakeRequest:
def test_basic(self):
def request_handler(operation_id):
assert operation_id == 'status'
fuzz_lighty... |
11492159 | import numpy as np
import pandas as pd
from sfrmaker.routing import find_path, make_graph
def valid_rnos(rnos):
"""Check that unique reach numbers (rno in MODFLOW 6)
are consecutive and start at 1.
"""
sorted_reaches = sorted(rnos)
consecutive = np.diff(sorted_reaches).sum() \
=... |
11492202 | import copy
import json
import re
import numpy as np
import torch
import transformers.data.processors.squad as squad
from tqdm import tqdm
class SquadExample:
"""
A single training/test example for the Squad dataset, as loaded from disk.
Args:
qas_id: The example's unique identifier
ques... |
11492204 | import pytest
from typus import en_typus, ru_typus
from typus.chars import *
QUOTES = (
''.join((LAQUO, RAQUO, DLQUO, LDQUO)),
''.join((LDQUO, RDQUO, LSQUO, RSQUO)),
)
TYPUSES = (
(ru_typus, {}),
(en_typus, str.maketrans(*QUOTES)),
)
@pytest.fixture(name='assert_typus', scope='module', params=TYPUSE... |
11492211 | from pandas_confusion import ConfusionMatrix
def write_prediction_file(path, test_unique_ids, Y_test_indices, y_prediction_classes):
with open(path, 'w') as prediction_handler:
prediction_handler.write('{}\t{}\t{}\n'.format("UniqueID", "Gold_Label", "Prediction"))
for index, val in enumerate(test_... |
11492227 | import numpy as np
from bokeh.core.properties import Float
from bokeh.io import save
from bokeh.model import DataModel
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.plotting import figure
class Params(DataModel):
amp = Float(default=0.1, help="Amplitude")
freq = Float(default=0.1, help="Freq... |
11492280 | import os
from pathlib import Path
def write_nblink(fpath, route):
rpath = Path(route, fpath)
new_name = fpath.name.replace(".ipynb", ".nblink")
fpath = fpath.with_name(new_name)
with open(fpath, "w") as f:
f.write("{ \n")
f.write(f' "path": "{rpath.as_posix()}"\n')
f.wri... |
11492282 | import re
import SourceModel.SM_CaseStmt
import SourceModel.SM_Class
import SourceModel.SM_Constants as SMCONSTS
import SourceModel.SM_Define
import SourceModel.SM_Define
import SourceModel.SM_Element
import SourceModel.SM_Exec
import SourceModel.SM_FileResource
import SourceModel.SM_IfStmt
import SourceModel.SM_Inclu... |
11492315 | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import xgboost as xgb
from xgboost import XGBClassifier, XGBRegressor
from xgboost import plot_importance
from catboost import CatBoostRegressor
from matplotlib import pyplot
import... |
11492324 | import pytest
from collections import namedtuple
from stack.kvm import Hypervisor, VmException
from unittest.mock import create_autospec, patch
from stack.commands import DatabaseConnection
from stack.argument_processors.vm import VmArgProcessor
from stack.commands.set.host.power.imp_kvm import Implementation
from stac... |
11492346 | import argparse
import collections
import os
import pickle
import pytest
import re
import signal
import subprocess
import sys
import time
import numpy as np
import cntk as C
TIMEOUT_SECONDS = 300
NUM_WORKERS = 4
NUM_BATCHES = 10
BATCH_SIZE_PER_WORKER = 20
def mpiexec_execute(script, mpiexec_params, params, timeout_se... |
11492350 | name = 'medcat'
# Hacky patch to the built-in copy module coz otherwise, thinc.config.Config.copy will fail on Python <= 3.6.
# (fixed in python 3.7 https://docs.python.org/3/whatsnew/3.7.html#re)
import sys # noqa
if sys.version_info.major == 3 and sys.version_info.minor <= 6:
import copy
import re
copy... |
11492416 | from django.urls import include
from django.views import defaults
__all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include']
handler400 = defaults.bad_request
handler403 = defaults.permission_denied
handler404 = defaults.page_not_found
handler500 = defaults.server_error
|
11492429 | import tensorflow as tf
import numpy as np
import coremltools as ct
from coremltools.models.neural_network import quantization_utils
import coremltools.proto.FeatureTypes_pb2 as FeatureTypes_pb2
path = "/Users/william/Downloads/AttGAN_384/generator.pb"
# Load the protobuf file from the disk and parse it to retrieve ... |
11492446 | from generativepy.drawing import make_image, setup
from generativepy.color import Color
from generativepy.geometry import Circle, Square, Text
'''
Create bezier curve using the geometry module.
'''
def draw(ctx, width, height, frame_no, frame_count):
setup(ctx, width, height, width=5, background=Color(0.8))
... |
11492484 | import cv2
import numpy as np
from pyaffx import Affine
from _griffig import BoxData, OrthographicImage
from ..utility.image import draw_line, get_inference_image
from ..utility.model_data import ModelArchitecture
class Heatmap:
def __init__(self, inference, a_space=None):
self.inference = inference
... |
11492525 | from guided_filter.datasets.google_image import dataFile
# -*- coding: utf-8 -*-
## @package guided_filter.results.performance
#
# Simple performance test.
# @author tody
# @date 2015/08/26
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
from guided_filter.io_util.image import ... |
11492528 | import collections
import csv
import glob
import os
import pandas as pd
import cea
import cea.config
import cea.inputlocator
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>... |
11492533 | import os
import pytest
from waterbutler.core import streams
DUMMY_FILE = os.path.join(os.path.dirname(__file__), 'fixtures/dummy.txt')
class TestFileStreamReader:
@pytest.mark.asyncio
async def test_file_stream_reader(self):
with open(DUMMY_FILE, 'r') as fp:
reader = streams.FileStre... |
11492549 | from colorclass import Color
from terminaltables import SingleTable
class ArticlePrinter(object):
"""Class which can be used to print Article stats on the command line"""
def __init__(self, article_obj):
self.article = article_obj
def print_article_stats(self):
"""This method is called t... |
11492587 | def gcd(u, v):
while v > 0:
tmp = v
v = u % v
u = tmp
return u
t = int(input())
for _ in range(t):
a, b, x, y = map(int, input().split())
# gcd definitions says:
# gcd (a + m * b, b) = gcd(a, b)
# such as m being an integer
# hence:
# gcd (a + b, b)
# gcd (a - b, b)
# gcd (a, a + b)
# gcd (a, a - b)
... |
11492593 | import torch
import numpy as np
from torch import nn, optim
from .data_helper import get_data_loader
history = {}
def root_mean_squared_error(y_true, y_pred):
""" RMSE implementation.
:param y_true: The correct labels
:param y_pred: The predicted labels
:return: RMSE score
"""
return np.sq... |
11492647 | import os, os.path, errno, sys, traceback, subprocess
import re, html.entities
import json
import logging
import yaml
from bs4 import BeautifulSoup
from datetime import datetime
import requests
import urllib.parse
import io
import gzip
import docx
import zipfile
from urllib.parse import urljoin
import inspect
import pd... |
11492648 | from xwing.network.transport.socket.backend.rfc1078 import send, recv
class Connection:
def __init__(self, loop, sock):
self.loop = loop
self.sock = sock
async def recv(self):
'''Try to recv data. If not data is recv NoData exception will
raise.
:param timeout: Timeo... |
11492659 | import os
import uuid
import boto3
from six.moves import configparser
from botocore.exceptions import ClientError
from .aws_util_exceptions import ProfileParsingError
from .aws_util_exceptions import RoleNotFoundError
from .aws_util_exceptions import AssumeRoleError
def get_aws_account_id(profile=None):
if profil... |
11492668 | from socket import AF_INET, SOCK_DGRAM, socket
# import requests
import sys
host = "172.16.58.3"
seq_num = sys.argv[1]
method = sys.argv[2]
buf = 2048
# url = "http://localhost:8002/getUDPPort"
# response = requests.get(url)
# data = response.content
# port = int(data.decode('utf-8'))
port = 20000
addr = (host, port)... |
11492669 | import sys
sys.path.insert(0, '..')
import unittest
import json
import numpy as np
import torch
from model import DurIAN
from base import suite, BaseModelForwardPassTest
seed = 0
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
class DurIANForwardPassTest(BaseModelForwardPas... |
11492695 | import copy
import random
import gym
import numpy as np
from gym import spaces
from gym.utils import seeding
class Bit_Flipping_Environment(gym.Env):
environment_name = "Bit Flipping Game"
def __init__(self, environment_dimension=20, deterministic=False):
self.action_space = spaces.Discrete(environme... |
11492702 | import pykd
import re
from common.v_0_0_3.common_utils import *
print('='*10 + ' Start ' + '='*10)
runCmd(r'bc *;g')
#runCmd(r'!idna.tt 4159E80000018') # Abnormal:ieframe!CDownloadWindowItem::_SetState
#runCmd(r'!idna.tt 54BF700000644') # Abnormal:wininet!CommitUrlCacheEntryW
#runCmd(r'!idna.tt CC66400005FC') # Norma... |
11492704 | import enum
from typing import NamedTuple, Optional
@enum.unique
class ErdAcFanSetting(enum.Enum):
DEFAULT = 0
AUTO = 1
LOW = 2
LOW_AUTO = 3
MED = 4
MED_AUTO = 5
HIGH = 8
HIGH_AUTO = 9
def stringify(self, **kwargs):
return self.name.replace("_"," ").title()
@enum.uni... |
11492726 | import unittest, sys
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_common
print "Assumes you ran ../build_for_clone.py in this directory"
print "Using h2o-nodes.json. Also the sandbox dir"
# uses a reduced common class
class releaseTest(h2o_common.ReleaseCommon2, unittest.TestCase):
def test_shutdown(se... |
11492728 | from setuptools import setup, find_packages
with open("README.md") as f:
long_description = f.read()
setup(
name="pytest-pylenium",
description="selenium wrapper for pytest to aid with system testing",
license="Apache Software License 2.0",
author="<NAME>",
url="https://github.com/symonk/pytest... |
11492764 | from __future__ import print_function
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import pandas as pd
import pickle
import threading
import sys
class FOMC (object):
'''
A convenient class for extracting meeting minutes from the FOMC website
Example Usage:
fomc = FOM... |
11492766 | import copy
import tensorflow as tf
import numpy as np
from onnx_tf.handlers.backend_handler import BackendHandler
from onnx_tf.handlers.handler import onnx_op
from onnx_tf.handlers.handler import tf_func
@onnx_op("LRN")
@tf_func(tf.nn.lrn)
class LRN(BackendHandler):
@classmethod
def _common(cls, node, **kwarg... |
11492812 | from .._public.artifactstore.api.ArtifactStoreApi import ArtifactStoreApi
from .._public.modeldb.api.CommentApi import CommentApi
from .._public.modeldb.api.DatasetServiceApi import DatasetServiceApi
from .._public.modeldb.api.DatasetVersionServiceApi import DatasetVersionServiceApi
from .._public.modeldb.api.Experimen... |
11492818 | from ghizmo.commands import lib
import os
import yaml
import urllib.parse
from collections import defaultdict
_AUTHORS_INFO_FILES = ["authors-info.yml", "authors-info.json", "admin/authors-info.yml", "admin/authors-info.json"]
def assemble_authors(config, args):
"""
Assemble a list of authors as an AUTHORS.md f... |
11492819 | from typing import Any
from typing import Union
import numpy as np
__all__ = ["Face", "Integer", "Float", "Complex", "Bool", "Void"]
Face = Any
_NumpyInt = Union[
np.int_,
np.intc,
np.intp,
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
... |
11492853 | import pandas as pd
def compute_quotient_metrics(filename,
index_col=0,
resample_period='1M',
shift=0,
quotient_metrics=[('Volume', 'max', 'median'),
('Clos... |
11492872 | from datetime import datetime
class Field(object):
to_py = lambda self, value: value
to_linode = to_py
def __init__(self, field):
self.field = field
class IntField(Field):
def to_py(self, value):
if value is not None and value != '':
return int(value)
to_linode = to_py
class FloatField(Fiel... |
11492919 | import os
import numpy as np
import PIL
import cv2
import tifffile
from scipy.signal import convolve2d
import merlin
from merlin.core import dataset
from merlin.data import codebook as cb
class MERFISHDataFactory(object):
"""
A class for simulating MERFISH data sets.
"""
def __init__(self):
... |
11492939 | def helper(lst1,lst2,n,x):
lst1.sort(reverse=True)
for i in range(0,n):
if(lst1[i] + lst2[i] <= x):
continue
else:
return False
return True
t = int(input())
while t > 0:
n,x = map(int,input().split())
lst1 = list(map(int,input().split()))
lst2 = list(map(... |
11492957 | import pygame as pg
from Entity import Entity
from Const import *
class Goombas(Entity):
def __init__(self, x_pos, y_pos, move_direction):
super().__init__()
self.rect = pg.Rect(x_pos, y_pos, 32, 32)
if move_direction:
self.x_vel = 1
else:
self.x_vel = -1
... |
11492987 | import sys, pytest
sys.path.append("../")
LIST_ONE = ["a", "b", "c", "d", "e"]
LIST_TWO = ["v", "d", "s", "t", "z"]
print(LIST_ONE)
print(LIST_TWO)
from tkinter import OptionMenu
from appJar import gui
def get(btn):
a = app.getOptionBoxWidget("l1")
b = app.getOptionBoxWidget("l2")
c = app.getOptionBoxWid... |
11493020 | import unittest
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from PySeismoSoil.class_ground_motion import Ground_Motion as GM
from PySeismoSoil.class_Vs_profile import Vs_Profile
from PySeismoSoil.class_frequency_spectrum import Frequency_Spectrum
import os
from os.path import join as _join
... |
11493041 | from toee import *
import char_editor
def CheckPrereq(attachee, classLevelled, abilityScoreRaised):
#Str requirement enforced by the engine
if not char_editor.has_feat(feat_two_weapon_fighting) and not char_editor.has_feat(feat_two_weapon_fighting_ranger):
return 0
return 1
|
11493045 | from .AbstractAdjacencyCompander import AbstractAdjacencyCompander
import numpy as np
import sys
import os
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'../../../../preprocessing')))
from mnist_to_graph_tensor import mnist_adj_mat
class ImageAdjacencyCompander(AbstractAdjacency... |
11493048 | import os
from infiniteremixer.utils.io import load
class BatchExtractor:
"""Batch extract features dynamically from a list of audio files."""
def __init__(self, sample_rate=22050):
self.sample_rate = sample_rate
self.extractors = []
self._features = {}
def add_extractor(self, e... |
11493136 | import numpy as np
from scipy.special import jv as besselj
from Solvers.QSP_solver import QSP_Solver
from math import ceil
# --------------------------------------------------------------------------
# Test case 1: Hamiltonian simulation
#
# Here we want to approxiamte e^{-i\tau x} by Jacobi-Anger expansion:
#
# e^{-i... |
11493153 | from django.contrib.auth import get_user_model
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from guardian.shortcuts import assign_perm, remove_perm
from grandchallenge.blogs.models import Post
@receiver(m2m_changed, sender=Post.authors.through)
def update_permissions_on_autho... |
11493156 | from django.conf import settings
from django.core import validators
class BookmarkURLValidator(validators.URLValidator):
"""
Extends default Django URLValidator and cancels validation if it is disabled in settings.
This allows to switch URL validation on/off dynamically which helps with testing
"""
... |
11493185 | import time
def initGPIO():
try:
with open("/sys/class/gpio/export", "w") as fp:
fp.write("477")
except:
pass
try:
with open("/sys/class/gpio/export", "w") as fp:
fp.write("476")
except:
pass
try:
with open("/sys/class/gpio/gpio477/d... |
11493202 | import pytest
from shortcuts import FMT_SHORTCUT, FMT_TOML
from shortcuts.cli import _get_format
class Test_get_format:
@pytest.mark.parametrize('filepath,exp_format', [
('file.shortcut', FMT_SHORTCUT),
('file.plist', FMT_SHORTCUT),
('file.toml', FMT_TOML),
('https://icloud.com/sh... |
11493211 | from sentry_relay import DataCategory, SPAN_STATUS_CODE_TO_NAME
def test_parse_data_category():
assert DataCategory.parse("default") == DataCategory.DEFAULT
assert DataCategory.parse("transaction") == DataCategory.TRANSACTION
assert DataCategory.parse("") is None
assert DataCategory.parse(None) is Non... |
11493213 | import argparse
from typing import List
import tqdm
import canrevan.parsing as parsing
import canrevan.utils as utils
from canrevan.crawling import Crawler
DEFAULT_USER_AGENT_STRING = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/87.0.4280.66 "
"Safa... |
11493241 | import pandas as pd
from tqdm import tqdm
import json
import torch
from nltk.corpus import stopwords
from transformers import GPT2LMHeadModel
from model.ConditionalLM import ConditionalLM
from util.utils import load_args, compute_logProb, init_tokenizer
from util.CLMDataset import CLMDataset
from torch.utils.data impor... |
11493266 | import queue
visited = []
MAX = 20
adj = {1: set([2,3,5]), 2: set([3]), 3: set([8,4]), 4:6}
q = queue.Queue(MAX)
def dfs(s):
if s in visited :
return
visited.append(s)
print(s)
children = adj.get(s)
if children != None:
if isinstance(children,int): # Case : values are not a set
dfs(children)
else : ... |
11493278 | class Solution:
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s): return s
row, direction, res = 0, -1, [""] * numRows
for char in s:
res[row] += char
if row == 0 or row == numRows - 1: direction *= -1
row += direction
return ""... |
11493288 | import os
import sys
import argparse
def genera(envF):
"""
Read genera per environment
:param envF:
:return:
"""
with open(envF, 'r') as f:
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Calculate shared genera per env")
parser.add_argument('-f', help=... |
11493328 | import numpy as np
import multiprocessing
import timeit
def start():
a = np.random.rand(1000, 1000)
b = np.random.rand(1000, 1000)
np.multiply(a,b)
start2 = timeit.timeit()
for i in range(500):
start()
end = timeit.timeit()
print(end-start2)
start2 = timeit.timeit()
pool = multiprocessing.Pool(multipro... |
11493338 | import collections
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
cnt = collections.Counter(text)
ans = float('inf')
for ch in 'ban':
ans = min(ans, cnt.get(ch, 0))
for ch in 'lo':
ans = min(ans, cnt.get(ch, 0) // 2)
... |
11493352 | from numpy import zeros, copy
from itertools import accumulate
M = 1e9 + 7
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
k, m = k + 1, m + 1
f1 = zeros((k, m))
f1[1, 1:] = 1
for _ in range(1, n):
f2 = copy(f1)
for j in range(1, k):
... |
11493378 | import pandas as pd
import numpy as np
def dataset():
train_data = pd.read_csv('train.csv', index_col=None)
direction_data = train_data['direction']
sentence_data = train_data['sentence']
rel_data = train_data['relation']
term1_data = train_data['term1']
term2_data = train_data['term2']
m =... |
11493410 | from ..cw_model import CWModel
class Report(CWModel):
def __init__(self, json_dict=None):
self.column_definitions = None # (JObject[])
self.row_values = None # (JObject[])
# initialize object with json dict
super().__init__(json_dict)
|
11493416 | import dataclasses
import re
from typing import Any, ClassVar, Match, Optional, Pattern, Set, Union
BASE_PATTERN = re.compile(
r"^arn:"
r"(?P<partition>.+?):"
r"(?P<service>.+?):"
r"(?P<region>.*?):"
r"(?P<account>.*?):"
r"(?P<rest>.*)$"
)
class InvalidArnException(Exception):
"""Raised w... |
11493443 | import datetime
from dojo.tools.stackhawk.parser import StackHawkParser
from dojo.models import Test, Finding
from unittests.dojo_test_case import DojoTestCase
class TestStackHawkParser(DojoTestCase):
__test_datetime = datetime.datetime(2022, 2, 16, 23, 7, 19, 575000, datetime.timezone.utc)
def test_invalid... |
11493478 | import argparse
import logging
import os
import subprocess
from concurrent import futures
from enum import Enum
from os import PathLike
from pathlib import Path
from tempfile import NamedTemporaryFile
from threading import Thread
from typing import List
from buglab.controllers.helper.randombugselectorserver import ran... |
11493505 | import re
import pandas as pd
from config_db import DB_CONNECTION
__all__ = []
OPTIONS = dict(
if_exists='replace',
index=False
)
def gsheet_csv_url(url):
"""
Returns the url for the Google Sheet csv export.
Parameters
----------
url : str
The editor url string as found when vi... |
11493509 | from django.urls import path
from custom_auth.oauth.views import login_with_github, login_with_google
app_name = "oauth"
urlpatterns = [
path("google/", login_with_google, name="google-oauth-login"),
path("github/", login_with_github, name="github-oauth-login"),
]
|
11493574 | import random
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return "Position=[x={},y={}]".format(se... |
11493590 | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.db',
}
}
# Required to serve the files while we use Gunicorn in dev env
MIDDLEWARE += [
'... |
11493634 | import pytest
from dbnd._core.settings.tracking_config import (
TrackingConfig,
ValueTrackingLevel,
get_value_meta,
)
from targets import target as target_factory
from targets.value_meta import ValueMetaConf
from targets.values import ListValueType, ObjectValueType, StrValueType, TargetValueType
class Te... |
11493637 | from ..utility.expr_wrap_util import symbolic
from ..expr import BVV, BVS
from ..utility.models_util import get_arg_k
from ..sym_state import State
MAX_READ = 100
def read_handler(state: State, view):
fd = get_arg_k(state, 1, 4, view)
buf = get_arg_k(state, 2, state.arch.bits() // 8, view)
count = get_ar... |
11493750 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange
# TODO
# - Proper tests of everything
# - be clearer about meaning of t_elapsed, t_ix and either (t)
# - Time Since Event is a ticking bomb. Needs better naming/... |
11493754 | from typing import Optional
from dissect.cstruct import Instance
from structlog import get_logger
from unblob.extractors.command import Command
from unblob.file_utils import InvalidInputFormat
from ...models import File, HexString, StructHandler, ValidChunk
logger = get_logger()
VALID_NT_SIGNATURES = [0x28, 0x29]... |
11493758 | from deepmatch.models import NCF
from ..utils import get_xy_fd_ncf
def test_NCF():
model_name = "NCF"
x, y, user_feature_columns, item_feature_columns = get_xy_fd_ncf(False)
model = NCF(user_feature_columns, item_feature_columns, )
model.compile('adam', "binary_crossentropy")
model.fit(x, y, ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.