id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11541615 | class Wrapper:
"""
Wraps an object and pretends to be it.
Can be modified/extended without affecting the underlying object.
"""
def __init__(self, target, *, affect_only_functions=True):
self._target = target
def __bool__(self):
return bool(self._target)
def __call__(self,... |
11541637 | import time
import numpy as np
from Little import solve_tsp
from utils import read_graph_matrix, draw_graph_with_path
if __name__ == '__main__':
m = read_graph_matrix('lab5.in')
out = file('report.md', 'w')
out.write('# lab5\nPazhitnykh Ivan\n\n* Solve **Travelling Salesman Problem**, with matrix:\n')
... |
11541639 | from distutils.core import setup
from Cython.Distutils import Extension
from Cython.Distutils import build_ext
import numpy
import os, tempfile, subprocess, shutil
# see http://openmp.org/wp/openmp-compilers/
omp_test = r"""#include <omp.h>
#include <stdio.h>
int main() {
#pragma omp parallel
printf("Hello from threa... |
11541694 | import h5py
import sys
file = h5py.File(sys.argv[1], "r")
#for chr in file.keys():
# data = file[chr][:]
# print(chr, data.mean())
for line in open(sys.argv[2], "r"):
line = line.split("\t");
c,b,e=line[0], int(line[1]), int(line[2])
print(c,b,e, file[c][b:e].mean())
|
11541700 | import random
import time
import pickle
from tqdm import tqdm
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms
from model.attention_ocr import OCR
from utils.dataset import CaptchaDataset
from utils.train... |
11541705 | from uploader import AbstractUploader
class Uploader(AbstractUploader):
@property
def request_url(self) -> str:
return 'https://mp.yidianzixun.com/upload?action=uploadimage'
@property
def file_key(self) -> str:
return 'upfile'
@property
def parsed(self) -> str:
return ... |
11541709 | from datetime import datetime
import pytest
from advent_readme_stars.advent import most_recent_advent_year
@pytest.mark.parametrize(
"now, expected",
[
(datetime(1999, 11, 30), 1998),
(datetime(1999, 12, 1), 1999),
(datetime(1999, 12, 31), 1999),
(datetime(2000, 1, 1), 1999),... |
11541791 | from vel.api.base import Model
from torch.optim import Optimizer
class OptimizerFactory:
""" Base class for optimizer factories """
def instantiate(self, model: Model) -> Optimizer:
raise NotImplementedError
|
11541823 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import modules.registry as registry
from .innerproduct_similarity import InnerproductSimilarity
@registry.Query.register("DN4")
class DN4(nn.Module):
def __init__(self, in_channels, cfg):
super().__init__()
self.n_way... |
11541825 | import os
import random
import signal
import subprocess
import time
import unittest
import warnings
import psutil # type: ignore
from os import path
from typing import List, Tuple
from tests.utils.project import (
GenerateProjectFromFixture,
GenerateProjectWithPyProjectToml,
TempProjectDir
)
class Taski... |
11541860 | import yaml
import caffe
from multiprocessing import Process, Queue
from sbir_util.batch_manager import MemoryBlockManager
from image_proc import Transformer
from sample_util import *
class TripletSamplingLayer(caffe.Layer):
def setup(self, bottom, top):
"""Setup the TripletSamplingLayer."""
... |
11541890 | class Thimbles:
def thimbleWithBall(self, swaps):
i = 1
for s in swaps:
a, b = map(int, s.split("-"))
if a == i:
i = b
elif b == i:
i = a
return i
|
11541926 | from myjwt.vulnerabilities import confusion_rsa_hmac
jwt = (
"<KEY>"
"-A2JQ6xcAVucXRhZbdBbAM2DG8io_brP_ROAqYaNlvRVsztXoPHFz_e7D2K0q6f02RXeRwZJGOhy0K"
<KEY>"
<KEY>"
<KEY>"
)
# Header: {"typ": "JWT", "alg": "RS256"}
# Payload: {"login": "a"}
file = "public.pem"
# file is a path file of your public ke... |
11542007 | from src.xcode_project_reader import XcodeProjectReader
from helpers import path_helper
import unittest
class TestXcodeProjectReader(unittest.TestCase):
def test_targets(self):
project = XcodeProjectReader(path_helper.xcode_example_project())
output = list(project.targets())
expectation = [... |
11542017 | import warnings
import numpy as np
from qiskit import Aer, execute, QuantumCircuit
from qiskit.circuit.library import (HGate, SdgGate, SGate, TGate,
XGate, YGate, ZGate)
from qiskit.extensions.unitary import UnitaryGate
from qiskit.providers.aer.noise import NoiseModel
from deltal... |
11542042 | import pytest
import isobar as iso
@pytest.fixture()
def dummy_timeline():
timeline = iso.Timeline(output_device=iso.io.DummyOutputDevice(), clock_source=iso.DummyClock())
timeline.stop_when_done = True
return timeline |
11542072 | import jwt
import json
from django.http import JsonResponse
from django.conf import settings
from user.models import User
def login_check(func):
def wrapper(self, request, *args, **kwargs):
try:
access_token = request.headers.get('Authorization', None)
if not acces... |
11542080 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.plant import TemperingValve
log = logging.getLogger(__name__)
class TestTemperingValve(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
... |
11542141 | def test():
from math import radians, degrees, pi
class Angle(object):
def __init__(self,rad):
self._rad = rad
@Property
def rad():
'''The angle in radians'''
def fget(self):
return self._rad
def fset(self,angle):
... |
11542167 | from os.path import dirname, join
from pytest import fixture
from shutil import rmtree
from ..asset import Asset
from ..assetset import Assetset
from ..paths import Paths
paths = Paths()
fixtures_dir_path = join(dirname(__file__), 'fixtures', 'assets')
@fixture
def assetset() -> Assetset:
asset = Asset(
... |
11542169 | import os
import unittest
from numpy.testing import assert_array_almost_equal
import scipy.io.matlab
import means
import means.examples
import numpy as np
from means.simulation import SolverException
MODELS = {'p53': means.examples.MODEL_P53}
class TestTrajectoriesMatch(unittest.TestCase):
def _read_data_from_m... |
11542200 | import pytest
import numpy as np
from ..posrich import posrich
import pkg_resources
PATH = pkg_resources.resource_filename(__name__, 'test_data/')
def test_posrich():
"Test positional enrichment"
# load data
X_list = open(PATH+'multiple.txt').read().splitlines()
X_err = 'AGT2HT9'
# test posrich ... |
11542208 | from .acquirer import Acquirer
from datetime import datetime
from urllib.parse import urlparse
import posixpath
import sites
class Instagram(Acquirer):
def __init__(self, colymer: sites.Colymer, instagram: sites.Instagram, collection: str):
super().__init__(colymer)
self.instagram = instagram
... |
11542224 | import numpy as np
import math
import tensorflow as tf
import h5py
import sys
import os
######## OPTIONS #########
ver = 6 # Neural network version
table_ver = 6 # Table Version
hu = 25 # Number of hidden units in each hidden layer in network
saveEvery = 1000 # Epoch frequency of ... |
11542230 | import math
import time
import torch
from utils.utils import print_speed
# -----------------------------
# Main training code for Ocean
# -----------------------------
def ocean_train(train_loader, model, optimizer, epoch, cur_lr, cfg, writer_dict, logger, device):
# unfix for FREEZE-OUT method
# model, optim... |
11542239 | from ..cw_model import CWModel
class AccountingBatch(CWModel):
def __init__(self, json_dict=None):
self.thruDate = None # (String)
self.transactionsClosedDate = None # (String)
self.locationId = None # (Integer)
self.summarizeInvoices = None # (Integer)
self.... |
11542288 | import datetime
from ming.datastore import DataStore
from ming import Session
from ming.orm.ormsession import ThreadLocalORMSession
bind = DataStore('mongodb://localhost:27017/orm_tutorial')
doc_session = Session(bind)
session = ThreadLocalORMSession(doc_session=doc_session)
from ming import schema
from ming.orm.mapp... |
11542365 | class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for p in path.split('/'):
if p not in {'', '.', '..'}:
stack.append(p)
elif p == '..' and stack:
stack.pop()
return '/' + '/'.join(stack)
|
11542409 | import time,sqlite3
import pandas as pd
import sqlalchemy as sqla
from . import config as cfg
__version__ = '0.1.3'
class CypTyper:
'''This is really just a db interface. Typing is done in the db'''
def __init__(self,alleles,variants,dbFile,dbStore=False):
self.alleles = alleles
self.variants... |
11542446 | import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import *
import tensorflow as tf
training_data_df = pd.read_csv("sales_data_training_scaled.csv")
X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values
# Define the model
model ... |
11542457 | from . import nsapiwrapper
from .objects import Nation, Region, World, WorldAssembly, Telegram, Cards, IndividualCards
class Nationstates:
def __init__(self, user_agent, version="11", ratelimit_sleep=True,
ratelimit_limit=40, ratelimit_timeframe=30, ratelimit_sleep_time=4,
ratelimi... |
11542467 | from .vgg16 import get_vgg
from .vgg16_deconv import get_vgg_deconv
from .utils import get_image, store_feature, visualize_layer |
11542470 | import matplotlib.pyplot as plt
import numpy as np
plt.switch_backend('Agg')
#
# Make image array with using matplotlib
#
def plot_to_buf(x: np.ndarray, align: bool = True) -> np.ndarray:
"""
make plotted image given array
:param x: an array to be plotted
:param align: make limit from -1 to +1 on ar... |
11542478 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
def _radar_factory(num_vars):
theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)
... |
11542486 | import requests
import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from .models import IntegrationData
class IntegrationUtils():
@staticmethod
def getNNEProfile(subscription_id):
jwtToken = jwt.encode({'sub': subscription_id}, settings.INTEGRATION_JWT_SECRET,... |
11542544 | from typing import List, Union, Optional
from .cache_manager import CacheManager
from ..__init__ import Guild, UnavailableGuild
class GuildManager(CacheManager):
def __init__(
self, client, guilds: Optional[List[Union[Guild, UnavailableGuild]]] = None
):
if guilds is None:
guilds ... |
11542584 | from pyChemometrics.ChemometricsPCA import ChemometricsPCA
from pyChemometrics.ChemometricsScaler import ChemometricsScaler
from nPYc.objects._dataset import Dataset
import copy
def exploratoryAnalysisPCA(npycDataset, scaling=1, maxComponents=10, minQ2=0.05, withExclusions=False, **kwargs):
"""
Performs and... |
11542594 | from six import itervalues
from flask_marshmallow import Schema
class Parameters(Schema):
class Meta:
ordered = True
def __init__(self, **kwargs):
kwargs["strict"] = kwargs.get("strict", True)
super(Parameters, self).__init__(**kwargs)
for required_field_name in getattr(self... |
11542597 | import pytest
from .data_providers import valid_customers
@pytest.mark.parametrize("customer", valid_customers, ids=[repr(x) for x in valid_customers])
def test_can_register_customer(app, customer):
old_ids = app.get_customer_ids()
app.register_new_customer(customer)
new_ids = app.get_customer_ids()
... |
11542601 | import tensorflow as tf
def variable_checkpoint_matcher(conf, vars, model_file=None, ignore_varname_firstag=False):
"""
for every variable in vars takes its name and looks inside the
checkpoint to find variable that matches its name beginning from the end
:param vars:
:return:
"""
if model_file is None:... |
11542610 | import os.path
import textwrap
from typing import Set
desc_id = 0
def _next_desc_id():
global desc_id
desc_id += 1
return f"desc{desc_id}"
class DocWriter(object):
def __init__(self, base_path, name):
self.base_path = base_path
self.name = name
self.path = os.path.join(base... |
11542615 | import astroid
from tools.pylint import LogNokwargsChecker
from tools.pylint.log_checker import LOGNOKWARGS_SYMBOL
def test_simple_logger_with_kwargs(pylint_test_linter):
"""Test that we can detect the usage of kwargs in a normal logging call
But that we also allow it for RotkehlchenLogsAdapter
"""
c... |
11542644 | def rightTriangle(nRows):
for i in range(1,nRows+1):
print("*"*i)
def invertedTriangle(nRows):
nSpaces=0
nStars=2*nRows-1
for i in range(1,nRows+1):
print(' '*nSpaces+'*'*nStars)
nStars-=2
nSpaces+=1
def main():
choice=int(input("Enter 1 for right triangle ... |
11542654 | import FWCore.ParameterSet.Config as cms
particleFlowTmpPtrs = cms.EDProducer("PFCandidateFwdPtrProducer",
src = cms.InputTag('particleFlowTmp')
)
|
11542662 | from bs4 import BeautifulSoup
from terminaltables import SingleTable
import requests, re
from tkinter import *
def searchCopainsdavant(text, nom, city):
url = "http://copainsdavant.linternaute.com/s/?ty=1&prenom=%s&nom=%s&nomjf=&annee=&anneeDelta=&ville=%s"
name = nom
if " " in name:
nom = name.split(" ")[1]
pr... |
11542721 | import random
import pytest
from .models import db, User, UserType, Friendship, Relation, MYSQL_URL
pytestmark = pytest.mark.asyncio
async def test_create(engine):
nickname = "test_create_{}".format(random.random())
u = await User.create(
bind=engine, timeout=10, nickname=nickname, age=42, type=Use... |
11542777 | import pytest
import tarski.benchmarks.blocksworld
from tarski.fstrips.representation import is_quantifier_free
from tarski.syntax import *
from tests.common import tarskiworld
from tarski.syntax.transform.nnf import NNFTransformation
from tarski.syntax.transform.cnf import to_conjunctive_normal_form_clauses
from tar... |
11542811 | from datetime import datetime, date
from six import string_types
from .utils import valid_platform, platform_names, valid_operand_for_operator, valid_operand_list, \
valid_operand, valid_operator, valid_days, valid_bool, parse_date
from .constants import TAG_FILTER_OPERATOR_LTE, TAG_FILTER_OPERATOR_GTE, TAG_FILTE... |
11542814 | from typing import Optional
import operator
import traitlets
import ipywidgets
from ..types import Image, ImageCollection, Proxytype
from .layer import WorkflowsLayer
class LayerPicker(ipywidgets.HBox):
"""
Widget to pick a WorkflowsLayer from a map
In subclasses, set `_attr` to the trait name on Work... |
11542823 | import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.tests.distributions.conditional import ConditionalDistributionTest
from survae.distributions import ConditionalMeanNormal, ConditionalMeanStdNormal, ConditionalNormal
class ConditionalMeanNormalTest(ConditionalDistributionTest):
... |
11542843 | import csv
import loremipsum
import random
import re
from ..loadxl import *
class Anonymizer(object):
"""Change email addresses and names consistently
"""
# From Colander. Not exhaustive, will not match .museum etc.
email_re = re.compile(r'(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}')
random_words... |
11542850 | from functools import lru_cache
from pathlib import Path
import pytest
XML_ROOT = Path(__file__).parent / "tests" / "xml"
@pytest.fixture()
@lru_cache()
def saml_request_minimal() -> str:
with (XML_ROOT / "min/request/sample_saml_request_minimal.xml").open("r") as f:
return f.read()
@pytest.fixture()... |
11542909 | import os
from typing import NamedTuple
dirname, _ = os.path.split(os.path.dirname(__file__))
class ConveRTModelConfig(NamedTuple):
num_embed_hidden: int = 512
feed_forward1_hidden: int = 2048
feed_forward2_hidden: int = 1024
num_attention_project: int = 64
vocab_size: int = 25000
num_encoder... |
11542926 | from marltoolbox.algos.lola.train_cg_tune_class_API import LOLAPGCG
from marltoolbox.algos.lola.train_exact_tune_class_API import LOLAExact
from marltoolbox.algos.lola.train_pg_tune_class_API import LOLAPGMatrice
|
11542932 | from __future__ import unicode_literals
import os
from rbtools.api.errors import APIError
from rbtools.commands import Command, CommandError, Option
class Attach(Command):
"""Attach a file to a review request."""
name = 'attach'
author = 'The Review Board Project'
needs_api = True
args = '<re... |
11542943 | from dataclasses import dataclass, field
from OnePy.sys_module.models.base_log import TradeLogBase
@dataclass
class StockTradeLog(TradeLogBase):
buy: float = None
sell: float = None
size: float = None
def generate(self):
sell_order_type = self._get_order_type(self.sell)
buy_order_ty... |
11542987 | from typing import Union, Tuple, Optional
from genomics_data_index.storage.model.QueryFeatureHGVS import QueryFeatureHGVS
from genomics_data_index.storage.model.QueryFeatureMutationSPDI import QueryFeatureMutationSPDI
class NucleotideMutationTranslater:
@classmethod
def convert_deletion(cls, deletion: Union... |
11543013 | class Artista(object):
def __init__(self, **args):
self._id = args.get('id')
self._area = args.get('area')
self._tipoc = args.get('TipoC')
self._name= args.get('nombre')
self._sortname = args.get('nombreBus')
self._id2 = args.get('id2')
self._eScore = args.get... |
11543022 | import argparse
from trapperkeeper import models
from trapperkeeper import config
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create schema on configured database.")
parser.add_argument("-c", "--config", default="/etc/trapperkeeper.yaml",
help="Path to con... |
11543036 | from team29.analizer.abstract.expression import Expression, TYPE
from team29.analizer.abstract import expression
from team29.analizer.reports import Nodo
from datetime import datetime
from team29.analizer.statement.expressions.primitive import Primitive
class Current(Expression):
def __init__(self, val, optStr, r... |
11543057 | import math
import torch
import torch.nn as nn
from collections import OrderedDict
import ltr.models.lwl.label_encoder as seg_label_encoder
from ltr import model_constructor
import ltr.models.lwl.linear_filter as target_clf
import ltr.models.target_classifier.features as clf_features
import ltr.models.lwl.initi... |
11543075 | import cv2
import itertools
import math
import numpy as np
import tensorflow as tf
import time
from attacks.local_search_helper import LocalSearchHelper
class ParsimoniousAttack(object):
"""Parsimonious attack using local search algorithm"""
def __init__(self, model, args, **kwargs):
"""Initialize attack.
... |
11543104 | import random
import string
import smtplib
from django.db import models
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth.models import User
def generate_code():
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
class ResetCo... |
11543114 | import os.path
import random
import torchvision.transforms as transforms
import torch
from data.base_dataset import BaseDataset
from data.image_folder import make_dataset
from PIL import Image
import numpy as np
import scipy.io as sio
class nyuv2dataset(BaseDataset):
@staticmethod
def modify_commandline_options(pars... |
11543124 | import sys
import os
PATH = os.path.dirname(__file__)
sys.path.append(PATH)
thirdparties = ['numpy-groupies']
for name in thirdparties:
sys.path.append(os.path.join(PATH, '../../thirdparty/', name))
# Data Layer
from .Data import *
# Layers
from .FC import *
from .Conv import *
from .ConvT import *
from .BatchNo... |
11543131 | import unittest
from arangodb import six
from arangodb.orm.fields import UuidField
class UuidFieldTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_state(self):
uuid = UuidField()
self.assertEqual(uuid.text, None)
uuid.on_cr... |
11543142 | import os
''' Create a folder if it doesn't exist '''
def createDirectory(new_dir):
if not os.path.isdir(new_dir):
for p in xrange(2,len(new_dir.split("/"))+1):
tmp_string = "/".join(new_dir.split('/')[:p])
if not os.path.isdir(tmp_string):
try:
os.mkdir(tmp_string)
except:
print "error maki... |
11543154 | import time
import cv2
import numpy as np
from chainer import serializers, Variable
import chainer.functions as F
import argparse
from yolov2 import *
class AnimalPredictor:
def __init__(self):
# hyper parameters
weight_file = "./backup/yolov2_final_cpu.model"
self.n_classes = 10
se... |
11543164 | from django.apps import AppConfig
class SampleappoauthConfig(AppConfig):
name = 'SampleAppOAuth'
|
11543214 | import collections
import datetime
import itertools
import logging
import os
import sys
from typing import List, Optional
import pandas as pd
import requests
from crowdkit.aggregation import BradleyTerry
from crowdkit.aggregation import MajorityVote
from toloka.client import Pool, Project, structure
from toloka.client... |
11543215 | import logging
import typing
import random
import heapq
import time
import asyncio
import threading
from .actor import Actor
from .message import ActorMessage
from .state import ActorState, OUTBOX, EXPORT, ERROR, ERROR_NOTRY
from .storage import ActorLocalStorage
from .registery import ActorRegistery
from .builtin_act... |
11543229 | import requests
from bs4 import BeautifulSoup
from accounts.models import Major
def contains_filters(listed_filters, desired_filters=set(), excluded_filters=set()):
# ensure no excluded filters appear
for curr_filter in excluded_filters:
if curr_filter in listed_filters:
return False
... |
11543292 | from rest_framework.authentication import SessionAuthentication
from rest_framework import permissions
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
class UserAccessPermission(permissions.BasePe... |
11543381 | import numpy as np
from astropy.coordinates import angles
k_Sun = 132749351440.0
def rv2coe(k, a, ecc, inc, raan, argp, nu):
"""Convierte elementos keplerianos a vectores r y v.
Parámetros
==========
k : float
Parámetro gravitacional (km^3 / s^2)
a : float
Semieje mayor (km)
... |
11543439 | from tornado.web import url
from .handlers import *
urlpattern = [
url("/monitor/", MonitorHandler),
]
|
11543595 | class Pipeline(object):
"""Common pipeline class fo all pipeline tasks."""
def __init__(self, source=None):
self.source = source
def __iter__(self):
return self.generator()
def generator(self):
"""Yields the pipeline data."""
while self.has_next():
try:
... |
11543604 | import logging
import os
from hydra.experimental.callback import Callback
from mpi4py import MPI
from detectron2.utils import comm as d2_comm
from detectron2.utils.logger import setup_logger
from tridet.utils.s3 import aws_credential_is_available, maybe_download_ckpt_from_url, sync_output_dir_s3
from tridet.utils.se... |
11543607 | from datetime import datetime
from typing import Dict, List, Any
from collections.abc import Iterable
import redis
from flask import (
Blueprint,
Response,
current_app,
jsonify,
redirect,
render_template,
request,
url_for,
get_template_attribute,
)
from werkzeug.utils import cache... |
11543622 | import itertools
import json
from pathlib import Path
from urllib.parse import urljoin
from flexget.utils.soup import get_soup
from loguru import logger
from ..schema.site_base import SiteBase, SignState, NetworkState, Work
from ..utils.net_utils import NetUtils
class NexusPHP(SiteBase):
def get_message(self, ... |
11543646 | class ModelFactory():
def __init__(self):
pass
@staticmethod
def get_model(model_type, dataset, in_channels=6, num_actions=6, width=300):
if dataset == "omniglot":
nm_channels = 112
channels = 256
size_of_representation = 2304
size_of_interpre... |
11543656 | from io import StringIO
from yglu.main import process
from .utils import outdent
def test_process_ok():
input = """
a: 1
b: 2
---
c: 3
"""
output = StringIO()
process(outdent(input), output)
assert output.getvalue() == "a: 1\nb: 2\n---\nc: 3\n"
def test_process_... |
11543663 | from appconf import AppConf
class CustomHolder(object):
pass
custom_holder = CustomHolder()
class TestConf(AppConf):
SIMPLE_VALUE = True
CONFIGURED_VALUE = 'wrong'
def configure_configured_value(self, value):
return 'correct'
def configure(self):
self.configured_data['CONFIG... |
11543677 | import os
import re
import sys
import json
import shutil
import logging
import zipfile
import requests
from datetime import datetime
import pandas as pd
from onesaitplatform.iotbroker import DigitalClient
from onesaitplatform.files import FileManager
import urllib3
urllib3.disable_warnings()
DATETIME_PATTERN = "%Y-... |
11543691 | import nltk
def english_segmentation(sentence):
""""""
# Converted to lowercase letters
sentence = sentence.lower()
# Separate words and token
sentence = nltk.tokenize.word_tokenize(sentence)
# delete the token
english_punctuations = [",", ".", ":", ";", "?", "(", ")", "[", "]", '\'', '"',... |
11543764 | from pathlib import Path
import cv2
import numpy as np
import torch
import torchvision
from PIL import Image
from torch.utils.data import Dataset
from scipy.spatial.transform import Rotation
from utils import map_fn
class TUMMonoVOMultiDataset(Dataset):
def __init__(self, dataset_dirs, **kwargs):
if is... |
11543765 | from django import template
from user.models import User_Info
from topic.models import Create_Topic
register=template.Library()
@register.simple_tag
def each_people_num(username):
info=User_Info.objects.get(username=username)
all_theme=info.create_topic_set.all()
all_theme1=len(all_theme)
ret... |
11543780 | from enum import Enum, unique
from app.domain.common.models.value_object import value_object
@unique
class LevelName(Enum):
BLOCKED = "BLOCKED"
USER = "USER"
ADMINISTRATOR = "ADMINISTRATOR"
@value_object
class AccessLevel:
id: int
name: LevelName
|
11543788 | import sys, random
fin = open(sys.argv[1], 'r')
data = fin.readlines()
fin.close()
random.shuffle(data)
sys.stdout.writelines(data)
|
11543791 | from petlib.ec import EcGroup
from genzkp import ZKProof, ZKEnv, ConstGen, Sec
def test_blog_post():
# Define an EC group
G = EcGroup(713)
print (EcGroup.list_curves()[713])
order = G.order()
## Define the Zero-Knowledge proof statement
zk = ZKProof(G)
g, h = zk.get(ConstGen, ["g", "h"])
... |
11543855 | import csv
import os
import re
import requests
from pattern import web
def get_dom(url):
html = requests.get(url).text
dom = web.Element(html)
return dom
def get_taxons_from_crispr_db():
taxon_ids = []
if os.path.exists('taxon_ids.csv'):
with open('taxon_ids.csv', 'r') as csvfile:
... |
11543862 | import sys
from abc import abstractmethod
import numpy as np
from sklearn.metrics import (accuracy_score, f1_score, log_loss, mean_absolute_error, mean_absolute_percentage_error,
mean_squared_error, mean_squared_log_error, precision_score, r2_score, roc_auc_score,
... |
11543908 | import inspect
from django.contrib.contenttypes.models import ContentType
from django.apps import apps
from django.core import serializers
from django.core.management import BaseCommand
from field_history.models import FieldHistory
from field_history.tracker import FieldHistoryTracker, get_serializer_name
class Com... |
11543909 | import {{ cookiecutter.app_module }}
import pytest
@pytest.fixture
def client():
"""Flask test client"""
{{ cookiecutter.app_module }}.app.testing = True
return {{ cookiecutter.app_module }}.app.test_client()
def test_version():
"""Package should have a version defined"""
version = getattr({{ co... |
11543934 | import logging
from exchange.errors import *
from exchange.ticker import Ticker
from exchange.orderbook import *
from exchange.currency_pair import CurrencyPair
from exchange.exchange_base import ExchangeBase
from exchange.coinbene.coinbene import Coinbene
class ExchangeCoinbene(ExchangeBase):
"""
Coinbene
... |
11543949 | import urllib.request
import urllib
def extract(html):
content = ""
for l in html.splitlines():
if 'class="verse"' in l:
for c in l:
if c==' ' or (c >= u"\U00001200" and c <= u"\U0000135A"):
content += c
content = ' '.join(content.split())
return ... |
11543962 | import re
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.query import QuerySet
from django.urls import reverse
from rest_framework import serializers
from reversion.models import Version
from apis_core.apis_labels.serializers import LabelSerializerLeg... |
11543992 | import cv2
# Get the number of cameras available
def count_cameras():
max_tested = 100
for i in range(max_tested):
temp_camera = cv2.VideoCapture(i)
if temp_camera.isOpened():
temp_camera.release()
continue
return i
print(count_cameras())
|
11543997 | import numpy as np
import matplotlib.pyplot as plt
import csv
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
def npRelu(X):
return np.maximum(0,X)
def npSigmoid(X):
return 1 / (1 + np.exp(-1 * X))
def parainit(n_X, m):
W = np.random.randn(1, n_X)*0.01
b = 0.0
return W, b
... |
11544093 | import torch
import torch.nn as nn
import torch.nn.functional as F
def general_weight_initialization(module: nn.Module):
if isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d)):
if module.weight is not None:
nn.init.uniform_(module.weight)
if module.bias is not None:
nn.ini... |
11544100 | import tensorflow as tf
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from IPython.terminal.debugger import set_trace as keyboard
def build_train_op(self):
with tf.device('/cpu:0'):
min_queue_examples =20
num_preprocess_threads = 16
imagefile_batch,image_batch,gra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.