id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9992959 | import copy
import torch
import random
import warnings
import argparse
import data_utils
import graph_utils
import numpy as np
import pickle as pkl
from tree import Tree
from graph2tree import *
warnings.filterwarnings('ignore')
if __name__ == "__main__":
main_arg_parser = argparse.ArgumentParser(description="pa... |
9992976 | from collections import Counter
import numpy
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import compute_class_weight
def get_class_labels(y):
"""
Get the class labels
:param y: list of labels, ex. ['positive', 'negative', 'positive', 'neutral', 'posi... |
9992996 | import django
import os
import django.contrib.auth.models as models
import pickle
def save_users():
users = models.User.objects.all()
shadow = []
for user in users:
shadow.append([user.username, user.password, user.is_superuser])
with open(os.environ['VIP_DJANGO_PASSWD'], 'wb') as fid:
pickle.dump(shad... |
9993025 | import os
from PIL import Image, ImageDraw
# import geojson
import csv
path="../famous_datasets/SpaceNet/processedBuildingLabels/vectordata/geojson"
outpath="../famous_datasets/SpaceNet/processedBuildingLabels/vectordata/png"
files = sorted(os.listdir(path))
out = Image.new("L",(49,87))
dout = ImageDraw.Draw(out)
... |
9993071 | from data_handler import DataHandler
from scanner import Scanner
from datetime import datetime
from queue import Queue
from threading import Thread
import sys
def printStats(devices_count, sensor_type):
time = datetime.now().strftime("%H:%M:%S")
print("%s | %d {:>4} devices found.".format(
sensor_type... |
9993074 | from build_base import build
if __name__ == '__main__':
build(output_folder_name="Windows",
target_platform_name="Windows",
python_platform_check_string="win32",
spec_files=[
"palyanytsya.spec",
"pyrizhok.spec"
])
|
9993077 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils.init_weights import init_weights, normalized_columns_initializer
from core.mo... |
9993083 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "AYL"
addresses_name = "2021-03-18T17:32:05.640816/Bucks_dedupe.tsv"
stations_name = "2021-03-18T17:32:05.640816/Bucks_dedupe.tsv"
elections = ["2021-05-06"... |
9993094 | import locale
import pytest
__all__ = ['fail_on_ascii', 'ack_2to3']
is_ascii = locale.getpreferredencoding() == 'ANSI_X3.4-1968'
fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale")
ack_2to3 = pytest.mark.filterwarnings('ignore:2to3 support is deprecated')
|
9993225 | import pytest
@pytest.mark.asyncio
async def test_RpcMethodNotFoundError(rpc_context):
from aiohttp_json_rpc import RpcMethodNotFoundError
client = await rpc_context.make_client()
with pytest.raises(RpcMethodNotFoundError):
await client.call('flux_capatitor_start')
@pytest.mark.asyncio
async d... |
9993260 | from blinker import Namespace
signals = Namespace()
request_finished = signals.signal('request_finished')
request_started = signals.signal('request_started')
request_error = signals.signal('request_error')
pre_save = signals.signal('pre_save')
post_save = signals.signal('pre_save')
|
9993289 | from .net import SlimYOLOv2
import torch
class Test():
def __init__(self, classes, anchors, input_size, saved_state_path, log, conf_thresh=0.3, nms_thresh=0.3, device="cuda"):
self.classes = classes
self.log = log
self.input_size = input_size
self.device = device
if not anch... |
9993299 | from collie.model.base.base_pipeline import *
from collie.model.base.layers import *
from collie.model.base.multi_stage_pipeline import *
from collie.model.base.trainer import *
|
9993358 | import configparser
import psycopg2
from sql_queries import create_table_queries, drop_table_queries
def drop_tables(cur, conn):
"""Drop any existing tables from sparkifydb.
Keyword arguments:
* cur -- cursory to connected DB. Allows to execute SQL commands.
* conn -- (psycopg2) connection to Po... |
9993362 | from ..broker import Broker
class IfGroupBroker(Broker):
controller = "if_groups"
def index(self, **kwargs):
"""Lists the available if groups. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is most effici... |
9993367 | from .dukemtmcreid_interpretation import DukeMTMC_Interpretation
from .market1501_interpretation import Market1501_Interpretation
from .duketomarket_interpretation import DukeToMarket_Interpretation
from .markettoduke_interpretation import MarketToDuke_Interpretation
# AND
from .market1501_and_interpretation import M... |
9993387 | from binding import *
from ..namespace import llvm
Reloc = llvm.Namespace('Reloc')
Reloc.Enum('Model',
'Default', 'Static', 'PIC_', 'DynamicNoPIC')
CodeModel = llvm.Namespace('CodeModel')
CodeModel.Enum('Model',
'Default', 'JITDefault', 'Small', 'Kernel', 'Medium', 'Large')
TLSModel = llvm... |
9993399 | import argparse
import torch.nn as nn
import torch
from torch.optim import lr_scheduler
import numpy as np
import random
import pdb
class TrainOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.parser.... |
9993404 | from uri.user import *
import flask
from modern_paste import app
import config
import constants.api
import database.user
from flask_login import current_user
from flask_login import login_user
from api.decorators import require_form_args
from api.decorators import require_login_api
from util.exception import *
@app... |
9993427 | import time
import ftrobopy
# Einlesen und Abspeichern eines TXT Camera Bildes (jpeg)
txt=ftrobopy.ftrobopy('auto')
time.sleep(2)
txt.startCameraOnline()
time.sleep(2.5)
pic = txt.getCameraFrame()
with open('TXTCamPic.jpg', 'wb') as f:
f.write(bytearray(pic))
|
9993440 | from django.db import models
class User(models.Model):
user = models.IntegerField(unique=True)
group = models.TextField()
nickname = models.TextField(null=True)
name = models.TextField(null=True)
sno = models.TextField(null=True)
tel = models.TextField(null=True)
email = models.TextField(n... |
9993442 | import torch
from torch.autograd import Variable
import torch.utils.data
from gan import GAN_base
class WGAN(GAN_base):
def __init__(self, netG, netD, optimizerD, optimizerG, opt):
GAN_base.__init__(self, netG, netD, optimizerD, optimizerG, opt)
self.clamp_lower = opt.wgan_clamp_lower
self... |
9993460 | import unittest
import torch
from pytorch_adapt.layers import BNMLoss
from .. import TEST_DEVICE, TEST_DTYPES
class TestBNMLoss(unittest.TestCase):
def test_bnm_loss(self):
for dtype in TEST_DTYPES:
if dtype == torch.float16:
continue
batch_size = 32
... |
9993461 | from __future__ import print_function
import argparse
import copy
import nltk
import time
import numpy as np
from rdkit import Chem
from rdkit import rdBase
import cfg_util
import rdock_util
import zinc_grammar
rdBase.DisableLog('rdApp.error')
GCFG = zinc_grammar.GCFG
def CFGtoGene(prod_rules, max_len=-1):
gen... |
9993471 | from eeg_utils import simulate_eeg
from bcipy.language_model.oclm_language_model import LangModel
import sys
sys.path.append('.')
def main():
"""Runs the demo"""
# init LMWrapper
lmodel = LangModel(logfile="lmwrap.log")
# init LM
nbest = 3
lmodel.init(nbest=nbest)
return_mode = 'letter'
... |
9993480 | from pygears.typing.visitor import TypingVisitorBase
from pygears.typing import bitw, is_type
class SVGenTypeVisitor(TypingVisitorBase):
struct_str = "typedef struct packed {"
union_str = "typedef union packed {"
def __init__(self, name, basic_type='logic', depth=4):
self.struct_array = []
... |
9993544 | import time
from typing import List, Optional
import pytest
import pythonbible as bible
from pythonbible.formatter import BookTitles
def test_format_scripture_references(
normalized_references_complex: List[bible.NormalizedReference],
formatted_reference: str,
) -> None:
# Given a list of normalized ref... |
9993554 | import numpy as np
import pyro
import pyro.distributions as dist
import torch
from pyro.ops.stats import quantile
import forecast
import pyro_model.helper
def gumbel_softmax(logits, dim=-1, temperature=0.1, eps=1e-9):
# get gumbel noise
noise = torch.rand(logits.size(), dtype=logits.dtype, device=logits.devi... |
9993589 | import math
import models
import tensorflow as tf
import numpy as np
import utils
from tensorflow import flags
import tensorflow.contrib.slim as slim
FLAGS = flags.FLAGS
class LstmPositionalAttentionMaxPoolingModel(models.BaseModel):
"""Max pooling over temporal weighted sums (attention) of lstm outputs."""
def c... |
9993593 | import cProfile
from data import serialize, test_object
def do_cprofile(func):
def profiled_func(*args, **kwargs):
profile = cProfile.Profile()
try:
profile.enable()
result = func(*args, **kwargs)
profile.disable()
return result
finally:
... |
9993603 | import logging
import bpy
from bpy.types import Operator, Menu
from . constants import Constants
class BatchLabsBlenderSubMenu(bpy.types.Menu):
bl_label = Constants.SUBMIT_MENU_LABEL
bl_idname = "OBJECT_MT_batch_labs_blender_sub_menu"
def __init__(self):
self.log = logging.getLogger(Constants.LOG... |
9993611 | import ntpath
import os
import sys
import tempfile
import unittest
from itertools import count
try:
from unittest.mock import Mock, patch, call, mock_open
except ImportError:
from mock import Mock, patch, call, mock_open
from flask import Flask, render_template_string, Blueprint
import six
import flask_s3
from... |
9993630 | from .epicurve_plots import plot_area_summary
from .intervention_plots import *
from .param_plots import *
|
9993632 | from collections import deque
from ParadoxTrading.Indicator.IndicatorAbstract import IndicatorAbstract
from ParadoxTrading.Utils import DataStruct
class EFF(IndicatorAbstract):
def __init__(
self, _period: int, _use_key: str = 'closeprice',
_idx_key: str = 'time', _ret_key: str = 'eff'
... |
9993661 | from enum import Enum
from queue import PriorityQueue
import numpy as np
from itertools import cycle
def getOrigin(filename):
"""
returns a tuple of lat0 and lon0)
"""
with open("data/colliders.csv") as f:
data0 = f.readline()
data0 = data0[0:-2]
data0 = data0.split(', ')
lat0 = ... |
9993694 | import numpy
def footprint_calc(spans, l_fus):
y1 = spans[0]*0.5
try:
y2 = spans[1]*0.5
except:
y2 = 0.0
l = (y2*y2 + l_fus*l_fus-y1*y1)/(2.0*l_fus)
#circle radius enclosing both surfaces
R = numpy.sqrt(l*l+y1*y1)
footprint = 2*R
return footprint |
9993697 | from .base import BaseChart
import json
from ..utils import JSONEncoderForHTML
class BaseMorrisChart(BaseChart):
def get_data(self):
header = self.header
data = super(BaseMorrisChart, self).get_data()
data_only = data[1:]
rows = []
for row in data_only:
rows.ap... |
9993707 | import deep_architect.core as co
import deep_architect.modules as mo
import deep_architect.hyperparameters as hp
import deep_architect.utils as ut
from deep_architect.searchers.common import random_specify
import deep_architect.helpers.keras_support as hke
import deep_architect.visualization as vi
D = hp.Discrete
fro... |
9993719 | from Katari.sip import SipMessage
class BadRequest400(SipMessage):
def __init__(self):
pass
class Unauthorized401(SipMessage):
def __init__(self):
pass
class PaymentRequired402(SipMessage):
def __init__(self):
pass
class Forbidden403(SipMessage):
def __init__(self):
... |
9993738 | import StockAnalysisSystem.core.api as sasApi
from StockAnalysisSystem.core.SubServiceManager import SubServiceContext
from StockAnalysisSystem.core.Utility.event_queue import Event, EventDispatcher
# 事件入口
# 定时事件
# 调用事件
# 订阅事件
# 线程入口
# Polling入口
# 注册系统调用
SERVICE_ID = '7129e9d2-4f53-4826-9161-c568ced52d02'... |
9993769 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .sampler_factory import get_sampler
|
9993789 | class Dir:
def __init__(self):
self.child = collections.defaultdict(Dir)
self.id = -1
self.isFile = False
self.t = 0
class LogSystem:
graDic = {'Year':0, 'Month':1, 'Day':2, 'Hour':3, 'Minute':4, 'Second':5}
def __init__(self):
self.d = Dir()
def put(se... |
9993797 | import argparse
from builtins import input
from collections import defaultdict
import datetime
import logging
import os
import pprint
import re
import sys
import ee
import utils
# from . import utils
def main(ini_path=None):
"""Remove earlier versions of daily tcorr images
Parameters
----------
ini... |
9993798 | from tool.runners.python import SubmissionPy
from collections import defaultdict
import heapq
class ThomasSubmission(SubmissionPy):
def run(self, s):
lines = s.split("\n")
requirements = defaultdict(set)
for line in lines:
splitted = line.split()
from_node, to_node ... |
9993856 | from unittest import TestSuite
import test_tps
def test_suite():
suite = TestSuite()
suite.addTest(test_tps.test_suite())
return suite
|
9993874 | import re
from .default import DefaultParser
class SaladParser(DefaultParser):
name = "salad"
def command_matches(self, command):
return "salad" in command
def num_passed(self, result):
# 3 steps (3 passed)
m = re.findall('(\d+) steps \((\d+) passed\)', result.cleaned_output)
... |
9993877 | import paho.mqtt.client as mqtt
from time import sleep
from RobotDance import RobotDance
from RobotWheels import RobotWheels
from RobotBeep import RobotBeep
from RobotCamera import RobotCamera
from gpiozero import DistanceSensor
distance_sensor = DistanceSensor(echo=18, trigger=17)
def on_message(client, us... |
9993887 | from keras.layers import Conv2D, Input, Activation
from keras.models import Model
def print_model():
"""
Creates a sample model and prints output shape
Use this to analyse convolution parameters
"""
# create input with given shape
x = Input(shape=(512,512,3))
# create a convolution layer
... |
9993896 | from happytransformer import HappyTokenClassification
def example_5_0():
happy_toc = HappyTokenClassification("BERT", "dslim/bert-base-NER") # default
happy_toc_large = HappyTokenClassification("XLM-ROBERTA", "xlm-roberta-large-finetuned-conll03-english")
def example_5_1():
happy_toc = HappyTokenClassi... |
9993964 | class Solution:
def findLucky(self, arr: List[int]) -> int:
c = collections.Counter(arr)
res = -1
for i, v in c.items():
if i == v:
res = max(res, i)
if res != -1:
return res
return -1 |
9993979 | import os
import pickle
from typing import Optional, Tuple
import numpy as np
import torch
from anndata import AnnData, read
from sklearn.utils import deprecated
from scvi._compat import Literal
def _should_use_legacy_saved_gimvi_files(dir_path: str, file_name_prefix: str) -> bool:
new_model_path = os.path.join... |
9994077 | def createStack():
stack=[]
return stack
def isEmpty(stack):
if sizeStack(stack)==0:
return true
def sizeStack(stack):
return len(stack)
def push(stack,val):
stack.append(val)
def pop(stack):
if isEmpty(stack):
return
return stack.pop()
def reverse(s):
n=len(s)
stack... |
9994117 | import pickle
import gdb # pylint: disable=E0401
from . import data_extractor
from . import util
try:
import scipy.io
SCIPY_AVAILABLE = True
except ImportError:
SCIPY_AVAILABLE = False
class SaveMat(gdb.Command):
def __init__(self):
super(SaveMat, self).__init__("savemat", gdb.COMMAND_OBSC... |
9994129 | import pytest
import zproc
@pytest.fixture
def ctx():
return zproc.Context()
def test_not_pass_ctx(ctx):
@ctx.spawn(pass_context=False)
def my_process():
return 0
assert my_process.wait() == 0
def test_pass_ctx(ctx):
@ctx.spawn(pass_context=True)
def my_process(ctx):
asse... |
9994167 | import json
import os
import sys
from collections import defaultdict
from typing import Dict, Any, Iterable, Tuple
import glob
import argparse
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))))
JsonDict = Dict[str, Any]
def process_dataset(data: JsonDict, split_type: str) -> Ite... |
9994213 | import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import feature_refine_cuda
class FeatureRefineFunction(Function):
"""Feature refine class."""
@staticmethod
def forward(ctx, features, be... |
9994245 | import typing
from test import db_kwargs
import pytest
import redshift_connector
access_key_id: str = "replace_me"
secret_access_key: str = "replace_me"
session_token: str = "<PASSWORD>_me"
"""
This is a manually executable test. It requires valid AWS credentials.
A Redshift authentication profile will be created ... |
9994250 | import unittest
from pyvalidator.is_slug import is_slug
from . import print_test_ok
class TestIsSlug(unittest.TestCase):
def test_valid_slug(self):
for i in [
'foo',
'foo-bar',
'foo_bar',
'foo-bar-foo',
'foo-bar_foo',
'foo-bar_foo*7... |
9994254 | import time
import random
import sys
import cv2
import numpy as np
from opencv_samples.common import draw_str
sys.path.append('../')
from modules.tracking import ProcessTracking
p = "../../../piscope-videos/constellation.mp4"
#p = "../../../piscope-videos/jupiter.mp4"
noise_x = 5
noise_y = 5
slope_x = 50 #(0.5 - ran... |
9994267 | from minpiler.typeshed import (
M,
switch1, display1,
setup, time,
)
# large display is 176 x 176
dsize = 176
M.draw.clear(0, 0, 0)
M.draw.stroke(5)
M.draw.color(255, 0, 0, 255)
def posvel(pos, vel):
pos += vel
if pos < 0:
pos = 0
vel = M.abs(vel)
if pos > dsize:
pos ... |
9994274 | import numpy
import torch.nn as nn
import torch.nn.functional as F
from thseq.data.vocabulary import Vocabulary
from thseq.modules.multihead_attention import MultiheadAttention
from ..abs import DecoderBase
class DecoderLayerR2L(nn.Module):
def __init__(self, args, hidden_size, dropout=0.1, relu_dropout=0.):
... |
9994287 | from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models.constants import LOOKUP_SEP
from django.db.models import F
class KeyTextTransformFactory:
def __init__(self, key_name):
self.key_name = key_name
def __call__(self, *args, **kwargs):
return KeyTextTransfor... |
9994311 | def selectionSort(l):
for start in range(len(l)):
#assign start value as minimum value
minpos=start
for i in range(start,len(l)):
if(l[i]<l[minpos]):
minpos=i
(l[start],l[minpos]) = (l[minpos],l[start])
if __name__ == "__main__":
... |
9994339 | from setuptools import setup
setup(
name='scrapy-corenlp',
version='0.2.0',
description='Scrapy spider middleware :: Stanford CoreNLP Named Entity Recognition',
url='https://github.com/vu3jej/scrapy-corenlp',
author='<NAME>',
author_email='<EMAIL>',
license='BSD-2-Clause',
packages=['s... |
9994359 | from tir import Webapp
import unittest
import time
#//-------------------------------------------------------------------
#/*/{Protheus.doc} MATC300 - DIAGNOSTICO BLOCO K
#
#@author <NAME>
#@since 16/09/2019
#@version 1.0
#/*/
#//-------------------------------------------------------------------
class MATC300(unitte... |
9994378 | import numpy as np
from scipy.stats import wishart
from scipy.special import multigammaln
x = np.array([
[10, 2, 3],
[2, 10, 1],
[3, 1, 10]
])
v = np.array([
[5, 1, 0],
[1, 5, 1],
[0, 1, 5]
])
n = 4
def logpdf(x, v, n):
correction = (n * v.shape[0] / 2.)*np.log(2) + \
mul... |
9994385 | def test():
assert (
"token1.similarity(token2)" or "token2.similarity(token1)" in __solution__
), "Compares-tu la similarité entre les deux tokens ?"
assert (
0 <= float(similarity) <= 1
), "La valeur de similarité doit être un nombre flottant. L'as-tu calculé correctement ?"
__msg_... |
9994427 | def write_ply_with_colors(vertex, tri, wfp):
header = """ply\nformat ascii 1.0\nelement vertex {}\nproperty float x\nproperty float y\nproperty float z\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nelement face {}\nproperty list uchar int vertex_indices\nend_header"""
n_vertex = vertex.shape[0]
n_... |
9994437 | import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
import traitlets as traitlets
def _wf_eq(wf_type, amp, sigma, cycles, width, t):
samps = t.size
if wf_type == 'Gaussian':
sig = amp * np.exp(-0.5 * ((t - max(t) / 2) / sigma) ** 2)
elif wf_type == 'Gaussian Derivative'... |
9994444 | import cymunk as cy
from os.path import dirname, join
from kivy.clock import Clock
from kivy.app import App
from kivy.graphics import Color, Rectangle
from kivy.uix.widget import Widget
from kivy.properties import DictProperty, ListProperty
from kivy.core.image import Image
from random import random
from kivy.lang impo... |
9994454 | from typing import Optional
from ..apibase import SlobsService, Event
from .typedefs import (
ISceneCollectionsManifestEntry,
ISceneCollectionSchema,
ISceneCollectionCreateOptions,
)
from .factories import source_factory, sceneitem_factory
def iscenecollectionmanifestentry_factory(json_dict):
return I... |
9994497 | class MatchFilter:
'''
Collection of flags used to filter word matches
To use this class:
1) Create an instance
2) Set desired parameters, or remove desired parameters, from lists
3) Pass to a method which accepts a filter
Examples: let `filt=MatchFilter()`
filt.frequenc... |
9994538 | import socket
import sys
if __name__ == '__main__':
ip = 'x.x.x.x'
port = 1234
try:
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.errror:
print("Failed to create socket")
sys.exit()
'''
try:
host = socket.gethostbyname("www.goog... |
9994542 | import lightgbm as lgb
import pandas as pd
df = pd.read_csv('test/support/data.csv')
X = df.drop(columns=['y'])
y = df['y']
X_train = X[:300]
y_train = y[:300]
X_test = X[300:]
y_test = y[300:]
print('test_regression')
regression_params = {'objective': 'regression', 'verbosity': -1}
regression_train = lgb.Dataset(... |
9994565 | import asyncio
from unittest import mock
import asynctest
import pytest
from aioredis_cluster.pooler import Pooler
from aioredis_cluster.structs import Address
def create_pool_mock():
mocked = mock.NonCallableMock()
mocked.closed = False
mocked.wait_closed = asynctest.CoroutineMock()
return mocked
... |
9994572 | import json
from datetime import datetime, timedelta
from unittest import TestCase, mock
import pytest
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core import mail
from django.urls import reverse
from pytz import UTC
from rest_framework import status
from rest_framework.... |
9994578 | class HTTPRequest:
path: str
method: str
http_version: str
headers: dict
cookies: dict
body: bytes
params: dict
def __init__(
self,
path: str = "",
method: str = "",
http_version: str = "",
headers: dict = None,
cookies: dict = None,
... |
9994583 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn.utils import check_random_state
__all__ = ['make_cubic', 'make_quadratic', 'make_polynomial',
'make_exponential']
def make_cubic(n_samples=500, n_features=10, n_i... |
9994585 | import time as tm
import numpy as np
from pylab import *
def Jacobi(A, b, x, eps=1e-4, xs=None):
x = x.copy()
cnt = 0
while True:
cnt += 1
x_old = x.copy()
for i in range(b.shape[0]):
x[i] += (b[i] - A[i].dot(x_old)) / A[i, i]
if abs(x_old - x).max() < eps:
return x, cnt
def GS(A, b, x, eps=1e-4, xs... |
9994646 | import numpy as np
import pandas as pd
from pandas.tseries.frequencies import to_offset
def align_outputs(
y_predicted,
X_trans,
X_test,
y_test,
target_column_name,
predicted_column_name="predicted",
horizon_colname="horizon_origin",
):
"""
Demonstrates how to get the output aligne... |
9994661 | from unittest.mock import MagicMock
import pytest
dulwich = pytest.importorskip("dulwich")
from prefect import context, Flow
from prefect.storage import Git
@pytest.fixture
def fake_temp_repo(monkeypatch):
temp_repo = MagicMock()
temp_repo.return_value.__enter__.return_value.temp_dir.name = "/tmp/test/"
... |
9994662 | from typing import Iterable
from pandas import DataFrame, Series
def eval_features_frame(data: DataFrame, prefix='mentioned_'):
"""Parses stringified lists and sets of features in columns of `data`."""
return (
data
[data.columns[data.columns.str.startswith(prefix)]]
.applymap(eval)
... |
9994689 | from server import app as application
if __name__ == "__main__":
application.run(debug=False, host='0.0.0.0')
|
9994718 | from . import test_algorithm
from . import test_cli
import os.path
import test.support
import unittest
def test_main():
for mod in (test_algorithm, test_cli):
getattr(mod, 'test_main')()
if __name__ == '__main__':
test_main()
|
9994726 | import logging
import re
import time
from os import getenv
import sentry_sdk
from deeppavlov import build_model
from flask import Flask, request, jsonify
sentry_sdk.init(getenv("SENTRY_DSN"))
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getL... |
9994754 | import os
import asyncio
from pyrogram import filters
from pyrogram.types import Message
from pymongo import MongoClient
from nksama import bot
from nksama.db import MONGO_URL as db_url
users_db = MongoClient(db_url)['users']
col = users_db['USER']
grps = users_db['GROUPS']
@bot.on_message(filters.command("stats"))... |
9994806 | from collections import OrderedDict
import numpy as np
from scipy import interpolate
from pycycle import constants
from pycycle.thermo.cea.thermo_data import co2_co_o2
from pycycle.thermo.cea.thermo_data import janaf
from pycycle.thermo.cea.thermo_data import wet_air
#from ad.admath import log
from numpy import log... |
9994828 | import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from os import getcwd, name
from os.path import join
import numpy
from Cython.Build import cythonize
pwd = getcwd()
sources = [join(pwd, 'dSFMT_wrapper.pyx'),
join(pwd, 'dSFMT.c')]
defs = [('HAVE_SSE2', '1'),... |
9994831 | from pwn import *
elf = ELF('no-bof')
#lib = ELF('x32_libc-2.19.so')
lib = ELF('/lib/i386-linux-gnu/libc-2.23.so')
context.arch = 'i386'
def leakAll():
r.sendlineafter('Your input: ','4 %4$p %8$p %21$p \x00/bin/sh;')
r.recvuntil('Your choice is:4 ')
def Insert(title,price):
r.sendlineafter('Your input: ','1')
r.... |
9994897 | from __future__ import division,unicode_literals,print_function,absolute_import
from builtins import map, range, chr, str
from io import open
from future import standard_library
standard_library.install_aliases()
from .file import File, WrongFormatError, BrokenFormatError
from .csv_file import CSVFile
import numpy as ... |
9994901 | from pathlib import Path
import mimetypes
import functools
def banner(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""
Añade como cabecera la ruta desde la cual se listan los archivos.
"""
print(f"=== {args[0]} ===")
function(*args, **kwargs)
... |
9994911 | expected_output = {
"GigabitEthernet0/0/0": {
"switching_path": {
"processor": {
"pkts_in": 33,
"chars_in": 2507,
"pkts_out": 33,
"chars_out": 2490,
},
"route_cache": {"pkts_in": 0, "chars_in": 0, "pkts_out":... |
9994916 | TEST_VC_DOCUMENT_SIGNED_ED25519 = {
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://w3id.org/citizenship/v1",
"https://w3id.org/security/bbs/v1",
],
"id": "https://issuer.oidp.uscis.gov/credentials/83627465",
"type": ["VerifiableCredential", "PermanentResidentCar... |
9994933 | from dateutil.tz import tzlocal
from paikkala.models import Ticket
from core.csv_export import CsvExportMixin
from .models import SignupExtra
class SignupExtraAfterpartyProxy(SignupExtra, CsvExportMixin):
class Meta:
proxy = True
@property
def personnel_class_name(self):
from badges.mo... |
9994962 | from nltk.util import ngrams
# This class makes use of nltk library for generating n-grams given a query
class ngramsEngine(object):
def __init__(self):
self = self
# Module to print n-grams
def printNGrams(self,ngramsList):
for token in ngramsList:
print(token.strip())
# Module that generates n-grams l... |
9994982 | import os
import base64
from algosdk.v2client import algod, indexer
from algosdk import mnemonic, account, encoding
from algosdk.future import transaction
ALGOD_ENDPOINT = os.environ['ALGOD_ENDPOINT']
ALGOD_TOKEN = os.environ['ALGOD_TOKEN']
INDEXER_ENDPOINT = os.environ['INDEXER_ENDPOINT']
INDEXER_TOKEN = os.environ[... |
9994989 | import argparse
from os.path import abspath
def parse_args(dirs):
default_uri_prefix = 'https://rdmorganiser.github.io/terms'
parser = argparse.ArgumentParser(
description='Rdmo catalog sanitizer replacing accidentally used uris',
formatter_class=argparse.RawTextHelpFormatter
)
parser.... |
9995019 | from __future__ import annotations
from ctc import evm
from ctc import spec
from .. import analytics_spec
async def async_compute_dex_volume(
blocks: list[int], verbose: bool = False
) -> analytics_spec.MetricGroup:
import asyncio
volume_tasks = []
for pool_name, pool_info in analytics_spec.dex_pool... |
9995053 | from __future__ import absolute_import
import os
import sys
import json
from todo.commands.base import Command
from todo.utils.styles import Fore, Style
class AddCommand(Command):
def update_todos(self, todos=[]):
"""Creates a copy of the todo list with the new item"""
new_todos = todos.copy()
... |
9995066 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
class patcher(patcher):
def __init__(self, body='./body/body_blanca.png', **options):
super().__init__('ブランカ', body=body, pantie_pos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.