id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11445960 | SWIGGY_URL = "https://www.swiggy.com"
CSRF_PATTERN = r"window._csrfToken = \"(.+?)\";"
SWIGGY_COOKIE = "__SW"
SWIGGY_LOGIN_URL = f"{SWIGGY_URL}/dapi/auth/signin-with-check"
SWIGGY_SEND_OTP_URL = f"{SWIGGY_URL}/dapi/auth/sms-otp"
SWIGGY_VERIFY_OTP_URL = f"{SWIGGY_URL}/dapi/auth/otp-verify"
STATUS_FLAG = "statusCode"
STA... |
11445963 | import time
import requests
import hashlib
import hmac
TICK_INTERVAL = 60 # seconds
API_KEY = 'my-api-key'
API_SECRET_KEY = b'my-secret-key'
def main():
print('Starting trader bot...')
while True:
start = time.time()
tick()
end = time.time()
# Sleep the th... |
11445983 | from pymui import createMuiTheme, colors, makeStyles, styled, Button
from pyreact import createElement as el
theme = createMuiTheme({
'palette': {
'primary': colors['teal'],
'secondary': colors['pink'],
'special': {
'main': colors['deepPurple'][600],
'contrastText': ... |
11445985 | import tcr_embedding.evaluation.Metrics as Metrics
import scanpy as sc
def run_knn_within_set_evaluation(data_full, embedding_function, prediction_labels, subset='val'):
"""
Function for evaluating the embedding quality based upon kNN (k=1) prediction inside the set
:param data_full: anndata object contai... |
11446004 | import base64
import boto3
import hmac
import hashlib
import json
import os
import sys
import contextlib
'''primary public entrypoint to this module --
given a valid eXchange-client.properties file located in
$EXCHANGE_CLIENT_HOME (or %%EXCHANGE_CLIENT_HOME%% if you are
a command-prompt person), t... |
11446023 | from random import seed,sample
import os
import csv
from pprint import pprint
src = 'C:/RavenFinetune/raw/movie_lines.csv'
data = list()
with open(src, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
info = {'index': int(row[0].strip()), 'name': row[1].strip(), 'lin... |
11446027 | from operator import itemgetter
import os
from zipfile import ZipFile
import click
import scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.files import FilesPipeline
from webcomix.comic import Comic
class ComicPipeline(FilesPipeline):
def get_media_requests(self, item, info):
click.ec... |
11446030 | from utils import CanadianScraper, CanadianPerson as Person
COUNCIL_PAGE = 'http://www.legassembly.sk.ca/mlas/'
class SaskatchewanPersonScraper(CanadianScraper):
def scrape(self):
page = self.lxmlize(COUNCIL_PAGE)
members = page.xpath('//table[@id="MLAs"]//tr')[1:]
assert len(members), '... |
11446043 | import schoolopy
from auth import *
print('Your name is %s' % sc.get_me().name_display)
for update in sc.get_feed():
user = sc.get_user(update.uid)
print('By: ' + user.name_display)
print(update.body[:40].replace('\r\n', ' ').replace('\n', ' ') + '...')
print('%d likes\n' % update.likes)
|
11446062 | import os
import random
import cv2 as cv
import numpy as np
from keras.utils import Sequence
from keras.utils import to_categorical
from config import batch_size, img_rows, img_cols, num_classes, color_map
train_images_folder = 'data/instance-level_human_parsing/Training/Images'
train_categories_folder = 'data/instan... |
11446074 | import json
from pydcop.infrastructure.orchestrator import RepairReadyMessage
from pydcop.utils.simple_repr import simple_repr
def test_serialize_RepairReadyMessage():
msg = RepairReadyMessage('a1', ['c1', 'c2', 'c3'])
msg_repr = simple_repr(msg)
json.dumps(msg_repr) |
11446106 | from pretty_midi import PrettyMIDI
from mgt.datamanagers.time_shift.time_util import TimeUtil
class Event(object):
def __init__(self, event_type, start, data):
self.event_type = event_type
self.start = start
self.data = data
def __repr__(self):
return 'Event(type={}, start={}... |
11446167 | from __future__ import print_function
import argparse
import numpy as np
import torch
import torch.nn as nn
from models.networks import get_nets
import cv2
import yaml
import os
from torchvision import models, transforms
from torch.autograd import Variable
import shutil
import glob
import tqdm
from util.metrics import ... |
11446177 | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import operator as o
import sys, csv
WORKING_DIR = "results/"
TMP_DIR = "/tmp"
OUT_DIR = "../paper/atc17/figures"
FOR_PAPER_OR_THESIS = "THESIS"
if FOR_PAPER_OR_THESIS == "THESIS":
LABEL_SIZE =... |
11446189 | from django.urls import path
from . import views
urlpatterns = [
path(r'synopsis/', views.UnitGroupListView.as_view(), name='synopsis'),
path(r'prefs/', views.UserProfileUpdateView.as_view(), name='profile'),
path(r'unit/problems/<int:pk>/', views.unit_problems, name='view-problems'),
path(r'unit/tex/<int:pk>/', ... |
11446205 | import logging
from ckan import model, authz
from ckan.common import c, _
log = logging.getLogger(__name__)
def member_request(context, data_dict):
""" Only allowed to sysadmins or organization admins """
if not c.userobj:
return {'success': False}
if authz.is_sysadmin(c.user):
return {'... |
11446242 | import animals as a
import keeper as k
dict_animals = {
'classes': [k.keeper, a.dog, a.cat],
'names': ['taro', 'pochi', 'mike']
}
def feed_time(animals):
keeper = animals[0]
keeper.feed(animals[1])
keeper.feed(animals[1])
keeper.feed(animals[1])
keeper.feed(animals[1])
... |
11446260 | import logging
import datetime as dt
import wukong.errors as solr_errors
from wukong.request import SolrRequest
from wukong.zookeeper import Zookeeper
import json
logger = logging.getLogger(__name__)
def _add_scheme_if_not_there(url, scheme='http'):
if not (
url.startswith('http://')
or url.starts... |
11446263 | import torch
from nni.retiarii.converter.graph_gen import convert_to_graph, GraphConverterWithShape
class ConvertMixin:
@staticmethod
def _convert_model(model, input):
script_module = torch.jit.script(model)
model_ir = convert_to_graph(script_module, model)
return model_ir
class Con... |
11446267 | import os
import sys
import logging
import csv
import re
import vcf
import argparse
import urllib2
import itertools
import pandas as pd
import numpy as np
import Fred2.Core.Generator as generator
import math
from collections import defaultdict
from Fred2.IO.MartsAdapter import MartsAdapter
from Fred2.Core.Variant impo... |
11446356 | import random
def get_domain_dn(name):
splitted_name = str(name).split(".")
dn = "DC=" + splitted_name[0]
for word in splitted_name[1:]:
dn = dn + ",DC=" + word
return dn
def generate_trust_sid():
#"S-1-5-21-883232822-274137685-4173207997"
return "S-1-5-21-" + str(random.randint(1000... |
11446376 | import sys
import numpy as np
import openmoc
#For Python 2.X.X
if (sys.version_info[0] == 2):
import checkvalue as cv
# For Python 3.X.X
else:
import openmoc.checkvalue as cv
class Subdivider(openmoc.Lattice):
"""A lattice that subdivides an arbitrary universe along a uniform mesh
NOTE: Currently on... |
11446394 | from flask import (
Flask,
current_app,
flash,
g,
redirect,
render_template,
url_for
)
from flask_bootstrap import Bootstrap
from flask_caching import Cache
from flask_login import LoginManager, logout_user, current_user
from flask_mail import Mail
from flask_migrate import Migrate
from flas... |
11446397 | NET_MAIN = "main"
NET_STAGE = "stage"
NET_TEST = "test"
NETS = (NET_MAIN, NET_TEST, NET_STAGE)
MASTERADDR_NETBYTES = (18, 53, 24)
SUBADDR_NETBYTES = (42, 63, 36)
INTADDRR_NETBYTES = (19, 54, 25)
PRIO_UNIMPORTANT = 1
PRIO_NORMAL = 2
PRIO_ELEVATED = 3
PRIO_PRIORITY = 4
|
11446456 | import argparse
import os.path
import torch
class Permutations(object):
def __init__(self, args):
super(Permutations, self).__init__()
self.n_tasks = args.n_tasks
self.i = args.i
self.train_file = args.train_file
self.test_file = args.test_file
self.o = os.path.joi... |
11446476 | from datetime import datetime
from time import time
EPOCH = datetime.utcfromtimestamp(0)
ISO_FMT = '%Y-%m-%dT%H:%M:%S'
LOCAL_FMT = '%Y-%m-%d %H:%M:%S'
DB_FMT = '%Y%m%d'
# DO NOT REMOVE!!! THIS IS MAGIC!
# strptime Thread safe fix... yeah ...
datetime.strptime("2000", "%Y")
# END OF MAGIC
def _epoch_to_ms(t: float) ... |
11446488 | from schematics.exceptions import ConversionError, DataError, ValidationError
from nose.tools import eq_,raises
from moncli import column_value as cv
from moncli.enums import ColumnType
from moncli.models import MondayModel
from moncli.types import EmailType
def test_should_succeed_when_to_native_returns_a_email_whe... |
11446492 | import ast
import csv
import datetime
import pytz
from sqlalchemy import Column, Integer, Numeric, String, Boolean, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Application(Base):
__tablename__ = 'applications'
id = Column(Integer, primary_key=True, autoincr... |
11446500 | from Bio import SeqIO
import argparse
parser = argparse.ArgumentParser(description='This program takes a fastq file and converts it to a fasta file')
parser.add_argument('I', metavar='Input fastq', nargs='+',
help='The fastq file that is to be converted')
parser.add_argument('O', metavar='Output fas... |
11446519 | import FWCore.ParameterSet.Config as cms
from SimGeneral.HepPDTESSource.pythiapdt_cfi import *
from TrackingTools.TransientTrack.TransientTrackBuilder_cfi import *
from SimTracker.TrackHistory.TrackHistory_cff import *
from SimTracker.TrackHistory.TrackQuality_cff import *
trackClassifier = cms.PSet(
trackHisto... |
11446523 | import logging.config
import os
import coloredlogs
import yaml
def setup_logging(
default_path="logging.yaml",
default_level=os.getenv("LOG_LEVEL", logging.INFO),
env_key="LOG_CFG",
):
"""Setup logging configuration
"""
coloredlogs.auto_install()
path = default_path
value = os.getenv... |
11446528 | import sys
from karton.core.karton import LogConsumer
class StdoutLogger(LogConsumer):
identity = "karton.stdout-logger"
def process_log(self, event):
if event.get("type") == "log":
print(f"{event['name']}: {event['message']}", file=sys.stderr)
if __name__ == "__main__":
StdoutLogge... |
11446547 | import wagtail.admin.rich_text.editors.draftail.features as draftail_features
from django.templatetags.static import static
from django.utils.html import format_html_join
from draftjs_exporter.dom import DOM
from wagtail.admin.rich_text.converters.html_to_contentstate import (
InlineEntityElementHandler,
)
from wag... |
11446656 | class Api:
""" """
client = None
def __init__(self, client):
self.client = client
def get_specific(self, engagement_ref):
"""List activities for specific engagement
:param engagement_ref: String
"""
return self.client.get("/tasks/v2/tasks/contracts/{0}".forma... |
11446691 | from django import forms
from courses.models import Course
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=200)
class Meta:
model = User
fields = ('username', 'email'... |
11446706 | import pytest
from busy_beaver.apps.slack_integration.interactors import generate_help_text
from tests._utilities import FakeSlackClient
pytest_plugins = ("tests._utilities.fixtures.slack",)
MODULE_TO_TEST = "busy_beaver.apps.slack_integration.interactors"
@pytest.fixture
def patch_slack(patcher):
def _patch_sl... |
11446728 | import cv2
import numpy as np
image1 = cv2.imread('../assets/globalaihub.png')
img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
thresh1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 199, 5)
thresh2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH... |
11446745 | import tensorflow as tf
from rltf.models import BasePG
from rltf.tf_utils import tf_utils
class PPO(BasePG):
"""Proximal Policy Optimization Model"""
def __init__(self, ent_weight, vf_weight, **kwargs):
super().__init__(**kwargs)
self.ent_weight = ent_weight
self.vf_weight = vf_weight
# C... |
11446784 | from pathlib import Path
import pytest
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
from whatlies.language import DIETLanguage
@pytest.mark.rasa
def t... |
11446829 | import json, logging, os, re, requests, sys
from bs4 import BeautifulSoup as Soup, Tag
from pyamazon.Downloader import AmazonDownloader as downloader
from pyamazon.Helpers.requesthelper import RequestHelper
from pyamazon.Params import AmazonParameters
from pyamazon.Configs.Amazon import *
from pyamazon.Configs.co... |
11446839 | import os
from .. import tools
def run_cite_seq_pipeline(input_file, output_name, **kwargs):
# load input data
adata = tools.read_input(input_file, genome = kwargs['genome'])
# filter out low quality cells/genes
tools.filter_cells_cite_seq(adata, kwargs['max_cells'])
# normailize counts and then transform to log... |
11446878 | from __future__ import absolute_import
__author__ = 'breddels'
import numpy as np
import logging
from vaex.dataframe import DataFrame
import vaex
from frozendict import frozendict
logger = logging.getLogger("vaex.server.dataframe")
allowed_method_names = []
# remote method invokation
def _rmi(f=None):
def decor... |
11446902 | from garpix_page.models import BaseListPage
class ListPage(BaseListPage):
paginate_by = 10
class Meta:
verbose_name = "Списочная страница"
verbose_name_plural = "Списочные страницы"
ordering = ('-created_at',)
|
11446904 | import time
from typing import Optional, Tuple
from httpx import AsyncClient
from src.modules.search_record import SearchRecord
from src.modules.ticket_info import TicketInfo
from src.utils.config import config
from src.utils.log import logger
from .config import JX3APP
class TicketManager(object):
'''ticket管理器... |
11446911 | import json
import logging
import os
from django.apps import apps
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
logger = logging.getLogger(__name__)
INTEGRATION_ADMIN_ROLE_NAME = "Integration Admin"
# These functions get automatically passed "proposal"... |
11446932 | import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description="Analyse the logs produced by torchbeast")
parser.add_argument("--dir", type=str, default="~/logs/torchbeast", help="Directory fo... |
11446970 | import math, random, os, time
from windowfilter import WindowAverage
class HoverCalc:
def __init__(self,airmainloop):
self.airmainloop=airmainloop
self.throttleAverage=WindowAverage(32)
self.accAverage=WindowAverage(32)
self.G=-981 #cm/s^2
self.minThrottle=1150
def update(self,acc,throttle):
self.ac... |
11446992 | import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
def generate_train_set():
a = np.zeros([600,4])
for i in range(0,600):
if i < 200:
a[i,0] = -1.0 + i/200.0
a[i,1] = +0.5
a[i,2] = +1.0 - i*0.75/200
a[i,3] = +0.25
elif 200 <= i < 400:
a[i,0] = 0.0
a[i,... |
11447006 | import re
import pytest
from wikipedia_ql.fragment import Fragment
from wikipedia_ql.selectors import text, section, css, alt, page, attr
from wikipedia_ql.parser import Parser
def make_fragment(html, **kwargs):
# Because fragment is Wikipedia-oriented and always looks for this div :shrug:
return Fragment.pa... |
11447056 | import unittest
from provider.article import article
import tests.settings_mock as settings_mock
import tests.test_data as test_data
from mock import patch
from ddt import ddt, data, unpack
class ObjectView(object):
def __init__(self, d):
self.__dict__ = d
BUCKET_FILES_MOCK_VERSION = [
"elife-06498-... |
11447083 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumRootToLeaf(self, root, tree_num=0):
if not root:
# empty node or empty tree
return 0
else:
# update tree_num ... |
11447117 | import html
import logging
import re
from depc.sources import BaseSource, SourceRegister
from depc.sources.exceptions import BadConfigurationException
from depc.utils.warp10 import Warp10Client, Warp10Exception, _transform_warp10_values
logger = logging.getLogger(__name__)
warp_plugin = SourceRegister()
SCHEMA = {
... |
11447134 | from chapter2_基础.soundBase import *
from chapter4_特征提取.end_detection import *
data, fs = soundBase('C4_1_y.wav').audioread()
data -= np.mean(data)
data /= np.max(data)
IS = 0.25
wlen = 200
inc = 80
N = len(data)
time = [i / fs for i in range(N)]
wnd = np.hamming(wlen)
overlap = wlen - inc
NIS = int((IS * ... |
11447149 | shell.connect(__uripwd);
session.drop_schema('prepared_stmt');
schema = session.create_schema('prepared_stmt');
session.sql("use prepared_stmt");
session.sql("create table test_table (id integer, name varchar(20), age integer)");
table = schema.get_table('test_table');
table.insert().values(1, "george", 18).execute();... |
11447153 | from Data.WorldPosData import *
class AoePacket:
def __init__(self):
self.type = "AOE"
self.pos = WorldPosData()
self.radius = 0
self.damage = 0
self.effect = 0
self.duration = 0
self.origType = 0
self.color = 0
self.armorPierce = ... |
11447157 | import logging
from time import time
import uvicorn
from fastapi import FastAPI, HTTPException
from app.constants import MLFLOW_MODEL_ARTIFACTS_PATH, MLFLOW_MODEL_RUN_ID
from app.ml import load_model
from app.models import ModelInput
logger = logging.getLogger(__file__)
app = FastAPI()
MODEL = None
@app.on_even... |
11447160 | from random import choices
class Codec:
rand_pool = list( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )
def __init__(self):
self.url_table = dict()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
url_id... |
11447198 | import pytest
from django.conf import settings
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: settings.AUTH_USER_MODEL):
assert user.get_absolute_url() == "/users/{username}/".format(
username=user.username
)
|
11447256 | import io
import pytest
from exif import Image
@pytest.fixture
def image():
with open("tests/fixtures/img_gps.jpeg", "rb") as f:
return io.BytesIO(f.read())
class TestScrubExif:
@pytest.fixture
def target(self):
from files.exif import scrub_exif
return scrub_exif
def test_... |
11447258 | from django.db.models import Q
from django.views import generic
from utils.mixins import BaseViewMixin, DetailViewMixin
from .models import Article
from .serializers import ArticleViewSetRetrieveSerializer, ArticleViewSetListSerializer
# Create your views here.
class ArticleListView(BaseViewMixin,
... |
11447264 | import unittest
from katas.kyu_7.keypad_horror import computer_to_phone
class ComputerToPhoneTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(computer_to_phone('94561'), '34567')
def test_equals_2(self):
self.assertEqual(computer_to_phone('000'), '000')
def test_equa... |
11447265 | import subprocess
import cookiecutter
# make venv
# inside the new venv, install test requirements and check pytest <project
# name> works
# make venv
# inside the new venv, install ci/rtd-requirements.txt, and check sphinx-build
# works
# oh and towncrier too
def test_stuff():
print("woo")
|
11447296 | import math
from .DyStockStopMode import *
from ...DyStockTradeCommon import *
class DyStockStopLossStepMode(DyStockStopMode):
def __init__(self, accountManager, initSLM=0.9, step=0.1, increment=0.09):
"""
激活阶梯停损,可以不需要止盈模式,也就是说包含止盈和止损。
https://www.ricequant.com/community/top... |
11447299 | import os
from fabric.api import cd, env, task, require, sudo, prefix
from fabric.contrib.files import exists, upload_template
VIRTUALENV_DIR = 'env'
CODE_DIR = 'app'
PACKAGES = (
'python-dev',
'python-virtualenv',
'supervisor',
)
LOG_DIR = 'logs'
@task
def demo():
env.server_name = 'demo.storyweb.g... |
11447332 | import math
import numpy as np
import torch
import torch.nn as nn
import warnings
from typing import List, Optional, Union
from .base import Flow
from .rnn import SplineRNN
__all__ = [
'TransformedExponential'
]
class StandardExponential(nn.Module):
"""Standard exponential distribution with unit rate."""
... |
11447400 | def coding_problem_08(bt):
"""
A unival tree (which stands for "universal value") is a tree where all nodes have the same value.
Given the root to a binary tree, count the number of unival subtrees.
Example:
>>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, None... |
11447446 | import os
import sys
from process import process
#Just as a note, absolutely none of this (or the stuff in process.py) is robust to malformed input.
#Hooray for rush-coding!
def build(direc):
os.chdir(direc)
# Note: This currently rewrites the entire toc on each execution. I'm going to make
# this only do... |
11447468 | import mimetypes
import os
import shutil
from BaseHTTPServer import BaseHTTPRequestHandler
from urllib2 import urlopen
class ProxyHttpRequestHandler(BaseHTTPRequestHandler):
dir_path = os.path.dirname(os.path.realpath(__file__)) + "/"
def _send_ok(self):
url = self.path[1:] # replace '/'
f... |
11447508 | from pytest import fixture
from pygiftgrab import (ColourSpace, Device)
def pytest_addoption(parser):
parser.addoption('--device', action='store',
help='Device to test (decklinksdi4k, or decklink4kextreme12g)')
parser.addoption('--colour-space', action='store',
help='... |
11447509 | import math
import numpy as np
import tensorflow as tf
import threading
import logging
def lrelu(input_tensor, reuse):
act_func = tf.contrib.keras.layers.LeakyReLU(alpha=0.001)
return act_func(input_tensor)
def pelu(x, reuse):
"""Parametric Exponential Linear Unit (https://arxiv.org/abs/1605.09332v1)."""
with tf... |
11447558 | from instauto.api.client import ApiClient
import instauto.api.actions.structs.activity as act
client = ApiClient(username="your_username", password="<PASSWORD>")
# or ApiClient.initiate_from_file('.instauto.save')
client.save_to_disk('.instauto.save')
obj = act.ActivityGet(mark_as_seen=False)
recent_activity = clie... |
11447576 | from __future__ import absolute_import as _abs
from ._ffi.node import NodeBase, NodeGeneric, register_node
from ._ffi.runtime_ctypes import TVMType, TypeCode
from . import make as _make
from . import generic as _generic
from . import _api_internal
class Expr(ExprOp, NodeBase):
"""Base class of all tvm Expressions... |
11447577 | import contextlib
import os.path
import test.test_tools
from test.support import load_package_tests
@contextlib.contextmanager
def tool_imports_for_tests():
test.test_tools.skip_if_missing('c-analyzer')
with test.test_tools.imports_under_tool('c-analyzer'):
yield
def load_tests(*args):
return lo... |
11447589 | from unittest import TestCase
from cmlkit.engine import Component, Configurable
class MyClass(Component):
kind = "hello"
default_context = {"b": 1}
def __init__(self, a, context={}):
super().__init__(context=context)
self.a = a
def _get_config(self):
return {"a": self.a}
... |
11447612 | import os
import shutil
TEMPLATE_DIR = os.path.dirname(os.path.abspath(__file__))
def template_path(*ps):
"""
returns a path relative to the template directory
"""
return os.path.join(TEMPLATE_DIR, *ps)
def copy_template(template_name, location):
"""
performs a simple recursive copy of a te... |
11447623 | import json
from typing import (
Mapping,
Optional,
)
is_sandbox = '/sandbox/' in __file__
def partition_prefix_length(n: int) -> int:
"""
For a given number of subgraphs, return a partition prefix length that
yields at most 512 subgraphs per partition.
>>> [partition_prefix_length(n) for n ... |
11447638 | import pytest
import brownie
from operator import itemgetter
from brownie import interface, Contract, ZERO_ADDRESS
yfiVaultAddress = "0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1"
yfiAddress = "0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e"
usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
cyUsdcAddress = "0x76E... |
11447644 | import os
import pathlib
from dotenv import load_dotenv
from maestro_agent.enums import LogLevel
load_dotenv()
def parse_bool(str_value):
return str_value.lower() in ["true", "1"]
AGENT_HOST = os.environ.get("AGENT_HOST", False)
DEFAULT_LOGGER_NAME = "maestro_logger"
LOG_LEVEL = os.environ.get("LOG_LEVEL", ... |
11447650 | import unittest
from wiki_dump_reader import Cleaner
class TestRemoveRefs(unittest.TestCase):
def setUp(self):
self.cleaner = Cleaner()
def test_remove_ref_type_1(self):
text = '數學有着久遠的歷史。它被認為起源於[[人|人類]]早期的生產活動:[[中國]]古代的[[六藝|六艺]]之一就有「數」<ref>《' \
'周礼·地官司徒·保氏》:「保氏掌谏王恶而养国子以道。乃教之六... |
11447662 | from setuptools import setup
import sys
# Make sure we have the right Python version.
if sys.version_info[:2] < (2, 7):
print("Phon requires Python 2.7 or newer. Python %d.%d detected" % sys.version_info[:2])
sys.exit(-1)
sys.path.append('phon')
setup(name='phon',
version='0.1.0',
author='<NAME... |
11447726 | import FWCore.ParameterSet.Config as cms
l1GtParametersTester = cms.EDAnalyzer("L1GtParametersTester"
)
|
11447739 | from django.test import SimpleTestCase
from robber import expect
from mock import patch
from twitterbot.text_extractors import TweetTextExtractor, HashTagTextExtractor, URLContentTextExtractor
from twitterbot.factories import TweetFactory, MockTweepyWrapperFactory
class TweetTextExtractorTestCase(SimpleTestCase):
... |
11447781 | import streamlit as st
from bert_serving.client import BertClient
from client.solr_client import SolrClient
from client.utils import get_solr_vector_search
import pandas as pd
import plotly.graph_objects as go
st.write("Connecting the BertClient...")
bc = BertClient()
st.write("Connecting the SolrClient...")
sc = Solr... |
11447783 | from alephclient.api import AlephAPI, APIResultSet
class TestApiSearch:
fake_url = "http://aleph.test/api/2/"
fake_query = "fleem"
def setup_method(self, mocker):
self.api = AlephAPI(host="http://aleph.test/api/2/", api_key="fake_key")
def test_search(self, mocker):
mocker.patch.obje... |
11447801 | from django.core.management.base import BaseCommand
from django.utils.timezone import timedelta, localtime, make_aware
from member.models import Profile
class Command(BaseCommand):
help = 'Revoke customer phone verification'
def handle(self, *args, **options):
Profile.objects \
.select_r... |
11447854 | from .ecgdigitize import \
estimateRotationAngle, \
SignalDetectionMethod, \
SignalExtractionMethod, \
digitizeSignal, \
GridDetectionMethod, \
GridExtractionMethod, \
digitizeGrid |
11447896 | import sys
import logging
import copy
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn import metrics
from collections import defaultdict
from mllp.utils import UnionFind
THRESHOLD = 0.5
class RandomlyBinarize(torch.autograd.Function):
"""... |
11447972 | from deepsplines.networks.twoDnet import TwoDNet
from deepsplines.networks.resnet_cifar import ResNet32Cifar
from deepsplines.networks.nin_cifar import NiNCifar
from deepsplines.networks.convnet_mnist import ConvNetMnist
__all__ = ["TwoDNet", "ResNet32Cifar", "NiNCifar", "ConvNetMnist"]
|
11447980 | import uuid
import random
import socket
import struct
import datetime
import time
def set_sourceIp():
sourceIp = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
# checking if 0.0.0.0 or 255.255.255.255. Still allows private IP addresses
if sourceIp == "0.0.0.0" or sourceIp == "255.255.2... |
11447993 | import sqlite3
def main(par_id, input_db):
con = sqlite3.connect(input_db)
cur = con.cursor()
cur.execute('select * from tsk_files')
item = get_column_dict(cur)
file_info = []
id = 1
for data in cur:
for idx, i in enumerate(item):
item[i] = data[idx]
# id, fil... |
11448040 | from DataStore import DataStore
# U3 ... is the unmodified column 3. Works only because 3 is in the unmodified list (see FDAXDataStore.py, search for unmodified_group)
# features_list is the list of features to extract from the input
# TODO: the Input for the unmodified group and where bid and ask are located should b... |
11448119 | import string
import requests
from .Invoices import invoices_from_dict
from .PgpList import (PpgList, ppg_list_from_dict)
from .PpgReadingForMeter import PpgReadingForMeter, ppg_reading_for_meter_from_dict
login_url = "https://ebok.pgnig.pl/auth/login?api-version=3.0"
devices_list_url = "https://ebok.pgnig.pl/crm/ge... |
11448130 | import torch
def test_model(model, data):
probs = model(data)
y_pred = probs.argmax(1)
y_true = torch.tensor([5, 0])
assert torch.all(torch.eq(y_pred, y_true))
|
11448131 | import pydantic
import simplejson
def _nan_safe_json_dumps(*args, **kwargs):
return simplejson.dumps(*args, **kwargs, ignore_nan=True)
class APIBaseModel(pydantic.BaseModel):
"""Base model for API output."""
class Config:
json_dumps = _nan_safe_json_dumps
# TODO(tom): Try fix all the e... |
11448145 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
def GetPhases(item):
if hasattr(item, "CreatedPhaseId"):
return item.Document.GetElement(item.CreatedPhaseId), item.Document.GetElement(item.DemolishedPhaseId)
else: return None, None
items = UnwrapElement(IN[0])
if isinstance(IN[0], list): ... |
11448185 | from snowddl.blueprint import MaterializedViewBlueprint, ViewColumn, Ident, SchemaObjectIdent
from snowddl.parser.abc_parser import AbstractParser, ParsedFile
materialized_view_json_schema = {
"type": "object",
"properties": {
"columns": {
"type": "object",
"additionalPropertie... |
11448197 | from ._base import DanubeCloudCommand, CommandError, lcd
class Command(DanubeCloudCommand):
help = 'Create git version tag.'
args = '<name> [description]'
name = ''
desc = ''
def git_tag(self, app, git_path):
with lcd(git_path):
self.local('git tag -a %s -s -m \'%s\'' % (self.... |
11448219 | import urwid
class LoggingView(urwid.WidgetWrap):
"""
LoggingView contains a Box widget that renders all logging messages
for the TUI and CLI processes to the screen.
"""
def __init__(self, model, height):
"""
Parameters
----------
model : ConfigurationModel
... |
11448222 | import sqlite3
import numpy
import data_algebra.test_util
from data_algebra.data_ops import *
from data_algebra.SQLite import SQLiteModel
import data_algebra
import data_algebra.util
import pytest
def test_if_else():
d = data_algebra.default_data_model.pd.DataFrame(
{"a": [True, False], "b": [1, 2], ... |
11448234 | import os
import sys
import copy
import json
import math
import torch
import pickle
import random
import logging
import logging.config
import numpy as np
import torch.nn as nn
from collections import Counter
from numba import guvectorize
from scipy.sparse import csr_matrix
from imblearn.over_sampling import SMOTE, AD... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.