id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
81813 | class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
h = {v: i for i, v in enumerate(list1)}
result = []
m = inf
for i, v in enumerate(list2):
if v in h:
r = h[v] + i
if r < m:
m = r... |
81818 | import time
import os
def get_format_time():
'''
:return:
'''
now = time.time()
tl = time.localtime(now)
format_time = time.strftime("%Y-%m-%d", tl)
return format_time
def write_file(filepath, content, filename):
filename += '.log'
path = os.path.join(filepath, filename)
with... |
81869 | import itertools
import pytest
import tubes
def test_static_tube_takes_a_list():
tube = tubes.Each([1, 2, 3])
assert list(tube) == [1, 2, 3]
def test_static_tube_takes_an_iter():
tube = tubes.Each(itertools.count(10)).first(3)
assert list(tube) == [10, 11, 12]
def test_static_tube_with_strings()... |
81885 | from fairwork_server.settings import *
import django_heroku
import dj_database_url
import os
DEBUG = False
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
ADMIN_NAME = os.environ['ADMIN_NAME']
ADMIN_EMAIL = os.environ['ADMIN_EMAIL']
ADMINS = [(os.environ['ADMIN_NAME'], os.environ['ADMIN_EMAIL']), ]
HOSTNAME = ... |
81934 | import time
import shutil
from HSTB.kluster.fqpr_intelligence import *
from HSTB.kluster.fqpr_project import *
def get_testfile_paths():
testfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', '0009_20170523_181119_FA2806.all')
testsv = os.path.join(os.path.dirname(testfile), '2020_0... |
81951 | from flask import Blueprint, jsonify, request
from cocoa.web.views.utils import userid, format_message
from web.main.backend import get_backend
action = Blueprint('action', __name__)
@action.route('/_select_option/', methods=['GET'])
def select():
backend = get_backend()
selection_id = int(request.args.get('s... |
81956 | import unittest
from nymms.reactor.Reactor import Reactor
from nymms.reactor.handlers.Handler import Handler
enabled_config = {'handler_class': 'nymms.reactor.handlers.Handler.Handler',
'enabled': True}
disabled_config = {'handler_class': 'nymms.reactor.handlers.Handler.Handler',
... |
81984 | from datetime import datetime
from elasticsearch_dsl import DocType, String, Date, Integer, Float
from elasticsearch_dsl.connections import connections
# Define a default Elasticsearch client
connections.create_connection(hosts=['localhost'])
class Extension(DocType):
name = String()
url = String()
descri... |
82015 | import os
from pyaedt import aedt_exception_handler
from pyaedt.modeler.GeometryOperators import GeometryOperators
class Part(object):
"""Manages 3D component placement and definition.
Parameters
----------
part_folder : str
Path to the folder with the A3DCOMP files.
part_dict : dict
... |
82029 | import dispatch.plugins.kandbox_planner.util.kandbox_date_util as date_util
from dispatch.plugins.bases.kandbox_planner import KandboxRulePlugin
class KandboxRulePluginRequestedSkills(KandboxRulePlugin):
"""
Has the following members
"""
# rule_code = "check_job_skill"
# rule_name = "Worker can... |
82034 | from random import randint
import numpy as np
try:
import tensorflow as tf
except ImportError:
tf = None
# ToDo: we are using a lot of tf.keras.backend modules below, can we use tf core instead?
class MaskingDense(tf.keras.layers.Layer):
""" Just copied code from keras Dense layer and added masking and ... |
82038 | import uuid
import os
from datetime import datetime
from django.db import transaction
from api.management.data_script import OperationalDataScript
from api.models.CarbonIntensityLimit import CarbonIntensityLimit
from api.models.CompliancePeriod import CompliancePeriod
from api.models.DefaultCarbonIntensity import De... |
82070 | import dataclasses
import click
import datetime
import neuro_extras
from collections import defaultdict
from graphviz import Digraph
from neuro_cli import __version__ as cli_version
from neuro_sdk import Client, ResourceNotFound, __version__ as sdk_version
from operator import attrgetter
from rich import box
from rich... |
82075 | from autoencoder import Lambda
import torch.nn as nn
import torch
def create_block(in_channels, out_channels=None):
if out_channels is None:
out_channels = in_channels
return nn.Sequential(
nn.Conv2d(in_channels = in_channels, out_channels = out_channels, kernel_size = 3, padding=1),
nn... |
82097 | from __future__ import print_function
from distutils import log
from setuptools import setup, find_packages
import os
from jupyter_packaging import (
create_cmdclass,
install_npm,
ensure_targets,
combine_commands,
get_version,
skip_if_exists
)
# Name of the project
name = 'keplergl'
here = os... |
82098 | import random
passlen = int(input("enter the length of password"))
s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
p = "".join(random.sample(s,passlen ))
print (p)
|
82169 | from __future__ import print_function
import math
import numpy
import theano
import itertools
from theano import tensor, Op
from theano.gradient import disconnected_type
from fuel.utils import do_not_pickle_attributes
from picklable_itertools.extras import equizip
from collections import defaultdict, deque
from toposo... |
82187 | import boto3
from botocore.config import Config
import json
import os
TABLE_NAME = os.environ['TABLE_NAME']
config = Config(connect_timeout=5, read_timeout=5, retries={'max_attempts': 1})
dynamodb = boto3.client('dynamodb', config=config)
def assemble(response):
body = {
'quotes': []
}
for item ... |
82204 | import numpy as np
class BayesDiscri:
def __init__(self):
'''
:__init__: 初始化BayesDiscri类
'''
self.varipro=[] # 各个特征xk在各个类别yi下的条件概率
self.priorpro={} # 各个类别yi的先验概率
self.respro=[] # 测试集中每个样本向量属于各个类别的概率
def train(self, data, rowvar=False):
... |
82207 | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from horch.common import tuplify
from horch.models import get_default_activation, get_default_norm_layer
from horch.config import cfg
# sigmoid = torch.nn.Sigmoid()
class SwishFunction(torch.autograd.Function):
... |
82254 | try:
raise
except:
pass
try:
raise NotImplementedError('User Defined Error Message.')
except NotImplementedError as err:
print('NotImplementedError')
except:
print('Error :')
try:
raise KeyError('missing key')
except KeyError as ex:
print('KeyError')
except:
print('Error :')
try:
... |
82267 | import scadnano as sc
import modifications as mod
import dataclasses
def create_design():
stap_left_ss1 = sc.Domain(1, True, 0, 16)
stap_left_ss0 = sc.Domain(0, False, 0, 16)
stap_right_ss0 = sc.Domain(0, False, 16, 32)
stap_right_ss1 = sc.Domain(1, True, 16, 32)
scaf_ss1_left = sc.Domain(1, False,... |
82278 | def extractBersekerTranslations(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if 'Because the world has changed into a death game is funny' in item['tags'] and (chp or vol or 'Prologue' in postfix):
return buildReleaseMessageWithType(item, 'Sekai ga death game ni natta ... |
82333 | import sys
import time
import random
from .address import Address
__all__ = [
'NameServers',
'NoNameServer',
]
class NoNameServer(Exception):
pass
class IterMixIn:
def iter(self):
if not self.data: raise NoNameServer
return iter(self.data)
def success(self, item):
pass
... |
82383 | import numpy as np
try:
import astropy.io.fits as pyfits
import astropy.wcs as pywcs
except ImportError:
import pyfits
import pywcs
def fits_overlap(file1,file2):
"""
Create a header containing the exact overlap region between two .fits files
Does NOT check to make sure the FITS files are ... |
82417 | import glm, random
def generateVoxelPositions(width, height, depth):
blockSize = 1.0
noiseScale = 20.0
amplitude = 20.0
offset = random.randrange(0, 1000000)
data = []
for x in range(width):
for y in range(height):
for z in range(depth):
noise = glm.perlin(gl... |
82430 | import os
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from data_pipeline.config import settings
from data_pipeline.utils import (
download_file_from_url,
get_module_logger,
)
logger = get_module_logger(__name__)
def check_score_data_source(
score_csv_data_path: Path,
... |
82453 | import numpy as np
#from cvxopt import matrix
import pickle
from l1ls import l1ls
import copy
import pdb
import os
feats_file = 'gt_feats.pkl'
mode = 'gt'
with open(feats_file, 'rb') as f:
feats = pickle.load(f)
num_classes = len(feats)
dicts_list = []
dicts_num = 192
max_iters = 25
min_tol = 1e-2
lamda = 1e-3... |
82483 | import seaborn as sns
import pandas
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# ファイルの読み込み
salary = pandas.read_csv('data-salary.txt')
# データの先頭5行の確認
print(salary.head())
# データのサマリを確認
print(salary.describe())
# データの図示
sns.scatterplot(
x='X',
y='Y',
data=salary
)
plt... |
82497 | import os
import sys
from multiprocessing import Process
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "src"))
cwd = os.getcwd()
from supervisor import supervisor
if __name__ == "__main__":
args = {}
dir_path = os.path.dirname(os.path.abspath(__file__))
args["ext_config... |
82526 | from torchmm.models.retrieval.scan import SCAN
from torchmm.models.retrieval.sgraf import SGRAF
from torchmm.models.retrieval.vsepp import VSEPP
from torchmm.models.retrieval.imram import IMRAM
from torchmm.models.retrieval.bfan import BFAN
from torchmm.models.captioning.aoanet import AoANet
from torchmm.mode... |
82545 | import os
import sys
import numpy as np
import scipy.io as sio
import more_itertools as mit
chan = ['Fp1','AF3','F3','F7','FC5','FC1','C3','T7','CP5','CP1','P3','P7','PO3','O1','Oz','Pz','Fp2','AF4','Fz','F4','F8','FC6','FC2','Cz','C4','T8','CP6','CP2','P4','P8','PO4','O2']
nLabel, nTrial, nUser, nChannel, nT... |
82556 | def reverse(string):
return string[::-1]
print('Gimmie some word')
s = input()
print(reverse(s))
|
82568 | import numpy as np
import tensorflow as tf
from DeepSparseCoding.tf1x.ops.init_ops import L2NormalizedTruncatedNormalInitializer
from DeepSparseCoding.tf1x.utils.trainable_variable_dict import TrainableVariableDict
class AeModule(object):
def __init__(self, data_tensor, layer_types, enc_channels, dec_channels, patc... |
82602 | import collections
import logging
import runpy
import typing
from pathlib import Path
import HABApp
log = logging.getLogger('HABApp.Rules')
class RuleFile:
def __init__(self, rule_manager, name: str, path: Path):
from .rule_manager import RuleManager
assert isinstance(rule_manager, RuleManager... |
82638 | from plugin.scrobbler.methods.s_logging import Logging
from plugin.scrobbler.methods.s_websocket import WebSocket
__all__ = ['Logging', 'WebSocket']
|
82655 | import os
import sys
import getopt
"""
Extracts the audio from our game videos. This script expects that ffmpeg is installed and in the PYTHONPATH.
Usage: python extract_wav.py -i <path_to_folder_where_mp4_files_are>
"""
def parse_arguments(argv):
input_path = ''
try:
opts, args = getopt.getop... |
82668 | strategies = {}
def strategy(strategy_name: str):
"""Register a strategy name and strategy Class.
Use as a decorator.
Example:
@strategy('id')
class FindById:
...
Strategy Classes are used to build Elements Objects.
Arguments:
strategy_name (... |
82671 | from .dvd import DVD
from .gopro import GOPRO
from .reds import REDS
#
from .build import build_dataset, list_datasets
__all__ = [k for k in globals().keys() if not k.startswith("_")] |
82673 | import pickle
import pytest
from taxi import projects
def test_legacy_projects_db(tmpdir):
projects_db_file = tmpdir.join(projects.ProjectsDb.PROJECTS_FILE)
local_projects_db = projects.LocalProjectsDb()
foo = pickle.dumps(local_projects_db)
with projects_db_file.open(mode='wb') as f:
f.wri... |
82682 | import h5py
import numpy as np
file = h5py.File('/data2/wt/openimages/vc_feature/1coco_train_all_bu_2.hdf5', 'r')
for keys in file:
feature = file[keys]['feature'][:]
np.save('/data2/wt/openimages/vc_feature/coco_vc_all_bu/'+keys+'.npy', feature)
|
82738 | from FrameLibDocs.utils import write_json
from FrameLibDocs.classes import dParseAndBuild, Documentation
def main(docs):
"""
A simplified version of the qlookup used to display information about specific objects when hovered over in the umenu.
"""
docs.interfaces_dir.mkdir(exist_ok=True)
obj_looku... |
82739 | from joern.shelltool.TraversalTool import TraversalTool
from py2neo import neo4j
DEFAULT_TAGNAME = 'tag'
BATCH_SIZE = 1000
class JoernTag(TraversalTool):
def __init__(self, DESCRIPTION):
TraversalTool.__init__(self, DESCRIPTION)
self.argParser.add_argument("-t", "--tag", default = D... |
82757 | import os
import pathlib
def model_path(config, root="./saved"):
root = pathlib.Path(root)
filename = "{}".format(config.dataset)
# Dataset-specific keys
if config.dataset in ["CIFAR10"]:
filename += "_augm_{}".format(
config.augment,
)
# Model-specific keys
file... |
82780 | import can
bus1 = can.interface.Bus('can0', bustype='virtual')
bus2 = can.interface.Bus('can0', bustype='virtual')
msg1 = can.Message(arbitration_id=0xabcde, data=[1,2,3])
bus1.send(msg1)
msg2 = bus2.recv()
print(hex(msg1.arbitration_id))
print(hex(msg2.arbitration_id))
assert msg1.arbitration_id == msg2.arbitration... |
82798 | import os
import Chamaeleo
from Chamaeleo.methods.default import BaseCodingAlgorithm
from Chamaeleo.methods.ecc import Hamming, ReedSolomon
from Chamaeleo.methods.fixed import Church
from Chamaeleo.utils.pipelines import RobustnessPipeline
if __name__ == "__main__":
root_path = os.path.dirname(Chamaeleo.... |
82877 | import datetime
from collections import Iterable
from dateutil import tz
from atpy.data.iqfeed.iqfeed_level_1_provider import get_splits_dividends
from atpy.data.iqfeed.util import *
from atpy.data.splits_dividends import adjust_df
from pyevents.events import EventFilter
class IQFeedBarDataListener(iq.SilentBarList... |
82902 | from django import VERSION
from django.conf.urls import url
from .views import GetPopupView
"""
In django 1.10 JavaScriptCatalog is new
so for older version django import view as function
and for django >= 1.10 I use view class
"""
if VERSION < (1, 10):
from django.views.i18n import javascript_catalog
else:
... |
82937 | import torch
import numpy as np
from tqdm import tqdm
from typing import Union, List, Tuple, Any, Dict
from easydict import EasyDict
from .dataset import preprocess, InferenceDataset, InferenceDatasetWithKeypoints
from .network import build_spin
from .. import BasePose3dRunner, BasePose3dRefiner, ACTIONS
from iPERCor... |
82969 | import pytest
import sqlite3
from unittest.mock import call, Mock
from allennlp.common.testing import AllenNlpTestCase
from scripts.ai2_internal.resume_daemon import (
BeakerStatus,
create_table,
handler,
logger,
resume,
start_autoresume,
)
# Don't spam the log in tests.
logger.removeHandler(... |
83003 | import pygame
import pystage
from pystage.core.constants import KEY_MAPPINGS
from pystage.core._base_sprite import BaseSprite
class _Sensing(BaseSprite):
def __init__(self):
super().__init__()
def sensing_askandwait(self, question):
# an input field, answer needs to be available somehow
... |
83009 | from models import *
from pokeapi import PokeAPI
import logging
# logger = logging.getLogger('peewee')
# logger.setLevel(logging.DEBUG)
# logger.addHandler(logging.StreamHandler())
def main():
api = PokeAPI()
for i in range(1, api.get_count(), 1):
try:
raw_pokemon = api.get_pokemon(i)... |
83057 | from __future__ import print_function
from tdda.rexpy import extract
from tdda.rexpy.seq import common_string_sequence
from tdda.rexpy.relib import re
x = extract(['Roger', 'Coger', 'Doger'], tag=True, as_object=True)
print(x)
patternToExamples = x.pattern_matches()
sequences = []
for j, (pattern, examples) in enum... |
83059 | from abc import ABC
import numpy as np
import gym
import mujoco_py
from gym.envs.registration import register
def change_fetch_model(change_model):
import os
import shutil
gym_folder = os.path.dirname(gym.__file__)
xml_folder = 'envs/robotics/assets/fetch'
full_folder_path = os.path.join(gym_folde... |
83060 | from django.db import models
from django.db.models import Case, F, Q, Value, When
from psqlextra.expressions import HStoreRef
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model
def test_query_annotate_hstore_key_ref():
"""Tests whether annotating using a :see:HStoreRef expression wo... |
83093 | import random
from cmath import exp
import math
def rotation_scale(origin, theta, scale, points):
return [origin + (point-origin)*scale*e(theta) for point in points]
def translate(origin, points):
# offset = points[0]-origin
return [point-origin for point in points]
def flip(z1, z2, points):
z1z2 = ... |
83100 | import sys
sys.path.append("../../")
from appJar import gui
def showPositions():
for widg in app.getContainer().grid_slaves():
row, column = widg.grid_info()["row"], widg.grid_info()["column"]
print(widg, row, column)
with gui("Grid Demo", "300x300", sticky="news", expand="both") as app:
for ... |
83105 | from django.test import TestCase
from model_bakery import baker
from django_cradmin.cradmin_testhelpers import TestCaseMixin
from django_cradmin.viewhelpers import listbuilderview
from django_cradmin.django_cradmin_testapp import models as testmodels
class ListBuilderViewWithoutPaging(listbuilderview.View):
mode... |
83115 | from cowait.tasks import Task
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, GlobalAveragePooling1D, Dense
class ImdbTask(Task):
async def run(self):
# get the pre-proc... |
83169 | from rustypy.pywrapper import rust_bind
@rust_bind
def first_module() -> None:
print('... called from first module')
if __name__ == "__main__":
first_module()
|
83179 | import torch
from functools import partial
from easydict import EasyDict as edict
from albumentations import *
from isegm.data.datasets import *
from isegm.model.losses import *
from isegm.data.transforms import *
from isegm.engine.trainer import ISTrainer
from isegm.model.metrics import AdaptiveIoU
from isegm.data.po... |
83188 | from .snpeff_dump import SnpeffDumper
from .snpeff_upload import SnpeffHg19Uploader, SnpeffHg38Uploader
|
83194 | import dash_bootstrap_components as dbc
from dash import html
from .util import make_subheading
spinner = html.Div(
[
make_subheading("Spinner", "spinner"),
html.Div(
[
dbc.Spinner(color=col)
for col in [
"primary",
... |
83228 | import os
main_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
empty_python_output = """\
# -*- encoding: utf-8 -*-
# This file has been generated by prophyc.
import sys
import prophy
"""
def test_showing_version(call_prophyc):
ret, out, err = call_prophyc(["--version"])
... |
83230 | import uuid
import datetime
from typing import List, Union, Dict
from plugins.adversary.app.engine.database import EncryptedDictField
from plugins.adversary.app.engine.objects import Log
from plugins.adversary.app.util import tz_utcnow
version = 1.1
class Operation(dict):
def __init__(self):
super().__i... |
83245 | from datetime import datetime
from os.path import dirname, join
import pytest
from city_scrapers_core.constants import COMMISSION, PASSED
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.chi_ssa_51 import ChiSsa51Spider
test_response = file_response(
... |
83255 | import attr
import pandas
from sarif_om import *
from src.exception.VulnerabilityNotFoundException import VulnerabilityNotFoundException
VERSION = "2.1.0"
SCHEMA = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json"
class SarifHolder:
def __init__(self):
self.... |
83265 | import matplotlib.pyplot as plt
import numpy as np
class RefDataType:
def __init__(self,length,steps,coverage,cv,marker,color,label):
self.length = length
self.steps = steps
self.coverage = coverage
self.cv = cv
self.marker = marker
self.color = color
self.label = label
def get_prop(self, prop_str):
... |
83291 | import pandas
import pkg_resources
from unittest import TestCase
from dfs.nba.expansion import get_expansion_targets, encode_names, expand_nba_data, discretize_data
class ExpansionTestCase(TestCase):
def setUp(self):
# A little test data from the past few years, useful for testing BREF data
testfn = pkg_res... |
83301 | from __future__ import annotations
import argparse
import json
import logging
import os
from datetime import datetime
from datetime import timedelta
import git
import humanfriendly
from datalad.plugin import export_archive
from github import Github
from scripts.datalad_utils import get_dataset
from scripts.datalad_u... |
83331 | from __future__ import print_function
from six import iteritems
from itertools import chain
import ipyparallel as ipp
from ipyparallel.client.client import ExecuteReply
# Remotely-called function; imports requirement internally.
def dummyTask(key):
from os import getpid
from time import sleep
from ipypara... |
83343 | import jiwer
import jiwer.transforms as tr
from jiwer import compute_measures
from typing import List
def compute_wer(predictions=None, references=None, concatenate_texts=False):
if concatenate_texts:
return compute_measures(references, predictions)
else:
incorrect = 0
total = 0
... |
83366 | from powerlift.bench import Experiment, Store
from powerlift.executors.docker import InsecureDocker
from powerlift.executors.localmachine import LocalMachine
from powerlift.executors.azure_ci import AzureContainerInstance
import pytest
import os
def _add(x, y):
return x + y
def _err_handler(e):
raise e
d... |
83387 | from struct import pack
from World.WorldPacket.Constants.WorldOpCode import WorldOpCode
from Server.Connection.Connection import Connection
class InitialSpells(object):
def __init__(self, **kwargs):
self.data = kwargs.pop('data', bytes())
self.connection: Connection = kwargs.pop('connection')
... |
83446 | class VehiclesDataset:
def __init__(self):
self.num_vehicle = 0
self.num_object = 0
self.num_object_with_kp = 0
self.vehicles = dict()
self.valid_ids = set()
self.mean_shape = None
self.pca_comp = None
self.camera_mtx = None
self.image_names = ... |
83448 | import logging.config
import os
import structlog
from node_launcher.constants import NODE_LAUNCHER_DATA_PATH, OPERATING_SYSTEM
timestamper = structlog.processors.TimeStamper(fmt='%Y-%m-%d %H:%M:%S')
pre_chain = [
# Add the log level and a timestamp to the event_dict if the log entry
# is not from structlog.
... |
83455 | from .__init__ import EntroQ
from . import entroq_pb2 as pb
import click
import datetime
from datetime import timezone
import grpc
import json
from google.protobuf import json_format
class _ClickContext: pass
def _task_str_raw(task):
return EntroQ.to_dict(task)
def _task_str_json(task):
return EntroQ.to_... |
83472 | import numpy as np
from noduleCADEvaluationLUNA16 import noduleCADEvaluation
import os
import csv
from multiprocessing import Pool
import functools
import SimpleITK as sitk
from config_testing import config
from layers import nms
annotations_filename = './labels/new_nodule.csv'
annotations_excluded_filename = './lab... |
83474 | import argparse
import cv2
import numpy as np
import torch
import kornia as K
from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint
def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -> np.ndarray:
kpt = det.get_keypoint(kpt_type).int().tolist()
return cv... |
83477 | import os
import re
import io
import sys
import glob
import json
import argparse
import datetime
from operator import itemgetter
from bs4 import BeautifulSoup
DURATION_RE = r'PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?'
def convert_to_type(s):
return s.replace('http://www.google.com/voice#', '')
def convert_to_tel(s)... |
83509 | from __future__ import unicode_literals
import codecs
def encode_hex(value):
return '0x' + codecs.decode(codecs.encode(value, 'hex'), 'utf8')
def decode_hex(value):
_, _, hex_part = value.rpartition('x')
return codecs.decode(hex_part, 'hex')
|
83545 | import random
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
"""
Generating squares
This example will generate 25 squares each in a randomly chosen grayvalue.
The grayvalue is chosen out of 25 different possiblities. Every redraw of the
window will create a new set of squares.
http://ww... |
83571 | import abc
import asyncio
import logging
from typing import Any, Callable, List, Optional, TYPE_CHECKING, Union
from discord import Message, Reaction, TextChannel, User
from discord.abc import GuildChannel
from discord.ext.commands import Context
from dpymenus import Page, PagesError, Session, SessionError
from dpyme... |
83598 | import os
import mock
import pytest
from prequ._pip_compat import PIP_10_OR_NEWER, PIP_192_OR_NEWER, path_to_url
from prequ.exceptions import DependencyResolutionFailed
from prequ.repositories.pypi import PyPIRepository
from prequ.scripts._repo import get_pip_command
PY27_LINUX64_TAGS = [
('cp27', 'cp27mu', 'man... |
83648 | import pandas as pd
import numpy as np
import pytest
from nltk.metrics.distance import masi_distance
from pandas.testing import assert_series_equal
from crowdkit.aggregation.utils import get_accuracy
from crowdkit.metrics.data import alpha_krippendorff, consistency, uncertainty
from crowdkit.metrics.performers import ... |
83652 | import pandas as pd
def correct_lr(data):
'''
Invert the RL to LR and R1R2 to r2>r1
'''
import pandas as pd
def swap(a,b): return b,a
data = data.to_dict('index')
for k,v in data.items():
if v['isReceptor_fst'] and v['isReceptor_scn']:
v['isReceptor_fst'],v['isReceptor_s... |
83655 | import albumentations
from albumentations.pytorch import ToTensorV2
import cv2
import numpy as np
def crop_image_from_gray(img, tol=7):
if img.ndim == 2:
mask = img > tol
return img[np.ix_(mask.any(1), mask.any(0))]
elif img.ndim == 3:
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
... |
83681 | import requests
login_url = "http://shop2.q.2019.volgactf.ru/loginProcess"
target_url = "http://shop2.q.2019.volgactf.ru/profile"
payload0 = {'name': 'wani', 'pass': '<PASSWORD>'}
payload1 = {'name': 'wani', 'CartItems[0].id': 4}
s = requests.Session()
r = s.post(login_url, data=payload0)
r = s.post(target_url, data... |
83707 | from django.contrib.auth.models import User
from demoproject.filter.forms import UserListForm
from django_genericfilters.views import FilteredListView
class UserListView(FilteredListView):
# Normal ListView options
template_name = "user/user_list.html"
paginate_by = 10
context_object_name = "users"
... |
83726 | import time
import cv2
import numpy as np
from chainer import serializers, Variable
import chainer.functions as F
import argparse
from darknet19 import *
from yolov2 import *
from yolov2_grid_prob import *
from yolov2_bbox import *
n_classes = 10
n_boxes = 5
partial_layer = 18
def copy_conv_layer(src, dst, layers):
... |
83734 | import numpy as np
import brainscore
from brainio.assemblies import DataAssembly
from brainscore.benchmarks._properties_common import PropertiesBenchmark, _assert_grating_activations
from brainscore.benchmarks._properties_common import calc_spatial_frequency_tuning
from brainscore.metrics.ceiling import NeuronalProper... |
83750 | import asyncio
import copy
import inspect
import logging
from typing import Dict, Any, Callable, List, Tuple
log = logging.getLogger(__name__)
class Parser:
"""
deal with a list of tokens made from Lexer, convert their type to match the command.handler
"""
_parse_funcs: Dict[Any, Callable] = {
... |
83755 | import math
layouts = []
def register_layout(cls):
layouts.append(cls)
return cls
def node(percent, layout, swallows, children):
result = {
"border": "normal",
# "current_border_width": 2,
"floating": "auto_off",
# "name": "fish <</home/finkernagel>>",
"percent"... |
83778 | import pytest
import mantle
from ..harness import show
def com(name, main):
import magma
from magma.testing import check_files_equal
name += '_' + magma.mantle_target
build = 'build/' + name
gold = 'gold/' + name
magma.compile(build, main)
assert check_files_equal(__file__, build+'.v', go... |
83783 | import json
import os
import asyncio
from aiohttp.client import ClientSession
from ln_address import LNAddress
import logging
###################################
logging.basicConfig(filename='lnaddress.log', level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.getLogger("lnaddres... |
83805 | import datetime
import numpy as np
import os
import pandas as pd
import shutil
import urllib.request
import zipfile
__all__ = [
'fetch_ml_ratings',
]
VARIANTS = {
'100k': {'filename': 'u.data', 'sep': '\t'},
'1m': {'filename': 'ratings.dat', 'sep': r'::'},
'10m': {'filename': 'ratings.dat', 'sep': r'... |
83824 | import os
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import QStandardPaths, QSettings
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QFileDialog
from PyQt5.QtXml import QDomDocument, QDomNode
try:
from krita import *
CONTEXT_KRITA = True
Krita = Krita # to stop Eric ide compl... |
83832 | import os
import scipy as sp
import scipy.misc
import imreg_dft as ird
basedir = os.path.join('..', 'examples')
# the TEMPLATE
im0 = sp.misc.imread(os.path.join(basedir, "sample1.png"), True)
# the image to be transformed
im1 = sp.misc.imread(os.path.join(basedir, "sample2.png"), True)
result = ird.translation(im0,... |
83868 | import json
def load_tools(file_path='/definitions/workers.json'):
tools = {}
with open(file_path) as json_file:
tools = json.load(json_file)
return tools
|
83876 | import os
import argparse
import sys
from Image_extractor import *
from Lidar_pointcloud_extractor import *
from Calibration_extractor import *
from Label_extractor import *
from Label_ext_with_occlusion import *
def File_names_and_path(source_folder):
dir_list = os.listdir(source_folder)
files = list()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.