id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
433228 | from django.urls import include, path
from likes.api.views import (
LikeListAPIView,
LikedCountAPIView,
LikeToggleView,
LikedIDsAPIView
)
app_name = 'likes-api'
urlpatterns = [
path('likes/', include([
path('count/', LikedCountAPIView.as_view(), name='count'),
path('is/', LikedIDsA... |
433240 | import numpy as np
class GreedyKCenter(object):
def fit(self, points, k):
centers = []
centers_index = []
# Initialize distances
distances = [np.inf for u in points]
# Initialize cluster labels
labels = [np.inf for u in points]
for cluster in range(k):
... |
433271 | import numpy as np
import pandas as pd
from pandas.io.parsers import read_csv
from BOAmodel import *
from collections import defaultdict
""" parameters """
# The following parameters are recommended to change depending on the size and complexity of the data
N = 2000 # number of rules to be used in SA_patternbase... |
433286 | from doitpy.pyflakes import Pyflakes
from doitpy.coverage import Coverage, PythonPackage
DOIT_CONFIG = {
'default_tasks': ['pyflakes'],
'verbosity': 2,
}
def task_pyflakes():
flaker = Pyflakes()
yield flaker.tasks('**/*.py')
def task_coverage():
"""show coverage for all modules including tests... |
433295 | from .kor2vec import Kor2Vec
from .context_kor2vec import ContextKor2Vec
from .model.vocab import *
# from .pretrained import SejongVector
import warnings
warnings.filterwarnings("ignore")
|
433358 | class Base:
"""The base object for all top-level client objects.
Parameters
----------
domain : one of rubicon.domain.*
The top-level object's domain instance.
config : rubicon.client.Config, optional
The config, which injects the repository to use.
"""
def __init__(self, d... |
433366 | import torch
import numpy as np
from torch.autograd import Variable
class loss_block:
def __init__(self):
super(loss_block, self).__init__()
def loss(self,input_vals,lables):
return torch.mean(input_vals) |
433395 | import pytest
import numpy as np
from floodlight import XY
@pytest.fixture()
def example_sequence():
seq = np.array(
[np.NaN, np.NaN, -5.07, -2.7, np.NaN, np.NaN, 1.53, 27.13, None, 30.06]
)
return seq
@pytest.fixture()
def example_sequence_empty():
seq = np.empty(())
return seq
@pytes... |
433402 | import os
import tensorflow as tf
num_threads = os.environ.get('OMP_NUM_THREADS')
def get_session(gpu_fraction=0.75):
"""Assume that you have 6GB of GPU memory and want to allocate ~2GB"""
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)
if num_threads:
print("with nth... |
433419 | from helper_helper import *
from helper_helper import _time
@unittest.skipUnless( os.environ.get('TEST_API','true').lower()=='true', 'skipping api' )
class ApiHelper(Chai):
def setUp(self):
super(ApiHelper,self).setUp()
self.series = Timeseries(self.client, type='series', prefix='kairos',
read_func=i... |
433449 | from flask import request
from test import client
from app.utils import SERIES, SERIES_URL
from app.utils import get_by_id, finder
def test_home_page(client):
""" Testcase for home url """
response = client.get("/api")
assert SERIES_URL == response.get_json()
assert SERIES_URL == response.get_json()
... |
433501 | import xml.etree.ElementTree as ET
import py7zr
import json
import os
import glob
import re
import argparse
from pathlib import Path
from bs4 import BeautifulSoup
from multiprocessing import Pool, cpu_count
from tqdm import tqdm
XML_SUFFIX = '<?xml version="1.0" encoding="utf-8"?>\n<posts>\n'
XML_PREFIX = '\n</posts>'... |
433512 | class Kite(object):
def __init__(self):
self.code = "kite"
def foo(self):
print("bar!")
|
433615 | from models.multiple_solution.swarm_based.EPO import BaseEPO
from utils.FunctionUtil import *
## Setting parameters
root_paras = {
"problem_size": 100,
"domain_range": [-100, 100],
"print_train": True,
"objective_func": C30
}
epo_paras = {
"epoch": 500,
"pop_size": 100
}
## Run model
md = Base... |
433652 | import time
import boto3
import os
import sys
from data_mesh_util.lib.ApiAutomator import ApiAutomator
sys.path.append(os.path.join(os.path.dirname(__file__), "resource"))
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
from data_mesh_util.lib.SubscriberTracker import *
class DataMeshProducer:
... |
433662 | from enum import Enum
class PublicMethods(Enum):
"""
Публичные методы, которые не требуют шифрования при запросе
"""
KEY_INFO = 'key_info'
I_CLIENT_PUB_KEY = 'iclient_pub_key'
class AsymEncryptionHandShake(Enum):
ASYM_HAND_SHAKE = 'asym_hand_shake'
|
433694 | from multiprocessing import Pool
import numpy as np
from mmcv.utils import print_log
from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps
from mmdet.core.evaluation.mean_ap import get_cls_results
def calc_tpfpfn(det_bboxes, gt_bboxes, iou_thr=0.5):
"""Check if detected bboxes are true positive or false... |
433719 | class Database:
database = None
def __init__(self):
self.content = "User Data"
@staticmethod
def getInstance():
if not Database.database:
print("New database instance created")
Database.database = Database()
return Database.database
def describe(self):
print("The databa... |
433811 | from datetime import datetime
import pytz
from django.test.testcases import TestCase
from robber.expect import expect
from freezegun import freeze_time
from analytics import constants
from analytics.factories import AttachmentTrackingFactory
from data.cache_managers import allegation_cache_manager
from data.constant... |
433821 | from TeamPromoConnectionFactory import TeamPromoConnectionFactory
from TeamAssessmentConnectionFactory import TeamAssessmentConnectionFactory
# Testing factory for Promo Team
currentFactory = TeamPromoConnectionFactory()
RPCConnection = currentFactory.createRPCConnection()
HTTPConnection = currentFactory.createHTTPCon... |
433859 | from typing import Tuple
import gdsfactory as gf
from gdsfactory.geometry import check_width
def test_wmin_failing(layer: Tuple[int, int] = (1, 0)) -> None:
w = 50
min_width = 50 + 10 # component edges are smaller than min_width
c = gf.components.rectangle(size=(w, w), layer=layer)
gdspath = c.write... |
433860 | from django.conf.urls import patterns, url
from contact_updater.views import prepopulate_agency, form_index
urlpatterns = patterns(
'',
url(r'^$', form_index, name='contact_updater_index'),
url(r'^(?P<slug>[-\w]+)/?$',
prepopulate_agency,
name='contact_updater_form'),
)
|
433889 | import torch
from torch.testing._internal.common_utils import TestCase
from torch.testing._internal.common_utils import dtype2prec_DONTUSE
from depthwise_conv3d import DepthwiseConv3d
class TestConv(TestCase):
def test_Conv3d_depthwise_naive_groups_cuda(self, dtype=torch.float):
for depth_multip... |
433942 | import pickle
import json
def v2d(names: list):
return {v: eval(v) for v in names}
def save_pickle(file_name: str, object):
with open(file_name, 'wb') as f:
pickle.dump(object, f)
def load_pickle(file_name: str):
with open(file_name, 'rb') as f:
return pickle.load(f)
def load_json(fi... |
433950 | def extractJunktranslatesWordpressCom(item):
'''
Parser for 'junktranslates.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('intl', 'It’s Not Too Late to Meet Again After Reb... |
433952 | import os
from typing import List, Tuple, Optional
import json
import pathlib
import tarfile
from contextlib import closing
from requests import Response, get
from autocorrect import Speller
from sentry_sdk import capture_exception
from rozental_as_a_service.common_types import TypoInfo
from rozental_as_a_service.con... |
433991 | from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
import os
import time
import shlex
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import channel
from amuse... |
433996 | import torch.nn as nn
from rpn.utils.eval_utils import binary_accuracy
from rpn.utils.config import dict_to_namedtuple
def compute_bce_loss(logits, labels, weight=None):
loss_fn = nn.BCEWithLogitsLoss(weight=weight, reduction='mean')
loss = loss_fn(logits, labels)
return loss
def log_binary_accuracy_fpf... |
434006 | from notion.store import RecordStore
def no_save_cache(self, attribute):
return()
def no_load_cache(self, attributes=("_values", "_role", "_collection_row_ids")):
return()
# Prevents the cache from being written and loaded
# Provides a massive speed boost for short lived commands
RecordStore._save_cache =... |
434013 | from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode
from armulator.armv6.bits_ops import unsigned_sat_q, zero_extend
class Usat16(AbstractOpcode):
def __init__(self, saturate_to, d, n):
super(Usat16, self).__init__()
self.saturate_to = saturate_to
self.d = d
self.n =... |
434075 | def test_passed():
assert True
def test_read_params(config, param):
assert config.get(param) == 2
def test_do_nothing():
pass
|
434098 | import argparse
import torch
from torch import nn
import numpy as np
from tqdm import tqdm
import pdb
import os
import csv
from glob import glob
import math
from torchvision import transforms
from torch.nn import functional as F
from matplotlib import pyplot as plt
import sys
sys.path.append('../retrieval_model')
from... |
434115 | from abc import ABCMeta, abstractmethod
import json
from typing import Any, IO, Optional, Sequence, cast
from pytest_wdl.core import DataDirs, DataManager, DataResolver
from pytest_wdl.utils import ensure_path
from py.path import local
import pytest
from _pytest.fixtures import FixtureRequest
try:
from ruamel im... |
434174 | import datetime
from sqlalchemy import Enum
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import Boolean
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalc... |
434186 | import torch
from moment_detr.model import build_transformer, build_position_encoding, MomentDETR
def build_inference_model(ckpt_path, **kwargs):
ckpt = torch.load(ckpt_path, map_location="cpu")
args = ckpt["opt"]
if len(kwargs) > 0: # used to overwrite default args
args.update(kwargs)
transf... |
434201 | from collections.abc import Mapping, Iterable
from typing import Iterable as IterableType
from jsons._compatibility_impl import get_naked_class
from jsons.deserializers.default_list import default_list_deserializer
def default_iterable_deserializer(
obj: list,
cls: type,
**kwargs) -> Iterable... |
434247 | import pandas as pd
import os
from .. import constants as c
def get_short_imagename(imagename):
"""Return image-specific suffix of imagename.
This excludes a possible experiment-specific prefix,
such as 0001_... for trial #1.
"""
splits = imagename.split("_")
if len(splits) > 1:
nam... |
434289 | import pandas as pd
import os
from helpers import *
def main():
sim_threshold = 100
prefix = '/home/cragkhit/data/cloverflow/github_max_to_10/'
dir = '../results/results_for_thesis/'
clones = pd.read_csv(
'../results/results_for_thesis/github_license_qr_17-08-18_16-46-780_for_github_query.csv'... |
434322 | import argparse
import os, sys
import numpy as np
from scipy.ndimage import rotate
from tqdm import tqdm
def rotate_gt(args, categories_dict, scannet_shape_ids, angles):
for category in categories_dict:
cat_path = categories_dict[category] + '_geo'
cat_save_path = os.path.join(args.data_dir, cat... |
434403 | import io
import re
from itertools import chain
import fbuild
import fbuild.builders
import fbuild.builders.c
import fbuild.builders.platform
import fbuild.db
import fbuild.record
from fbuild.path import Path
from fbuild.temp import tempfile
# --------------------------------------------------------------------------... |
434411 | def do_stuff():
print('stuff')
def do_other_stuff():
print('other stuff')
def branching(some_condition):
if some_condition is True:
do_stuff()
do_other_stuff()
|
434441 | from .Euler_Scheme import EulerScheme
import taichi as ti
import numpy as np
# ref IVOCK 2014, Dr <NAME> .etal
# need help on stretch and stream function(velocity from vorticity)
@ti.data_oriented
class IVOCK_EulerScheme(EulerScheme):
def __init__(self, cfg):
super().__init__(cfg)
def advect(self, d... |
434460 | import numpy as np
import matplotlib.pyplot as plt
logistic = False
samples = [[0.47,1],[0.24,1],[0.75,1],[0.00,1],[-0.80,1],[-0.59,1],[1.09,1],[1.34,1],
[1.01,1],[-1.02,1],[0.50,1],[0.64,1],[-1.15,1],[-1.68,1],[-2.21,1],[-0.52,1],
[3.93,1],[4.21,1],[5.18,1],[4.20,1],[4.57,1],[2.63,1],[4.52,1],[3... |
434500 | def main():
info('Waiting for minibone access')
wait('JanMiniboneFlag', 0)
info('Minibone released')
wait('MinibonePumpTimeFlag', 0)
acquire('FelixMiniboneFlag', clear=True)
info('minibone acquired')
|
434539 | from .mod import mod
from ..db import get_watches_bi_user_id as _get_watches_bi_user_id
from ..ut.bunch import Bunch
def get_watches_bi_user_id(conn, user_id, offset=None, limit=None):
return [transform(w) for w in _get_watches_bi_user_id(
conn,
user_id,
offset=offset,
limit=limit
... |
434657 | from math import *
from NodeGeneratorBase import *
from Spheral import Vector3d, Tensor3d, SymTensor3d, Plane3d, rotationMatrix
from SpheralTestUtilities import *
import mpi
procID = mpi.rank
nProcs = mpi.procs
#-------------------------------------------------------------------------------
# The sign function
#----... |
434665 | import enum as _enum
import string as _string
from typing import Any
from . import auth as _auth
from . import helper as _helper
from . import url as _url
import requests
class Method(_enum.Enum):
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
def request(
request_method: Method,
uri: str... |
434695 | import argparse
def parse(args):
parser = argparse.ArgumentParser()
parser.add_argument(
"--debug", action="store_true", default=False, help="Enable debug logging"
)
parser.add_argument("--xml")
parser.add_argument(
"--module", action="store_true", default=False, help="Trace a m... |
434746 | from .svg_parser_utils import *
import OpenGL.GL as gl
import math
EPSILON = 0.001
class vec2(object):
def __init__(self, *args):
if isinstance(args[0], vec2):
self.x = args[0].x
self.y = args[0].y
elif isinstance(args[0], list):
self.x, self.y = args[0]
... |
434764 | import collections
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
count_map = collections.Counter(s)
stack = []
for c in s:
if len(stack) == 0:
stack.append(c)
count_ma... |
434788 | import elbus_async
import asyncio
async def main():
name = 'test.client.python.async_sender'
bus = elbus_async.client.Client('/tmp/elbus.sock', name)
await bus.connect()
# send a regular message
result = await bus.send('test.client.python.async',
elbus_async.client.Fram... |
434798 | from __future__ import division, print_function
import argparse
import pickle as pkl
import h5py
import glob
import os
from tqdm import tqdm
def main(args):
print(args)
compression_flags = dict(compression='gzip', compression_opts=9)
filenames = glob.glob(os.path.join(args.features_folder, '*.pkl'))
... |
434883 | from About import *
from Args import *
from DemoSet import *
from DemoSplash import *
from geoparse import *
from MainDisplay import *
from MainMenu import *
|
434938 | from getpass import getpass
import os
import click
from flask.cli import FlaskGroup
import lxml.etree
from passlib.apache import HtpasswdFile
from tqdm import tqdm
from .flask import app
from . import models, tasks
from . import views, twilio # noqa: F401
@click.group(cls=FlaskGroup, create_app=lambda *args, **kwa... |
434952 | from __future__ import print_function
import argparse
import sys
import traceback
from botocore.exceptions import ClientError
from ridi.secret_keeper.connect import tell
def run(arguments):
description = """
Retrieve and print secrets from `secret-keeper`.
You need to configure AWS credentials by enviro... |
434993 | def dedupe_and_sort(sequence, first=None, last=None):
"""
De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will... |
435010 | from starflyer import Handler, redirect, asjson
from camper import BaseForm, db, BaseHandler
from camper import logged_in, is_admin, ensure_barcamp
from .base import BarcampBaseHandler
import werkzeug.exceptions
ALLOWED_CHECKS = [
'has_event',
'has_sponsor',
'has_hashtag',
'has_twitter',
'has_faceb... |
435076 | from boto.swf.exceptions import SWFResponseError
from botocore.exceptions import ClientError
from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import
from unittest import SkipTest
import pytest
from moto import mock_swf, mock_swf_deprecated
from moto import settings
from moto.swf import sw... |
435083 | import sys
sys.path.append("./")
import examples as ex
import pytest
import pyinspect as pi
def test_examples():
pi.search(ex) # runs all of them
|
435098 | def decimal_to_binary(n):
if n > 1: decimal_to_binary(n//2)
print(n % 2, end = '')
try: decimal_to_binary(int(input("Enter an Integer to Covert into Binary: ")))
except ValueError: print("Input is not an integer.")
print()
|
435119 | from __future__ import print_function
from coverage import coverage
cov = coverage(source=('doubles',))
cov.start()
pytest_plugins = ['doubles.pytest_plugin']
def pytest_sessionfinish(session, exitstatus):
cov.stop()
cov.save()
def pytest_terminal_summary(terminalreporter):
print("\nCoverage report:\... |
435133 | from database import db
from flask import Flask
from yelp_beans.logic.config import get_config
def create_app():
app = Flask(__name__, template_folder='yelp_beans/templates')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = get_config().get('DATABASE_URL_PROD', ... |
435136 | from modules import DNSListener
from modules import AgentControllerCLI
import threading
banner = """
____ _ _______ ____ _ __
/ __ \/ | / / ___/ / __ \___ __________(_)____/ /_
/ / / / |/ /\__ \______/ /_/ / _ \/ ___/ ___/ / ___/ __/
/ /_/ / /| /___/ /_____/ ____/ __... |
435154 | from abc import abstractmethod
import math
import generator
import magma
import mantle
from from_magma import FromMagma
from configurable import Configurable, ConfigurationType
from const import Const
class FeatureGenerator(Configurable):
def __init__(self):
super().__init__()
class CoreGenerator(Featur... |
435156 | from networkx import DiGraph, disjoint_union # type: ignore
from veniq.ast_framework import AST, ASTNodeType
from typing import Tuple
NODE_TYPES = [
ASTNodeType.ASSIGNMENT,
ASTNodeType.RETURN_STATEMENT
]
def build_cfg(tree: AST) -> DiGraph:
'''Create Control Flow Graph'''
g = DiGraph()
g.add_no... |
435163 | import _kratos
import sqlite3
import tempfile
import os
import json
from kratos import Generator, Event, always_comb, always_ff, posedge, Transaction, verilog
def test_event_extraction():
mod = Generator("mod")
event = Event("test1/event1")
event_ff = Event("test1/event2")
t = Transaction("test")
... |
435180 | from ckan_cloud_operator.providers import manager as providers_manager
from .constants import PROVIDER_SUBMODULE
from .adminer.constants import PROVIDER_ID as adminer_provider_id
def initialize():
get_provider(default=adminer_provider_id).initialize()
def start():
"""Start a web-UI for db management"""
... |
435181 | from opytimizer.optimizers.population import OSA
# One should declare a hyperparameters object based
# on the desired algorithm that will be used
params = {
'beta': 1.9
}
# Creates an OSA optimizer
o = OSA(params=params)
|
435204 | import os
from spira.technologies.mit.process import RDD
import spira.all as spira
import spira.yevon.io.input_gdsii as io
from copy import copy, deepcopy
def wrap_references(cell, c2dmap, devices):
""" """
for e in cell.elements.sref:
if e.reference in c2dmap.keys():
e.reference = c2dmap... |
435215 | from distutils.core import setup
setup(
name='influx-nagios-plugin',
version="1.1.0",
packages=['src'],
install_requires=['influxdb', 'NagAconda'],
license='MIT',
url="https://github.com/shaharke/nagios-influx-plugin.git",
description='Nagios plugin for querying stats from InfluxDB',
a... |
435264 | import math
import pytest
from skspatial._functions import _allclose
from skspatial.objects import Line
from skspatial.objects import Plane
from skspatial.objects import Points
@pytest.mark.parametrize(
("array_point", "array_a", "array_b", "plane_expected"),
[
([0, 0], [1, 0], [0, 1], Plane([0, 0, ... |
435299 | import pytest
from impl import type_of_triangle
@pytest.mark.parametrize("x", range(1, 10))
def test_equilateral(x):
ret = type_of_triangle(x, x, x)
assert ret == "equilateral"
@pytest.mark.parametrize("x", range(1, 10))
@pytest.mark.parametrize("y", range(1, 10))
def test_isoceles(x, y):
if y >= x + x or... |
435311 | from ...utils import needs_py310
@needs_py310
def test_app():
from docs_src.app_testing.app_b_py310 import test_main
test_main.test_create_existing_item()
test_main.test_create_item()
test_main.test_create_item_bad_token()
test_main.test_read_inexistent_item()
test_main.test_read_item()
t... |
435334 | from __future__ import print_function, division
from collections import OrderedDict
from abc import ABCMeta
from six import text_type
from six import binary_type
from torch import nn
from torch.nn import init
CONTAINER_NAMES = (
'module.',
'segnet.',
'resnet.',
'encoder.',
'decoder.',
'clas... |
435402 | import sys, cv2, time, os
from UI import Ui_TabWidget
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog,QTabWidget
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QLabel,QWidget, QProgressBar
from py_util impor... |
435405 | def test_augassign():
r: i32
s: i32
r = 0
r += 4
s = 5
r *= s
r -= 2
s = 10
r /= s
a: str
a = ""
a += "test"
|
435533 | import typing
import pytest
from nonebug.app import App
@pytest.mark.asyncio
@pytest.mark.render
async def test_render(app: App):
from nonebot_bison.plugin_config import plugin_config
from nonebot_bison.utils import parse_text
plugin_config.bison_use_pic = True
res = await parse_text(
"""a\... |
435694 | import os
import sys
from argparse import ArgumentParser
from windowsprefetch import Prefetch
# Note: This wrapper script is a work in progress, and needs to be refined.
# todo: robust error handling and notifications, built into result output.
# todo: error-handling based on file content, not just file extension
d... |
435698 | import os
import sys
import time
import signal
import click
import json
@click.group()
def cli():
pass
@cli.command()
@click.option('-m', type=str)
def stdio(m):
print(m)
@cli.command()
@click.option('-m', type=str)
@click.option('-p', default='/mnt/girder_worker/data/output_pipe', type=click.File('w'))
d... |
435702 | import sys
sys.path = ["."] + sys.path
from petlib.ec import EcGroup
from petlib.bn import Bn
from hashlib import sha256
import math
## ######################################################
## An implementation of the ring signature scheme in
##
## <NAME> and <NAME>. "One-out-of-Many Proofs:
## Or How to Le... |
435712 | from ..core import ProteinLigandDatasetProvider
class KinomeScanDatasetProvider(ProteinLigandDatasetProvider):
pass
|
435734 | def parse(a):
a = a.split("\n")
a = [x+", " for x in a]
a = [''.join(a[i:i+6])+"\n" for i in range(0, len(a), 6)]
print(''.join(a))
|
435763 | from fastapi import Depends
from sqlalchemy.orm import Session
from utils.logger import Logger
from utils.db_connection import get_db_session
from schema.sample_object import SampleObject as SampleObjectSchema
from model.sample_object import SampleObject as SampleObjectModel
logger = Logger.get_logger(__name__)
clas... |
435772 | import sys
import random
import copy
#reload(sys)
#sys.setdefaultencoding="utf-8"
if (len(sys.argv)<3):
print("no enough parameter")
exit()
hownet_filename = sys.argv[1]
embedding_filename = sys.argv[2]
answer_filename = hownet_filename+"_answer"
test_filename = hownet_filename+"_test"
with open(hownet_filename... |
435871 | import collections
class netlistspec(collections.namedtuple(
"netlistspec", "vertices, load_function, before_simulation_function, "
"after_simulation_function, constraints")):
"""Specification of how an operator should be added to a netlist."""
def __new__(cls, vertices, load_fu... |
435873 | import torch
import torch.nn.functional as F
from ..base_loss import BaseLoss
class CrossEntropyLoss(BaseLoss):
"""
paper: `Momentum Contrast for Unsupervised Visual Representation Learning <http://openaccess.thecvf.com/content_CVPR_2020/html/He_Momentum_Contrast_for_Unsupervised_Visual_Representation_Learnin... |
435891 | def convert_bytes(byte):
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB'
'YiB', 'BiB', 'NiB', 'DiB', 'CiB']
for x in units:
if divmod(byte, 1024)[0] == 0:
break
else:
byte /= 1024
return ('%.2lf%s' % (byte, x))
|
435901 | import django
import logging
# from nltk import word_tokenize
import os
# import re
from slacker import Slacker
from sutime import SUTime
import tweepy
from tweepy.api import API
from slack_msg import send_slack_message
# need to point Django at the right settings to access pieces of app
os.environ["DJANGO_SETTINGS_MO... |
435907 | from terra_sdk.core.coins import Coins
from ._base import BaseAsyncAPI, sync_bind
__all__ = ["AsyncSupplyAPI", "SupplyAPI"]
class AsyncSupplyAPI(BaseAsyncAPI):
async def total(self) -> Coins:
"""Fetches the current total supply of all tokens.
Returns:
Coins: total supply
"""... |
435916 | import asyncio
import time
import asynctnt
import logging
logging.basicConfig(level=logging.DEBUG)
async def run():
conn = asynctnt.Connection(host='127.0.0.1', port=3305)
begin = time.time()
n = 1000
for i in range(n):
await conn.connect()
await conn.disconnect()
dt = time.time... |
435936 | import pytest
from ocs_ci.framework.pytest_customization.marks import tier1
@tier1
@pytest.mark.last
class TestFailurePropagator:
"""
Test class for failure propagator test case. The test intention is to run last and propagate
teardown failures caught during the test execution, so regular test cases won'... |
435938 | import os
import ssl
import unittest
from mock import MagicMock, patch, call
from kafka.tools.configuration import ClientConfiguration, eval_boolean, check_file_access
from kafka.tools.exceptions import ConfigurationError
class ConfigurationTests(unittest.TestCase):
def test_eval_boolean(self):
assert ev... |
435947 | import fields
import debug
import csv
import os
import sys
import datetime
def writer(vulns, **params):
csvfile = params['fobj']
debug.write('.')
for vuln in vulns:
csvfile.writerow([vuln['name'], vuln['count']])
def gen_csv(sc, filename):
'''csv SecurityCenterObj, EmailAddress
'''
... |
435948 | from torch import nn
import torch.nn.init as init
import numpy as np
def gaussian_weights_init(m):
classname = m.__class__.__name__
# print(classname)
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
def xavier_weights_init(m):
classname = m.__class__.__name__
# print(cl... |
435958 | from django.conf.urls import url
import twofa.views
app_name = "twofa"
urlpatterns = [
url(r"^verify/$", twofa.views.verify, name="verify"),
url(r"^verify/(?P<device_id>[0-9]+)/$", twofa.views.verify, name="verify"),
url(r"^setup/totp/$", twofa.views.setup_totp, name="setup-totp"),
url(r"^setup/backu... |
435994 | from typing import Callable, Tuple
import flax.linen as nn
import jax.numpy as jnp
from .weightnorm import constant
class PosDense(nn.Module):
"""Dense-layer with positive weights
"""
channels: int
use_bias: bool = True
kernel_init: Callable = nn.initializers.lecun_normal()
bias_init: Callab... |
436014 | from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import password_validators_help_texts
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from bananas.admin.api.schemas import schema_serializer_method
class UserSerializer(serialize... |
436035 | import ray
from tqdm import tqdm
class Pool:
def __init__(self, actors):
"""
actors: list of ray actor handles
"""
self.actors = actors
assert len(self.actors) > 0
def map(self, exec_fn, iterable,
callback_fn=None,
desc=None,
pbar_up... |
436041 | import pytest
from fastapi import Depends
from fastapi_jsonrpc import get_jsonrpc_request_id
@pytest.fixture
def probe(ep):
@ep.method()
def probe(
jsonrpc_request_id: int = Depends(get_jsonrpc_request_id),
) -> int:
return jsonrpc_request_id
return ep
def test_basic(probe, json_req... |
436049 | import torch
import text2text as t2t
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
class Answerer(t2t.Transformer):
pretrained_answerer = "valhalla/longformer-base-4096-finetuned-squadv1"
def __init__(self, **kwargs):
pretrained_answerer = kwargs.get('pretrained_answerer')
if not ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.