id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11517826 | import os
import io
import json
import argparse
import time
import glob
import ntpath
from typing import List
class SppClient:
def process(self, input: str, output: str):
raise NotImplementedError
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Client for ScienceParsePlus (S... |
11517856 | import os
import tensorflow as tf
from riptide.binary import binary_layers as nn
def channel_shuffle(x, groups):
n, h, w, c = x.shape
channels_per_group = tf.math.floordiv(c, groups)
# reshape
x = tf.reshape(x, [n, h, w, groups, channels_per_group])
x = tf.transpose(x, [0, 1, 2, 4, 3])
x = tf.... |
11517878 | import argparse
import logging
from os import path
from kubebench.test import deploy_utils
from kubeflow.testing import test_helper
from kubeflow.testing import util # pylint: disable=no-name-in-module
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--namespace", default=None, typ... |
11517896 | from keras.models import Model
from keras.layers import Input, merge, ZeroPadding2D
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import AveragePooling2D, GlobalAveragePooling2D, MaxPooling2D
from keras.layers.normalization import... |
11517903 | from conans import ConanFile, CMake, tools
import os
import subprocess
class EigenQLDTestConan(ConanFile):
requires = "eigen-qld/1.0.0@gergondet/stable"
settings = "os", "arch", "compiler", "build_type"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
... |
11517919 | import argparse
from model.utils.config import cfg, cfg_from_file, cfg_from_list
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--dataset', dest='dataset',
help='source training... |
11517922 | from dataclasses import dataclass
@dataclass
class Person:
"""Person class creates an user object"""
_weight: float = 0.0
_height: float = 0.0
_age: int = 0
_gender: str = 'male'
_body_fat: float = 0.0
@property
def weight(self) -> float:
"""Weight in pounds"""
return ... |
11517924 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.hub import load_state_dict_from_url
import torchvision
from functools import partial
from collections import OrderedDict
import math
import os,inspect,sys
currentdir = os.path.dirname(o... |
11517974 | sm.setSpeakerID(2159008)
sm.sendNext("Little rats. I say, how DARE you try to escape this place?")
sm.setPlayerAsSpeaker()
sm.sendSay("Shoot, we were spotted!")
sm.setSpeakerID(2159008)
sm.sendSay("Now, now, children. Don't make this harder than it needs to be. Just walk towards me, nice and easy... Wait, you're not ... |
11518030 | import ConfigParser
import logging
import os
import unittest
from impacket.examples.secretsdump import LocalOperations, RemoteOperations, SAMHashes, LSASecrets, NTDSHashes
from impacket.smbconnection import SMBConnection
def _print_helper(*args, **kwargs):
try:
print args[-1]
except UnicodeError:
... |
11518032 | from dataloading.dataloading import get_dataloader
from dataloading.configloading import load_config
|
11518058 | from startX.serivce.v1 import StartXHandler, get_m2m_display, Option
from django.urls import reverse
from django.utils.safestring import mark_safe
from .base_promission import PermissionHandler
class CourseDetailHandler(PermissionHandler, StartXHandler):
def display_outline(self, model=None, is_header=None, *args... |
11518094 | import atexit
import sacred
import argparse
import time
import math
import subprocess
import shutil
import os
import json
import threading
import requests
import glob
from configs import fetch_model_params
import socket
import subprocess
import queue
import sys
import signal
parser = argparse.ArgumentParser()
parser.... |
11518134 | import time
import scrapely
from . import slybot_project
from . import kernel
from . import ptree
def generate_slybot_project(url, path='slybot-project', verbose=False):
def _print(s):
if verbose:
print s,
_print('Downloading URL...')
t1 = time.clock()
page = scrapely.htmlpage.ur... |
11518147 | from flask import url_for
import pytest
from flexmeasures.data.services.users import find_user_by_email
from flexmeasures.ui.tests.utils import mock_user_response
"""
Testing if the UI crud views do auth checks and display answers.
Actual logic is tested in the API tests.
"""
@pytest.mark.parametrize("view", ["inde... |
11518163 | import numpy as np
from numpy import linalg as la, random as rnd, testing as np_testing
from scipy.linalg import eigvalsh, expm
from pymanopt.manifolds import SymmetricPositiveDefinite
from pymanopt.tools.multi import multiprod, multisym, multitransp
from .._test import TestCase
class TestSingleSymmetricPositiveDefi... |
11518203 | from . import dependency
import unittest
class DependencyGraphTestCase(unittest.TestCase):
def test_add_all(self):
graph = dependency.DependencyGraph()
graph.add_all({
'/content/test.yaml': ['/content/test1.yaml'],
'/content/test2.yaml': ['/content/test1.yaml'],
})... |
11518230 | import os
import javabridge as jv
from cellacdc import bioformats
# import bioformats
print(bioformats.__file__)
# path = r'"G:\My Drive\01_Postdoc_HMGU\Python_MyScripts\MIA\Git\Cell_ACDC\cellacdc\bioformats\jars\bioformats_package.jar"'
jars = bioformats.JARS
print(jars)
jv.start_vm(class_path=jars)
paths = jv.JCl... |
11518263 | from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.contrib.sites.models impo... |
11518268 | import io
import os
import json
import zipfile
import argparse
import urllib.request
import multiprocessing
from os.path import join as pjoin
import tqdm
import numpy as np
import spacy
import textworld
from textworld.logic import State, Rule, Proposition, Variable
from generic import preproc
from generic import pro... |
11518284 | from typing import List
import gevent
import pytest
from eth_typing import Address, BlockNumber
from web3 import Web3
from raiden.constants import BLOCK_ID_LATEST, GENESIS_BLOCK_NUMBER
from raiden.exceptions import BrokenPreconditionError
from raiden.network.proxies.proxy_manager import ProxyManager, ProxyManagerMeta... |
11518287 | import maya.mel as mm
import maya.cmds as mc
import glTools.tools.mesh
import glTools.utils.component
import glTools.utils.mathUtils
import glTools.utils.mesh
import glTools.utils.skinCluster
def cutSkin(mesh,weightThreshold=0.25,reducePercent=None,parentShape=False):
'''
Extract a per influence proxy mesh from a ... |
11518293 | from altfe.interface.root import interRoot
@interRoot.bind("api/biu/get/idworks/", "PLUGIN")
class getIDWorks(interRoot):
def run(self, cmd):
try:
args = self.STATIC.arg.getArgs(
"userWorks",
[
"userID=%s" % self.CORE.biu.apiAssist.user_id,
... |
11518338 | import pytest
from jumpscale.loader import j
from solutions_automation import deployer
from tests.sals.automated_chatflows.chatflows_base import ChatflowsBase
from gevent import sleep
@pytest.mark.integration
class PoolChatflows(ChatflowsBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
... |
11518352 | import json
from conftest import setup_dashboard
def test_freeform_mode_has_no_rows_or_cols(monkeypatch, ctx, client):
app, test = client
data = dict(
mode='freeform',
name='Some dashboard',
module_baz=json.dumps(
dict(name=1, width=400, height=112, dataSource='...')
... |
11518375 | from tests.integration.integration_test_case import IntegrationTestCase
class TestSessionExpired(IntegrationTestCase):
def test_session_expired_should_log_user_out(self):
self.launchSurvey('1', '0205')
start_page = self.last_url
self.post(url='/expire-session')
self.assertStatusOK... |
11518376 | import os
import sys
import argparse
from functools import partial
import time
import matplotlib.pyplot as plt
# import seaborn.apionly as sns
import seaborn as sns
import torch.nn as nn
import torch.nn.utils.spectral_norm as spectral_norm
from torch import autograd
from torch.autograd import Variable
import ray.tun... |
11518412 | from os import remove
import shlex
from os.path import isfile, join, split, splitext
from prody.tests import TestCase, skipIf, skipUnless
from numpy.testing import *
try:
import numpy.testing.decorators as dec
except ImportError:
from numpy.testing import dec
from prody import parsePDB, DCDFile, parseDCD
fro... |
11518426 | import os
import torch
import torch.optim as optim
from imbalanceddl.utils.utils import AverageMeter, save_checkpoint, collect_result
from imbalanceddl.utils.metrics import accuracy
from .base import BaseTrainer
class Trainer(BaseTrainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **k... |
11518435 | import utils
import random
import argparse
import tsp_ga as ga
from datetime import datetime
def run(args):
genes = utils.get_genes_from(args.cities_fn)
if args.verbose:
print("-- Running TSP-GA with {} cities --".format(len(genes)))
history = ga.run_ga(genes, args.pop_size, args.n_gen,
... |
11518440 | from __future__ import unicode_literals
from abc import ABCMeta
from future.utils import with_metaclass
from .base import Base
class Message(with_metaclass(ABCMeta, Base)):
"""Abstract Base Class of Message."""
def __init__(self, id=None, mid=None, seq=None, is_echo=None, app_id=None, metadata=None, **kwar... |
11518497 | from django.shortcuts import render
import re
from punctuation.removePunctuations import Punctuation
def indexView(request):
if request.method=="POST":
string = request.POST["string"]
removePunc = request.POST.get("removePunc",False)
removeDigit = request.POST.get("r... |
11518498 | from modelchimp.tests import BaseTest
from modelchimp.factories.factory_user import UserFactory
from modelchimp.models.user import User
class UserModelTest(BaseTest):
model_class = User
factory_class = UserFactory
data = {
'username' : 'modelchimp_admin',
'email':'<EMAIL>',
'passw... |
11518542 | from math import sqrt
from tessagon.core.tile import Tile
from tessagon.core.tessagon import Tessagon
from tessagon.core.tessagon_metadata import TessagonMetadata
# TODO: gulp, 'octagon' does not begin with 'octo'
metadata = TessagonMetadata(name='Octagons and Squares',
classification='arc... |
11518548 | import os
import random
from avel.video_lib import drawtext, create_drawtext_dict
"""
create_hiit_video takes in a video file (e.g. TV show) and outputs a HIIT workout video
It employs a routine of 15s of high-intensity exercises, followed by 45s of low-intensity
It displays text to inform me when to work out and rest... |
11518565 | from .aes import InvalidPadding
from .keys import verify_signed_text, Key, PublicKey, PrivateKey
from .transaction import TxInput, TxOutput, Transaction, Unspent, InsufficientFunds
from .wallet import Wallet
__version__ = '0.8.0'
|
11518566 | from __future__ import print_function, division
import os
import shutil
import tempfile
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal_nulp
from astropy import units as u
from .. import Model
from ..image import Image
from ...util.functions import random_id
from .test_helpers i... |
11518571 | import os.path as osp
from torch_geometric.datasets import Planetoid
import torch_geometric.transforms as T
def get_planetoid_dataset(name, normalize_features=False, transform=None):
path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
dataset = Planetoid(path, name)
if transform is ... |
11518580 | from apple.util.ints import uint64
# The actual space in bytes of a plot, is _expected_plot_size(k) * UI_ACTUAL_SPACE_CONSTANT_FACTO
# This is not used in consensus, only for display purposes
UI_ACTUAL_SPACE_CONSTANT_FACTOR = 0.762
def _expected_plot_size(k: int) -> uint64:
"""
Given the plot size parameter ... |
11518598 | from BaseController import BaseController
import tornado.ioloop
import tornado.web
import dateutil.parser
import datetime
class TopCommandsController(BaseController):
def get(self):
return_data = dict(data=[],
timestamp=datetime.datetime.now().isoformat())
server = sel... |
11518609 | import os
import glob
import numpy as np
import nibabel as nib
import pandas as pd
from glmsingle.design.make_design_matrix import make_design
from glmsingle.glmsingle import GLM_single
import time
sub = 2
ses = 1
stimdur = 0.5
tr = 2
proj_path = os.path.join(
'/home',
'adf',
'charesti',
'data',
'... |
11518640 | from unittest import mock, skipUnless
from django.db import connection
from django.db.backends.mysql.features import DatabaseFeatures
from django.test import TestCase
@skipUnless(connection.vendor == 'mysql', 'MySQL tests')
class TestFeatures(TestCase):
def test_supports_transactions(self):
"""
... |
11518657 | from boa3.builtin import public
@public
def Main(condition: bool) -> int:
a = 0
if condition:
a = a + 2
else:
a = 10
return a
|
11518679 | import os
import sys
import acconeer.exptool as et
def main():
parser = et.utils.ExampleArgumentParser()
parser.add_argument("-o", "--output-dir", type=str, required=True)
parser.add_argument("--file-format", type=str, default="h5")
parser.add_argument("--frames-per-file", type=int, default=10000)
... |
11518684 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class CRF(nn.Module):
"""
Class for learning and inference in conditional random field model using mean field approximation
and convolutional approximation in pairwise potentials term.
Parameters
----------
n... |
11518686 | import argparse
import os
import ubiq_internal_tasks as tasks
from Ity.Tokenizers import RegexTokenizer
from collections import defaultdict
import sys
import csv
import math
from operator import itemgetter
__author__ = 'wintere'
parser = argparse.ArgumentParser(description='Test Ubiqu+Ity tag_corpus task')
parser.ad... |
11518708 | import datetime as dt
import pytest
import pytz
import stix2
from .constants import CAMPAIGN_ID, CAMPAIGN_MORE_KWARGS, IDENTITY_ID
EXPECTED = """{
"type": "campaign",
"id": "campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
"created_by_ref": "identity--311b2d2d-f010-4473-83ec-1edf84858f4c",
"created"... |
11518713 | import sys
import os
import numpy as np
import time
from PIL import Image
APS = 100;
TileFolder = sys.argv[1] + '/';
heat_map_out = 'patch-level-color.txt';
def whiteness(png):
wh = (np.std(png[:,:,0].flatten()) + np.std(png[:,:,1].flatten()) + np.std(png[:,:,2].flatten())) / 3.0;
return wh;
def blackness(p... |
11518734 | from jikji import getview
getview('myview.home').url_rule = '/'
getview('myview.profile').url_rule = '/$1/'
getview('myview.requirements').url_rule = '/requirements.txt' |
11518749 | number1 = input('Enter first number: ')
number2 = input('Enter second number: ')
number3 = input('Enter third number')
sum = int(number1) + int(number2) + int(number3)
print(sum)
|
11518758 | import itertools
from array import array
from collections import Counter
import pytest
from hypothesis import given, strategies
from anonlink.solving import (
greedy_solve, greedy_solve_python, greedy_solve_native, pairs_from_groups,
probabilistic_greedy_solve, probabilistic_greedy_solve_native,
probabili... |
11518769 | import boto3
import os
import time
import json
'''
SAMPLE EVENTS
####
Import Events from config.json file
####
{
"LanguageCodes": [
"en",
"fr",
"es"
]
}
####
Insert or overwrite messages using events
####
{
"LanguageCodes": [
"en",
"fr",
"es"
],
"C... |
11518832 | from subprocess import *
class HighlightPipe:
""" This Python package serves as interface to the highlight utility.
Input and output streams are handled with pipes.
Command line parameter length is validated before use."""
def __init__(self):
self.cmd = 'highlight'
self.src=''
self.options=dict()
self.su... |
11518862 | from time import time
from urllib.parse import parse_qs, urlsplit
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db import IntegrityError
from d... |
11518947 | from __future__ import print_function
import unittest
import numpy
import irbasis
from irbasis_util.internal import *
class TestMethods(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestMethods, self).__init__(*args, **kwargs)
def test_o_to_matsubara(self):
for n in r... |
11518964 | import sublime
import traceback, threading, os, sys, imp, tarfile, zipfile, urllib, json, shutil
import node_variables
from animation_loader import AnimationLoader
from repeated_timer import RepeatedTimer
from main import NodeJS
from main import NPM
def check_thread_is_alive(thread_name) :
for thread in threading.en... |
11518992 | from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, np.rint(y_pred)))
cf_10_3 = confusion_matrix(y_test, np.rint(y_pred))
|
11519005 | import os
from conans import ConanFile, CMake
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'version'), 'r') as f:
content = f.read()
try:
content = content.decode()
except AttributeError:
pass
return content.strip()
class Bip39Cona... |
11519035 | from roiextractors import Suite2pSegmentationExtractor
from ..basesegmentationextractorinterface import BaseSegmentationExtractorInterface
from ....utils.json_schema import FilePathType, IntType
class Suite2pSegmentationInterface(BaseSegmentationExtractorInterface):
"""Data interface for Suite2pSegmentationExtr... |
11519047 | from default_config import basic_cfg
cfg = basic_cfg
cfg.train_df = cfg.data_dir + "train_meta_4folded_v1.csv"
cfg.val_df = cfg.data_dir + "train_soundscape_labels_v2.csv"
# dataset
cfg.min_rating = 2.0
cfg.wav_crop_len = 30 # seconds
cfg.lr = 0.0001
cfg.epochs = 20
cfg.batch_size = 32
cfg.batch_size_val = 1
cfg.d... |
11519061 | import logging
from texts.models import Subscriber
from twilio import TwilioRestException
from util.showerthoughts import get_todays_thought
from util.texter import DuplicateTextException, Texter
def subscribe(sms_number):
if not sms_number:
return 'You sent nothing yo.'
sms_number = filter(str.isdigi... |
11519091 | import unittest
from carbon.aggregator.rules import AggregationRule
class AggregationRuleTest(unittest.TestCase):
def test_inclusive_regexes(self):
"""
Test case for https://github.com/graphite-project/carbon/pull/120
Consider the two rules:
aggregated.hist.p99 (10) = avg... |
11519092 | import unittest
import mock
from rollingpin.args import (
parse_args,
make_profile_parser,
construct_canonical_commandline,
)
class TestArgumentParsing(unittest.TestCase):
def setUp(self):
self.config = {
"deploy": {
"default-parallel": 5,
"default... |
11519094 | import os
import sys
import io
from mock import *
from .gp_unittest import *
from gppylib.programs.clsAddMirrors import GpAddMirrorsProgram, ProgramArgumentValidationException
from gparray import Segment, GpArray
from gppylib.system.environment import GpCoordinatorEnvironment
from gppylib.system.configurationInterface... |
11519115 | StringType = getmeta("")
ListType = getmeta([])
DictType = getmeta({})
class Exception:
def __init__(self, *args):
self.args = args
def __repr__(self):
return str(self.args)
class ImportError(Exception):
pass
def startswith(self, prefix):
return self.find(prefix) == 0
StringType['sta... |
11519125 | from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
from tdw.version import __version__
import docker
import time
import os
import subprocess
"""
Using NVIDIA Flex in a docker container, drape a cloth over an object.
"""
class DockerController(Controller):
def __init__(self):
... |
11519145 | from .code import CodeUtil
from .mol import MolUtil
from .tud import TUUtil
DATASET_UTILS = {
'ogbg-code': CodeUtil,
'ogbg-code2': CodeUtil,
'ogbg-molhiv': MolUtil,
'ogbg-molpcba': MolUtil,
'NCI1': TUUtil,
'NCI109': TUUtil,
}
|
11519209 | import torch
from torch import nn
from torch.cuda import amp
from quickvision import utils
from tqdm import tqdm
import time
from collections import OrderedDict
from quickvision.models.detection.utils import _evaluate_iou, _evaluate_giou
__all__ = ["train_step", "val_step", "fit", "train_sanity_fit",
"val_s... |
11519220 | from packetbeat import (BaseTest, FLOWS_REQUIRED_FIELDS)
from pprint import PrettyPrinter
import six
def pprint(x): return PrettyPrinter().pprint(x)
def check_fields(flow, fields):
for k, v in six.iteritems(fields):
assert flow[k] == v
class Test(BaseTest):
def test_mysql_flow(self):
self... |
11519229 | from metrics.metric import Metric
from typing import Dict, Union
import torch
class PiBehaviorCloning(Metric):
"""
Behavior closing loss for training graph traversal policy.
"""
def __init__(self, args: Dict):
self.name = 'pi_bc'
def compute(self, predictions: Dict, ground_truth: Union[to... |
11519246 | import math
import torch
import torch.nn as nn
from kornia.geometry.subpix import dsnt
from kornia.utils.grid import create_meshgrid
class FineMatching(nn.Module):
"""FineMatching with s2d paradigm."""
def __init__(self):
super().__init__()
def forward(self, feat_f0, feat_f1, data):
""... |
11519250 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
hltMuonValidator = DQMEDAnalyzer('HLTMuonValidator',
hltProcessName = cms.string("HLT"),
hltPathsToCheck = cms.vstring(
"HLT_(L[12])?(Iso)?(Tk)?Mu[0-9]*(Open)?(_NoVertex)?(_eta2p1)?(_v[0-9]*)?$",
... |
11519255 | import asyncio
import logging
from caldera_agent import agent_protocol
from caldera_agent import foster3 as foster
from caldera_agent import utils
import win32ts
import win32security
import re
# Add module name to log messages
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
log.setLevel(loggin... |
11519289 | from os import makedirs
from os.path import exists, join
from typing import Any, Sequence, Tuple
import imageio
from arbol.arbol import aprint, asection
from joblib import Parallel, delayed
from dexp.datasets import BaseDataset
from dexp.processing.color.projection import project_image
from dexp.utils.backends import... |
11519309 | import warnings
from inspect import isclass
import numpy as np
from UQpy.RunModel import RunModel
from UQpy.SampleMethods import *
########################################################################################################################
################################################################... |
11519343 | import json
import os
import random
from glob import glob
import numpy as np
import pandas as pd
# from preprocessing.CredbankProcessor import preprocessing_tweet_text
from CredbankProcessor import preprocessing_tweet_text
from src.data_loader import load_files_from_dataset_dir, load_matrix_from_csv
from pprint impor... |
11519361 | from click.testing import CliRunner
from healthkit_to_sqlite import cli, utils
import io
import pathlib
import pytest
import sqlite_utils
from sqlite_utils.db import ForeignKey
import pathlib
import zipfile
@pytest.fixture
def xml_path():
return pathlib.Path(__file__).parent / "export.xml"
@pytest.fixture
def x... |
11519414 | from .serving import run_simple as run_simple
from .test import Client as Client
from .wrappers import Request as Request
from .wrappers import Response as Response
__version__ = "2.1.0.dev0"
|
11519433 | import shortuuid
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from urllib.parse import urljoin
from app.files import RandomFileName
from app.models import DefaultQuerySet, TimestampedModel, models
from app.tasks import send_mail
from users.models import User
class Languages... |
11519436 | from socket import *
serverName = 'localhost'
serverPort = 3001
serverSocket= socket(AF_INET, SOCK_STREAM)
serverSocket.connect( (serverName, serverPort) )
script=open('testcommand2.py','rb')
serverSocket.send(script.read())
wow = serverSocket.recv(1024)
serverSocket.close()
|
11519463 | from __future__ import print_function, division
import os
import sys
import json
import pandas as pd
def convert_csv_to_dict(csv_path, subset, labels):
data = pd.read_csv(csv_path, delimiter=' ', header=None)
keys = []
key_labels = []
key_start_frame = []
key_end_frame = []
for i in range(data.... |
11519465 | import logging
from typing import Any, Dict, List, Optional
import torch
from torch.autograd import Variable
from torch.nn import Linear,ReLU
from torch.nn.functional import nll_loss
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from alle... |
11519475 | from pymongo import MongoClient
import app
import settings
def connect(collection):
client = MongoClient()
d = client[settings.MONGO_DATABASE]
return d[collection]
def bake():
from flask import g
for route in ['index']:
with (app.app.test_request_context(path="/%s.html" % route)):
... |
11519488 | class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
MOD = 10 ** 9 + 7
A.sort()
total = 0
c = 1
for i in range(len(A)):
total = (total + A[i] * c - A[len(A) - i - 1] * c) % MOD
c = (c * 2) % MOD
return total
|
11519517 | from base import BaseModel
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from itertools import chain
from math import ceil
class SegNet(BaseModel):
def __init__(self, num_classes, in_channels=3, pretrained=True, freeze_bn=False, **_):
super(SegNet, self).... |
11519536 | import datetime
import subprocess
import threading
import random
import queue
import atexit
import json
import time
import sys
import re
import os
class Remote:
def __init__(self, address=None, port=None, identity_file=None):
self.address = address
self.port = port or 22
self.ifile = ident... |
11519587 | import numpy as np
from scipy.linalg import expm
def cost(seq):
N=len(seq)
dt=2*np.pi/N
sx=1/2 * np.mat([[0,1],\
[1,0]], dtype=complex)
sz=1/2 * np.mat([[1,0],\
[0,-1]], dtype=complex)
U = np.matrix(np.identity(2, dtype=complex)) #initial Evolution operator
... |
11519588 | import json
import sys, os.path
import os
storage = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..\..')) + '\\storageManager')
sys.path.append(storage)
error_path = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..\..')) + '\\ERROR')
sys.path.append(error_path)
response_path = (os.path.abspa... |
11519617 | from tkinter import *
root = Tk()
b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()
root.mainloop() |
11519622 | r"""
Fermionic Ghosts Super Lie Conformal Algebra
The *Fermionic-ghosts* or b--c system super Lie conformal algebra
with `2n` generators is the H-graded super Lie conformal algebra
generated by odd vectors `b_i, c_i, i = 1,\ldots,n` and a central
element `K`, with non-vanishing `\lambda`-brackets:
.. MATH::
[{b_... |
11519629 | import numpy as np
from yggdrasil.components import ComponentBase
class FilterBase(ComponentBase):
r"""Base class for message filters.
Args:
initial_state (dict, optional): Dictionary of initial state variables
that should be set when the filter is created.
"""
_filtertype = Non... |
11519638 | import unittest
from com.example.client.config.low_level_client import ESLowLevelClient
class TestLowLevelClientSearch(unittest.TestCase):
es = ESLowLevelClient.get_instance()
def test_match_phrase_query(self):
body={
"query": {
"match_phrase": {
"fund_... |
11519682 | from typing import Any, Dict, List, Text
import regex
import re
import rasa.shared.utils.io
from rasa.shared.constants import DOCS_URL_COMPONENTS
from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer
from rasa.shared.nlu.training_data.message import Message
class WhitespaceTokenizer(Tokenizer):
defaults =... |
11519721 | import importlib
import logging
import sys
import click
import numpy as np
import tensorflow as tf
from experiment.config import load_config
@click.command()
@click.argument('config_file')
def run(config_file):
"""This program is the starting point for every experiment. It pulls together the configuration and a... |
11519755 | from functools import reduce
from math import ceil
from concurrent.futures import ProcessPoolExecutor, as_completed
from .mergesort import sort as _sort, merge
def sort(v, workers=2):
if len(v) == 0:
return v
dim = ceil(len(v) / workers)
chunks = (v[k: k + dim] for k in range(0, len(v), dim))
... |
11519811 | import logging
import urllib
import requests
import base64
import voluptuous as vol
from datetime import timedelta
from homeassistant.helpers.discovery import load_platform
import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_HOST
from homeassistant.h... |
11519835 | import requests
from flask import abort, jsonify, request, Blueprint
from nookipedia.config import DB_KEYS
from nookipedia.middlewares import authorize
from nookipedia.cargo import call_cargo, get_other_item_list
from nookipedia.errors import error_response
from nookipedia.models import format_other_item
from nookiped... |
11519847 | import tarfile
import argparse
import subprocess
from pathlib import Path
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
from model import *
from utils import *
from dataset import *
def parse_args():
parser = argparse.ArgumentParser()
parser.add_a... |
11519855 | import unittest
from Ejercicio3 import ITasks, SystemAuthProxy, User
class ProxyTest(unittest.TestCase):
def test_level_one_user(self):
usr = User(name='foo', access_level=1)
proxy = SystemAuthProxy(usr, "Payments")
self.assertEqual("User 'foo' is doing level-1 tasks on system ### Payments ... |
11519874 | import json
import platform
import sys
import sysconfig
if platform.python_implementation() == "PyPy":
# Workaround for PyPy 3.6 on windows:
# - sysconfig.get_config_var("EXT_SUFFIX") differs to importlib until
# Python 3.8
# - PyPy does not load the plain ".pyd" suffix because it expects that's
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.