id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9963883 | from datetime import date, datetime, timezone
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from loguru import logger
from pydantic import ConstrainedStr, HttpUrl, NonNegativeInt, validator
from app.schemas.addresses import AddressCreateRequest
from app.schemas.base import BaseModel
from a... |
9963922 | from __future__ import print_function
from distutils.util import strtobool
from .basecommand import BaseCommand
class LastPassUsers(BaseCommand): # pylint: disable=too-few-public-methods
"""
Get users in LastPass
Usage:
lastpassusers [options]
-n --dry-run Display API reques... |
9963941 | import os
import rioxarray
import xarray as xr
from scipy.stats import binom
from carbonplan_forest_risks import load
from carbonplan_forest_risks.utils import get_store
# flake8: noqa
account_key = os.environ.get('BLOB_ACCOUNT_KEY')
# this is only used to provide the x/y template for the insects/drought tifs
gri... |
9963980 | import dataset
import trees
import tensorflow as tf
import numpy as np
import utils
from sklearn.externals import joblib
from sklearn.tree import DecisionTreeClassifier
import argparse
import time
import pandas as pd
import json
import re
tf.enable_eager_execution()
parser = argparse.ArgumentParser()
parser.add_argum... |
9963996 | import viola
import pandas as pd
import sys, os
from io import StringIO
HERE = os.path.abspath(os.path.dirname(__file__))
HEADER = """##fileformat=VCFv4.1
##contig=<ID=chr1,length=195471971>
##contig=<ID=chr2,length=182113224>
##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description="Imprecise structural variation">
##INF... |
9964025 | t = int(raw_input())
for i in xrange(t):
data = [int(j) for j in raw_input().split()]
n = data[0]
x = data[1]
data = [int(j) for j in raw_input().split()]
if data[-1] == x:
minimum = 0
maximum = 1000000000000
for k in data:
if k < maximum and k > x:
... |
9964137 | import pkg_resources
ensembl_file_37 = 'annotations/ensembl_genes_37.txt.gz'
ensembl_file_38 = 'annotations/ensembl_genes_38.txt.gz'
ensembl_path_37 = pkg_resources.resource_filename('genmod', ensembl_file_37)
ensembl_path_38 = pkg_resources.resource_filename('genmod', ensembl_file_38) |
9964152 | from common.methods import set_progress
from infrastructure.models import Environment
import boto3
def connect_to_elasticache(env):
"""
Return boto connection to the elasticache in the specified environment's region.
"""
rh = env.resource_handler.cast()
return boto3.client(
'elasticache',... |
9964168 | from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from datetime import datetime
map = Basemap(projection='vandg',lon_0=0,resolution='c')
map.drawmapboundary(fill_color="#7777ff")
map.fillcontinents(color="#ddaa66",lake_color="#7777ff")
map.drawcoastlines()
map.nightshade(datetime.now(), delta... |
9964173 | from enum import Enum
class AggregationMode(Enum):
OVER_FLOW = 1
OVER_CLASSIFIER = 2
def __str__(self):
return self.name
@property
def counter(self):
return self.value
DEFAULT_AGGREGATION_MODE = AggregationMode.OVER_FLOW
|
9964193 | from sqlalchemy import create_engine, Column, MetaData, Table, Index
from sqlalchemy import Integer, String, Text, Float, Boolean, BigInteger, Numeric, SmallInteger, DateTime
import time
import requests
from requests_futures.sessions import FuturesSession
import requests_futures
from concurrent.futures import as_comple... |
9964207 | import os
import logging
import numpy as np
import cv2
import pandas as pd
from preprocessing import crop_face
from PIL import Image
class Entity(object):
def timestamps_sec(self):
""" Get timestamp of each frame from video file """
cap = cv2.VideoCapture(self.path_video)
ret = True
... |
9964221 | import protocols
class Conduit:
downlink = None
def __init__(self):
self.handlers = {}
self.setup()
def setup(self):
pass
def setDownlink(self, downlink):
self.downlink = downlink
def packetReceived(self, packet, fullPacket):
self.dispatch(packet, fullPac... |
9964278 | import tensorflow as tf
import unreal_engine as ue
from TFPluginAPI import TFPluginAPI
class ExampleAPI(TFPluginAPI):
#expected optional api: setup your model for training
def onSetup(self):
self.sess = tf.InteractiveSession()
#self.graph = tf.get_default_graph()
self.a = tf.placeholder(tf.float32)
self.b ... |
9964283 | import functools
from . import biggan
Generator = functools.partial(biggan.Generator, G_attn='0', hier=False, shared_dim=False)
Discriminator = functools.partial(biggan.Discriminator, D_attn='0', D_wide=False)
|
9964291 | import unittest
from path import PathBuilder, Pen
class PathBuilderTest(unittest.TestCase):
def test_add(self):
pb = PathBuilder()
p1 = (10, 10)
p2 = (20, 10)
pb.add_segment(p1, p2)
self.assertEqual(pb._segments, {p1: set([p2])})
def test_cancel(self):
pb = P... |
9964293 | import unittest
from partitura import (
EXAMPLE_MIDI,
EXAMPLE_MUSICXML,
load_performance_midi,
load_musicxml,
)
from partitura.musicanalysis.tonal_tension import (
prepare_note_array,
estimate_tonaltension,
)
import numpy as np
class TestTonalTension(unittest.TestCase):
score = load_musi... |
9964296 | import pytest
# module-level parameterization
pytestmark = pytest.mark.parametrize('x', [(1,), (1.0,), (1+0j,)])
def test_param_13(x):
assert x == 1
class TestParamAll(object):
def test_param_13(self, x):
assert x == 1
def test_spam_13(self, x):
assert x == 1
|
9964348 | import torch
def rmspe_loss(targets: torch.Tensor, predictions: torch.Tensor) -> torch.Tensor:
"""Root mean square percentage error."""
loss = torch.sqrt(torch.mean(((targets - predictions).float() / targets) ** 2))
return loss
def mean_confidence_penalty(probabilities: torch.Tensor, num_classes: int) -... |
9964366 | from yowsup.layers.protocol_iq.protocolentities.test_iq_result import ResultIqProtocolEntityTest
class GroupsResultIqProtocolEntityTest(ResultIqProtocolEntityTest):
pass |
9964372 | import xarray as xr
from .grid import convert_lon
from .stats import corr, linear_slope, linregress, polyfit, rm_poly, rm_trend
@xr.register_dataarray_accessor("grid")
@xr.register_dataset_accessor("grid")
class GridAccessor:
"""Allows functions to be called directly on an xarray dataset for the grid module.
... |
9964375 | from collections import OrderedDict
from functools import wraps
from sanic import Blueprint, Sanic
from sanic.exceptions import ServerError
from sanic.response import BaseHTTPResponse, text
from sanic_restful.exceptions import NotAcceptable
from sanic_restful.output import output_json
from sanic_restful.util import un... |
9964392 | from pylab import *
from collections import namedtuple
from .varifolds import Varifolds, Varifold
from .currents import Currents, Current
Cylinders = namedtuple('Cylinders', 'centers normals weights')
Spherical = namedtuple('Spherical', 'points directions weights')
class NormalCycle :
def __init__(self, cylinders, ... |
9964394 | import os
import infra.basetest
class TestS6Networking(infra.basetest.BRTest):
config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
"""
BR2_PACKAGE_S6_NETWORKING=y
BR2_TARGET_ROOTFS_CPIO=y
# BR2_TARGET_ROOTFS_TAR is not set
"""
def test_run(self):
img = os.path.... |
9964395 | import os
import pathlib
import secrets
from json import JSONDecodeError
import uvicorn
from asyncpgsa import pg
from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, JSONRespo... |
9964456 | r"""
YOLOv5 v6.0.
Add in 2022.03.04.
Upgrade in 2022.04.19.
"""
import math
import torch
import torch.nn as nn
from ...utils.log import logging_initialize
from ...utils.decode import parse_outputs_yolov5, filter_outputs2predictions, non_max_suppression
from ..units import Conv, C3, SPPF
from ...metaclass.metamodel im... |
9964459 | import os
import cv2
import torch
from config import CFG
class ShopeeDataset(torch.utils.data.Dataset):
"""for training
"""
def __init__(self,df, transform = None):
self.df = df
self.root_dir = CFG.DATA_DIR
self.transform = transform
def __len__(self):
return len(self... |
9964481 | from .core import Args
from .core import BindError
from .core import call
from .core import contexts
from .core import defaults
from .core import first
from .core import func
from .core import init
from .core import Lazy
from .core import load
from .core import parametrize
from .core import s
from .core import val
from... |
9964494 | import argparse
import csv
class dyndns(object):
def __init__(self):
try:
self.dyndns = {}
with open('dynamic-dns.csv') as f:
reader = csv.DictReader(f)
for row in reader:
self.dyndns[row["domain"]] = row["comment"]
se... |
9964541 | import pythonbible as bible
def test_invalid_verse_error_with_message() -> None:
# Given a message
message: str = "invalid verse"
try:
# When an InvalidVerseError is raised with that message
raise bible.InvalidVerseError(message)
except bible.InvalidVerseError as e:
# Then the... |
9964562 | from flask import jsonify
from flasgger import swag_from
@swag_from('package_specs.yml')
def package_view(username):
return jsonify({'username': username})
|
9964563 | def func_name(view_func):
return view_func.__name__
def normalize_vendor(name):
return name
|
9964594 | from pathlib import Path
import shutil
NUGET_DIR = Path(__file__).parents[1] / ".nuget"
TURDSHOVEL_DLLS = Path(__file__).parents[1] / "turdshovel/_dlls"
for file in NUGET_DIR.glob("*/lib/netstandard2.0/*"):
# Need to unblock files since downloaded from internet
Path(str(file) + ":Zone.Identifier").unlink(miss... |
9964608 | from allauth.account.adapter import DefaultAccountAdapter
from core.models import MyProfile
class UserAccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=True):
user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False)
user.save()
... |
9964626 | from grpc import insecure_channel
from loop_rpc.protos import loop_client_pb2 as loop, loop_client_pb2_grpc as looprpc
class LoopClient:
"""
As per the instructions at https://github.com/lightninglabs/loop/blob/master/README.md both
LND and loopd must be installed and running.
If loopd is running wit... |
9964634 | import unittest
from libsaas.executors import test_executor
from libsaas.services import bitly
class BitlyTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
self.executor.set_response(b'{}', 200, {})
self.service = bitly.Bitly('my-access-token')
def e... |
9964642 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
def GetFunction(item):
try: return item.get_Parameter(BuiltInParameter.FUNCTION_PARAM).AsValueString()
except: return None
items = UnwrapElement(IN[0])
if isinstance(IN[0], list): OUT = [GetFunction(x) for x in items]
else: OUT = GetFunction(i... |
9964657 | from anasymod.templates.generic_ip import TemplGenericIp
from anasymod.util import next_pow_2
from anasymod.targets import FPGATarget
class TemplILA(TemplGenericIp):
def __init__(self, target: FPGATarget, depth=4096):
# set defaults
scfg = target.str_cfg
# Sanity checking for ILA ... |
9964693 | import pytest
def test_passed():
pass
def test_failed():
assert 2 + 2 * 2 == 8
def test_broken():
raise Exception("Ima broke")
def test_skipped():
pytest.skip("yo")
raise Exception("If you see it - ima broke")
|
9964732 | from unittest import TestCase
import numpy as np
from cmlkit.utility import OptimizerLGS
def f(x, y):
return (x - 1.0) ** 2 + (y - 2.0) ** 2
class TestOptLGS(TestCase):
def test_quadratic_minimum(self):
lgs = OptimizerLGS()
result = lgs(f, ((), ()))
self.assertEqual(result["best"]... |
9964779 | from peewee import AutoField, IntegerField, ForeignKeyField, CharField
from ..database import Model
from .known_users import known_users
class nickname(Model):
ID = AutoField(primary_key=True)
ID_Inst = ForeignKeyField(known_users, related_name="nickname", unique=True)
nickname = CharField(max_length=32)
|
9964782 | import cv2 as cv
import numpy as np
import json
def load_json_data():
with open("config.json", 'r') as f:
load_json = json.load(f)
camera_parameter = load_json["camera2"]
known_distance = camera_parameter["known_distance"]
known_width = camera_parameter["known_width"]
known_height = camera... |
9964853 | import re
import json
import hashlib
import random
import logging
import asyncio
import inspect
import traceback
from .BaseGetter import BaseGetter
from ..Config.ConfigUtil.GetterConfig import RAPIConfig
from ..Config.ConfigUtil.AsyncHelper import AsyncGenerator
from ..PersistentUtil.PersistentWriter import PersistentW... |
9964871 | import scapy.all
class Deauthenticate:
def __init__(self, iface, bssid):
scapy.all.conf.verbose = False
self.iface = iface
self.pkt = (
scapy.all.RadioTap()
/ scapy.all.Dot11(
type=0,
subtype=12,
addr1="ff:ff:ff:ff:ff... |
9964875 | import os
import yaml
import json
import copy
import pprint
import argparse
import subprocess
from collections import defaultdict
NAMESPACE = os.environ.get('KUBECTL_PLUGINS_CURRENT_NAMESPACE')
KUBECTL_PATH = os.environ.get('KUBECTL_PLUGINS_CALLER')
class RBAC(object):
def __init__(self, namespace, kubectl_path... |
9964908 | def _gpg_sign_impl(ctx):
output_file = ctx.actions.declare_file(ctx.file.base.basename + ctx.attr.suffix, sibling = ctx.file.base)
if not ctx.configuration.default_shell_env.get("GPG_PASS"):
ctx.actions.write(output_file, "")
else:
command = "echo ${GPG_PASS} | gpg --pinentry-mode loopback --digest-algo S... |
9964977 | class Excluder(object):
def __init__(self, gallery_fids):
# Store the gallery data
self.gallery_fids = gallery_fids
def __call__(self, query_fids):
# Only make sure we don't match the exact same image.
return self.gallery_fids[None] == query_fids[..., None]
|
9965063 | from aws_lambda_typing.events import CodeCommitMessageEvent
def test_code_commit_event() -> None:
event: CodeCommitMessageEvent = {
"Records": [
{
"awsRegion": "us-east-2",
"codecommit": {
"references": [
{
... |
9965066 | import requests
import configuration
import performance
from mamba import description, context, it
from expects import expect, be_true, have_length, equal, be_a, have_property, be_none
rule_name="route-rule-http-redirect.yaml"
Rule=configuration.Rule()
with description('Testing HTTP Redirect'):
with before.all:
... |
9965079 | import picamera
import threading
import time
import subprocess
from rx import Observer
from modules import logger
from modules import utils
import config
import parameters
class CameraObserver(Observer):
def __init__(self):
camera = picamera.PiCamera()
camera.vflip = True
camera.hflip = ... |
9965108 | import functools
import threading
import logging
import inspect
from contextlib import contextmanager
from time import sleep
from typing import Any, Callable, ContextManager, Set, Type, Union, Optional
import attr
from privex.helpers.common import DictObject, auto_list, empty, empty_if
from privex.helpers.cache import... |
9965115 | import pytest
from pyle38.commands.sethook import SetHook
from pyle38.errors import Tile38Error
key = "fleet"
name = "warehouse"
endpoint = "kafka://10.0.20.78:9092/warehouse"
meta = {"city": "Berlin"}
@pytest.mark.asyncio
async def test_command_sethook_compile_within(tile38):
received = (
SetHook(tile3... |
9965116 | from .default_helper import deep_merge_dicts
from easydict import EasyDict
class Scheduler(object):
"""
Overview:
Update learning parameters when the trueskill metrics has stopped improving.
For example, models often benefits from reducing entropy weight once the learning process stagnates.
... |
9965123 | from osim.env import L2RunEnv
import opensim
env = L2RunEnv(visualize=True)
observation = env.reset()
s = 0
for s in range(80):
d = False
if s == 30:
state_old = env.osim_model.get_state()
print("State stored")
print(state_old)
if s % 50 == 49:
env.osim_model.set_state(sta... |
9965173 | import numpy
import chainerx
def test_constants():
assert chainerx.Inf is numpy.Inf
assert chainerx.Infinity is numpy.Infinity
assert chainerx.NAN is numpy.NAN
assert chainerx.NINF is numpy.NINF
assert chainerx.NZERO is numpy.NZERO
assert chainerx.NaN is numpy.NaN
assert chainerx.PINF is ... |
9965253 | from .fhirbase import fhirbase
class Distance(fhirbase):
"""
A length - a value with a unit that is a physical distance.
"""
__name__ = 'Distance'
def __init__(self, dict_values=None):
self.object_id = None
# unique identifier for object class
if dict_values:
... |
9965258 | import numpy as np
import pandas
import math
from sklearn.utils import resample
import time
import sys
import cdrds_analysis as cdrds
import random
# I might want to get rid of this shit to make it a more tunable script...
import seq_loader
ntasks = int(sys.argv[1])
which_num = int(sys.argv[2])
num_RE = 1000
# How ... |
9965309 | import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Linear, LayerNorm, ReLU
from torch_scatter import scatter
# from torch_geometric.nn import GINEConv
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree, softmax
from torch_geometric... |
9965314 | from __future__ import unicode_literals
from erpnext_biotrack.biotrackthc.client import BioTrackClientError
from .client import post
import frappe
from frappe.integration_broker.doctype.integration_service.integration_service import get_integration_controller
def sync_up_enabled():
if frappe.flags.in_import or frapp... |
9965321 | import ksc
from ksc.tracing.functions import core, math, nn
@ksc.trace
def dense(x, weights):
W, b = weights
return math.broadcast_add(math.dot(x, math.transpose(W)), b)
@ksc.trace
def conv_block(x, weights, strides):
(
conv_1_weights,
norm_1_weights,
conv_2_weights,
norm... |
9965383 | import sklearn
from .base import ExcursionModel
from .utils import get_kernel
import numpy as np
class SKLearnGP(ExcursionModel, sklearn.gaussian_process.GaussianProcessRegressor):
"""This is a guassian process used to compute the excursion model. Most if not all excursion models will be a
gaussian process.
... |
9965390 | import math
import random
import sys
def usage():
print( sys.argv[0] + " maximum_brightness(Default 100, 10-254) maximum_number_of_spheres(Default 5, 1-10)")
# if you are turning a lot of them on at once, keep their brightness down please
max_brightness = 100
min_brightness = math.floor(max_brightness/2) #Min brig... |
9965400 | from django.conf import settings
from django.core.management import BaseCommand, CommandError
from django.db import connection, transaction
PATH_DIGITS = getattr(settings, 'COMMENT_PATH_DIGITS', 10)
SQL = """
INSERT INTO threadedcomments_comment (
comment_ptr_id,
parent_id,
last_child_id,
tree_path... |
9965417 | from argparse import ArgumentParser
import numpy as np
argparser = ArgumentParser('test sentence generator')
argparser.add_argument('--keyword', default='')
argparser.add_argument('--switch', action='store_true')
argparser.add_argument('--best', action='store_true')
argparser.add_argument('--cfg', default='')
ar... |
9965424 | import json
import re
import pprint
import os
import argparse
import pandas as pd
import random
import numpy as np
from tqdm import tqdm
SQUAD_TEST_HEADS = ['where were', 'what political', 'what religion', 'why did', 'what type', 'what language', 'who had', 'what percentage', 'what can', 'how much']
def strip(sent):... |
9965440 | import pytest
import numpy as np
import numpy.testing as npt
from zepid import load_sample_data
from zepid.causal.ipw import IPMW
from zepid.causal.snm import GEstimationSNM
class TestGEstimationSNM:
@pytest.fixture
def data_c(self):
df = load_sample_data(False).drop(columns=['dead']).dropna()
... |
9965462 | import ply.lex as lex
from sema_ast import Number, Var
# TODO: lex hex literal
reserved = {
'FOR',
'ENDFOR',
'CASE',
'OF',
'ESAC',
'IF',
'THEN',
'ELSE',
'FI',
'DO',
'WHILE',
'OD',
'TO',
'DOWNTO',
'BREAK',
'RETURN',
'DEFINE',
'OP',
'AN... |
9965483 | from aiohttp import web
from external_modules.context.models import Infs
class CreateInfHelper(web.View):
async def post(self):
data = await self.request.json()
try:
inf = await Infs().create(uuid=data['buid'], inf_profile=data['profile'])
inf.uuid = inf.uuid_str
... |
9965496 | import argparse
import os
# python concat.py --dirs "outputs" --music music_sample/2.flac --output output.mp4
# Create the parser
vq_parser = argparse.ArgumentParser(description='concat')
# Add the arguments
vq_parser.add_argument("--dirs", type=str, default="outputs")
vq_parser.add_argument("--music", type=str)
vq_... |
9965501 | import random
from requests import post
from myclass import Information, ChessBoard
from styles import Style, array
class Generator(object):
# def generate_int(self, num, range_top, range_button = 0):
# int_list = []
# for i in range(num):
# int_list.append(random.randint((range_butt... |
9965510 | import httplib
import urllib
__author__ = 'oker'
class PushoverNotifier:
def notify(self, notification):
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.urlencode({
"token": notification.user_to_notify.profile.pushover_ap... |
9965515 | from __future__ import print_function
import openravepy
import unittest
import os # environ, path
import subprocess
import sys # stderr
import numpy
from prpy.clone import Clone
# Add the models included with OpenRAVE to the OPENRAVE_DATA path.
# These may not be available if the user manually set the OPENRAVE_DAT... |
9965541 | import logging
import os
import pprint
import tempfile
from urlparse import urlparse, parse_qs
from urllib import unquote
from assemblyline.common.exceptions import get_stacktrace_info
from assemblyline.common.net import get_hostip, get_hostname
from assemblyline.al.common import forge
from assemblyline.al.common.tra... |
9965562 | from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from models import db_base as base
import os
from datetime import datetime
from models.User import User
from models.ChatThread import ChatThread
from common.utils import *
from html.parse... |
9965606 | from ansible import context
from ansible.module_utils.common.collections import ImmutableDict
from ansible.playbook.play import Play
from testaid.ansiblerun import AnsibleRun
class MoleculePlay(object):
'''Run ansible playbooks against molecule host using the ansible python api.
'''
def __init__(self,
... |
9965614 | import torch
import argparse
import numpy as np
import random
import torchvision
import json
import os
import importlib
import torch.utils.data as data
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from typing import Optional
from iirc.datasets_loader import get_lifelong_da... |
9965656 | import torch
import torch.nn.functional as F
class OHEMHingeLoss(torch.autograd.Function):
"""
This class is the core implementation for the completeness loss in paper.
It compute class-wise hinge loss and performs online hard negative mining
(OHEM).
"""
@staticmethod
def forward(ctx, pre... |
9965714 | import json
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from net_utils import run_lstm, col_name_encode
class MultiSqlPredictor(nn.Module):
'''Predict if the next token is (multi SQL key words):
NONE, EXCEPT, INTERSECT, or UNION... |
9965720 | from github import Github
from github_token import GITHUB_TOKEN, user, password
g1 = Github(GITHUB_TOKEN)
g2 = Github(user, password)
#List all templates available to pass
#as an option when creating a repository
gitignore_templates = g1.get_gitignore_templates()
print(gitignore_templates)
for gitignore_template in ... |
9965724 | from DRecPy.Dataset import get_train_dataset
from DRecPy.Dataset import get_test_dataset
from DRecPy.Dataset import get_full_dataset
from DRecPy.Dataset import available_datasets
print('Available datasets', available_datasets())
# Reading the ml-100k full dataset and prebuilt train and test datasets.
print('ml-100k f... |
9965727 | from django.db import models
from openwisp_network_topology.base.link import AbstractLink
from openwisp_network_topology.base.node import AbstractNode
from openwisp_network_topology.base.snapshot import AbstractSnapshot
from openwisp_network_topology.base.topology import AbstractTopology
class DetailsModel(models.Mo... |
9965756 | from ...ut.bunch import bunchr, bunchset, bunchdel
from ..base import Mod
from ..mixins import (
ViewMixin,
NoEmptyQueryMixin,
make_blueprint_mixin,
IdentityGuessNameMixin,
make_field_guess_name_mixin
)
name = 'pixiv'
class Pixiv(
ViewMixin,
NoEmptyQueryMixin,
make_blueprint_mixin(__... |
9965800 | class Selection(object):
"""
Selection of nodes (MObject) and paths (MDagPath). Behaves like a set.
"""
def __contains__(self, item):
pass
def __init__(self, items='None'):
pass
def add(self, item):
pass
def clear(self):
... |
9965843 | import asyncio
import aiopg
from . import nwdb
from . import core
@core.handler
def send(client, member_id, type, text):
"""
Send a message to another member.
"""
client.require_auth()
with (yield from nwdb.connection()) as conn:
cursor = yield from conn.cursor()
yield from cursor... |
9965849 | import torch
import torch.nn.functional as F
from torch import nn
from torchvision import models
from multi_scale_module import ASPP,GPM,PPM,FoldConv_aspp,PAFEM
class RGBD_sal(nn.Module):
def __init__(self):
super(RGBD_sal, self).__init__()
################################vgg16####################... |
9965905 | import os
import ujson
import random
from argparse import ArgumentParser
from colbert.utils.utils import print_message, create_directory, load_ranking, groupby_first_item
from utility.utils.qa_loaders import load_qas_
def main(args):
print_message("#> Loading all..")
qas = load_qas_(args.qas)
rankings =... |
9965963 | from pomagma.compiler.expressions import Expression, Expression_0, Expression_2
from pomagma.compiler.util import memoize_arg, memoize_args
TOP = Expression_0('TOP')
BOT = Expression_0('BOT')
I = Expression_0('I')
F = Expression_0('F')
K = Expression_0('K')
B = Expression_0('B')
C = Expression_0('C')
J = Expression_0(... |
9965986 | import logging
import statistics
import typing
import boto3
import click
from boto3.dynamodb.conditions import Key
import cdk_s3_sns_latency.cdk_s3_sns_latency_stack as stack
BUCKET_WITH_LAMBDA: str = None
BUCKET_WITH_SNS: str = None
MEASUREMENT_TABLE_NAME: str = None
GENERATOR_FUNCTION_NAME: str = None
def get_c... |
9966002 | if __name__ == '__main__':
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from not_my_code import other
def callback2():
return 'my code2'
def callback1():
other.call_me_back2(callback2) # first step into my code
other.call_me_back1(call... |
9966019 | import argparse
import os
import batchgenerators.transforms as bg_tfm
import matplotlib.pyplot as plt
import numpy as np
import torchio as tio
import pymia.data.transformation as tfm
import pymia.data.augmentation as augm
import pymia.data.definition as defs
import pymia.data.extraction as extr
class Batchgenerator... |
9966052 | import numpy as np
import torch
from bisect import bisect_left
from PIL import Image
import os
# from .tiny_path_config import tiny_path
import paths_config
tiny_path = paths_config.location_dict['TinyImages']
dirname = os.path.dirname(__file__)
class TinyImages(torch.utils.data.Dataset):
def __init__(self, tr... |
9966083 | def switch_catalog_logging(catalog, logging_flag=True):
for name, data_set in catalog._data_sets.items():
if type(data_set).__name__.startswith("Mlflow"):
catalog._data_sets[name]._logging_activated = logging_flag
|
9966096 | from onnx_tf.handlers.frontend_handler import FrontendHandler
from onnx_tf.handlers.handler import onnx_op
from onnx_tf.handlers.handler import tf_op
@onnx_op("Identity")
@tf_op("Identity")
class Identity(FrontendHandler):
@classmethod
def version_1(cls, node, **kwargs):
return cls.make_node_from_tf_node(nod... |
9966136 | from ._sigma_points import (
JulierSigmaPointStrategy,
MerweSigmaPointStrategy,
SigmaPointStrategy,
)
from ._unscented_transform import UnscentedTransform
__all__ = [
"JulierSigmaPointStrategy",
"MerweSigmaPointStrategy",
"SigmaPointStrategy",
"UnscentedTransform",
]
|
9966155 | from pcf.particle.aws.vpc.vpc_instance import VPCInstance
from pcf.core import State
particle_definition = {
"pcf_name": "pcf_vpc",
"flavor": "vpc_instance",
"aws_resource": {
"custom_config":{
"vpc_name":"test",
"Tags":[{"Key":"Name","Value":"test"}]
},
"Cid... |
9966160 | import importlib
commands = {
'apply': 'apply',
'check': 'check',
'import': 'import_files',
'plan': 'plan',
'plan_export': 'plan_export',
'version': 'version'
#'export': 'export_files'
}
def allowed(command):
return command in commands
def execute(command, options):
if not c... |
9966190 | import os, getpass
if getpass.getuser() == 'samuel':
ironclust_path = '/home/samuel/Documents/SpikeInterface/ironclust/'
os.environ["IRONCLUST_PATH"] = ironclust_path
import unittest
import pytest
from spikeinterface.sorters import IronClustSorter
from spikeinterface.sorters.tests.common_tests import SorterC... |
9966216 | from __future__ import absolute_import, print_function
# imports
from .n2v_config import N2VConfig
from .n2v_standard import N2V |
9966222 | import time
from functools import wraps
from pypact.util.exceptions import PypactFrozenException
def freeze_it(cls):
cls.__frozen = False
def frozensetattr(self, key, value):
if self.__frozen and not hasattr(self, key):
raise PypactFrozenException(
"Class {} is frozen. Ca... |
9966228 | import sys
sys.path.append("cider")
import pickle
from pyciderevalcap.ciderD.ciderD import CiderD
class Cider:
def __init__(self, args):
self.cider = CiderD(df='coco-train')
with open('data/train_references.pkl') as fid:
self.references = pickle.load(fid)
def get_scores(self, seqs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.