id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1631140 | from twisted.web import proxy
class TerminalResource(proxy.ReverseProxyResource):
def __init__(self):
proxy.ReverseProxyResource.__init__(self, "127.0.0.1", 4200, '')
|
1631208 | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt
import sys
from typing import List
from neural_network import *
from snake import Snake
class NeuralNetworkViz(QtWidgets.QWidget):
def __init__(self, parent, snake: Snake):
super().__init__(parent)
self.snake = snake... |
1631236 | from loguru import logger
from tests.conftest import MIN_MS1_INTENSITY, check_non_empty_MS2, check_mzML, OUT_DIR, BEER_CHEMS, BEER_MIN_BOUND, \
BEER_MAX_BOUND
from vimms.Common import POSITIVE
from vimms.Controller import TopNController
from vimms.Environment import Environment
from vimms.MassSpec import Independe... |
1631286 | 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 TimestampedModel, models
from app.tasks import send_mail
class Languages(models.TextChoices):
RU = 'RU', _('Russian... |
1631300 | import datetime
import os
from fastfec import FastFEC
def test_filing_1550126_line_callback(filing_1550126):
"""
Test the FastFEC line-by-line callback functionality, in addition
to the package's ability to parse summary, contribution and
disbursement rows.
"""
with open(filing_1550126, "rb")... |
1631325 | from tx2.calc import frequent_words_in_cluster, frequent_words_by_class_in_cluster
def test_frequent_words_in_cluster(dummy_df):
freq_words = frequent_words_in_cluster(dummy_df.text)
assert freq_words == [("row", 4), ("testing", 4), ("awesome", 2)]
def test_frequent_words_by_class_in_cluster(dummy_df, dummy... |
1631327 | input = """
arc(a,b,2).
arc(a,c,3).
arc(b,d,3).
arc(c,d,2).
arc(d,a,2).
% maxint is deliberately set too large to detect wrong minima.
#maxint=20.
path(X,Y,C) :- arc(X,Y,C).
path(X,Y,C) :- arc(X,Z,C1), path(Z,Y,C2), C = C1 + C2.
minpath(X,Y,C) :- path(X,Y,C), C = #min{ C1: path(X,Y,C1) }.
"""
output = """
{arc(a,b... |
1631383 | def processing(mode, text, key):
key_ints = [ord(i) for i in key]
text_ints = [ord(i) for i in text]
finished_text = ""
for i in range(len(text_ints)):
adder = key_ints[i % len(key)]
if mode == 1:
adder *= -1
char = (text_ints[i] - 32 + adder) % 95
finished_te... |
1631400 | import notebookgenerator
def init():
print('Generating notebooks.')
notebookgenerator.main()
def clean(app, *args):
print('Remove rst notebook files.')
#notebookgenerator.clean()
def setup(app):
init()
app.connect('build-finished', clean)
|
1631401 | from . import unet2d
from . import segmentation_models_pytorch as smp
def get_base(base_name, exp_dict, n_classes):
if base_name == "fcn8_vgg16":
base = fcn8_vgg16.FCN8VGG16(n_classes=n_classes)
if base_name == "unet2d":
base = unet2d.UNet(n_channels=1, n_classes=n_classes)
if base_name ... |
1631408 | import pandas as pd
import numpy as np
import scipy
from scipy.stats import laplace
def estimate_precsion(max, min ):
diff= 1/max
precision=(diff - min) / (max - min)
return precision
def match_vals(row, cumsum, precision):
cdf=float(cumsum[cumsum.index==row['relative_time']])
#cdf plus
v... |
1631419 | from talon.voice import Context
from . import browser
from ...misc import audio
context = Context(
"netflix", func=browser.url_matches_func("https://www.netflix.com/.*")
)
context.keymap(
{"full screen": [lambda m: audio.set_volume(100), browser.send_to_page("f")]}
)
|
1631423 | import jax
from jax.config import config; config.update("jax_enable_x64", True)
import jax.numpy as jnp
from jax.experimental import loops
import psi4
from .energy_utils import nuclear_repulsion, partial_tei_transformation, tei_transformation, cartesian_product
from .hartree_fock import restricted_hartree_fock
def r... |
1631472 | from tests.common import TestCase
import torch
from torch.autograd import Variable
import torchvision.models
from dsnt.model import ResNetHumanPoseModel
class TestResNetHumanPoseModel(TestCase):
def test_truncate(self):
resnet = torchvision.models.resnet18()
model = ResNetHumanPoseModel(resnet,... |
1631496 | import discord
from discord.ext import commands
from discord.utils import get
import datetime
from discord import Member
class Joinlog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
usedinvite = Noneg
... |
1631511 | from __future__ import with_statement
import itertools
import functools
import logging
import os, sys, traceback
import threading
import time
log = logging.getLogger('util.primitives.synch')
def lock(f):
@functools.wraps(f)
def wrapper1(instance, *args, **kw):
if not hasattr(instance, '_l... |
1631538 | import datetime
import pytest
from eth_utils import to_wei
from web3.contract import Contract
@pytest.fixture
def release_agent(chain, team_multisig, token) -> Contract:
"""Create a simple release agent (useful for testing)."""
args = [token.address]
tx = {
"from": team_multisig
}
cont... |
1631649 | from torch._six import container_abcs
from itertools import repeat
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
__all__ = ['InducedNormLinear', 'InducedNormConv2d']
class InducedNormLinear(nn.Module):
def __init__(
self, in_features, out_fea... |
1631668 | from pyscalambda.formula import Formula
class Operator(Formula):
pass
class UnaryOperator(Operator):
def __init__(self, operator, value):
"""
:param operator: str
:param value: Formula
"""
super(UnaryOperator, self).__init__()
self.operator = operator
... |
1631694 | import unittest
from katas.kyu_6.dbftbs_djqifs import encryptor
class EncryptorTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(encryptor(13, ''), '')
def test_equals_2(self):
self.assertEqual(encryptor(13, 'Caesar Cipher'), 'Pnrfne Pvcure')
def test_equals_3(self):
... |
1631700 | from goopylib.objects.GraphicsObject import GraphicsObject
from goopylib.styles import STYLES, global_style
from goopylib.colours import Colour
from goopylib.util import GraphicsError
from tkinter import Text as tkText
from tkinter import WORD as tkWORD
from tkinter import END as tkEND
from tkinter import Frame as tkF... |
1631721 | import sys
from urlparse import urlparse
from urllib import unquote
def compare(a, b):
return (
a.scheme.lower() == b.scheme.lower()
and a.hostname == b.hostname
and (a.port or 80) == (b.port or 80)
and unquote(a.path) == unquote(b.path)
)
test_cases = open(sys.argv[1], "r")
... |
1631722 | from .core import *
from .flat_estimators import *
from .preprocessing import *
from .validation import *
from .verification import *
from .estimators import *
from .tests import NMME_IMD_ISMR
import warnings
from pathlib import Path
__version__ = "0.5.0"
__licence__ = "MIT"
__author__ = "<NAME> (<EMAIL>)"
|
1631734 | import unittest
from kafka.tools.protocol.requests import ArgumentError
from kafka.tools.protocol.requests.list_offset_v2 import ListOffsetV2Request
class ListOffsetV1RequestTest(unittest.TestCase):
def test_process_arguments(self):
val = ListOffsetV2Request.process_arguments(['-1', 'false', 'topicname',... |
1631744 | words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################')
file_name = 'test_doc.docx'
# Calls AcceptAllRevisionsOnline method for document in cloud.
request_document = open(file_name, 'rb')
request = asposewordscloud.models.requests.AcceptAllRevisionsOnlineRequest(document=req... |
1631848 | import warnings
from django.test.utils import get_warnings_state, restore_warnings_state
from regressiontests.comment_tests.tests import CommentTestCase
class CommentFeedTests(CommentTestCase):
urls = 'regressiontests.comment_tests.urls'
feed_url = '/rss/comments/'
def test_feed(self):
response... |
1631860 | import dash_core_components as dcc
import dash_html_components as html
from app.dashes.components import areasDropdown, collapseExpand, enterprisesDropdown, sitesDropdown, tagsDropdown, timeRangePicker
layout = html.Div(children =
[
html.Div(id = "loadingDiv", className = "text-center", children = [html.Img(src = ... |
1631864 | from __future__ import division
import os,time,cv2
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
def lrelu(x):
return tf.maximum(x*0.2,x)
def identity_initializer():
def _initializer(shape, dtype=tf.float32, partition_info=None):
array = np.zeros(shape, dtype=float)... |
1631869 | import logging
import subprocess
from typing import Mapping
from .action import Action
logger = logging.getLogger(__name__)
class Shell(Action):
"""
Executes a shell command
:param str cmd: The command to execute.
Example:
- (macOS) Open all pdfs on your desktop:
.. code-block:: ya... |
1631871 | import numpy, os
import tensorflow as tf
from phi.tf.util import *
from phi.control.sequences import *
from phi.control.nets.force.forcenets import forcenet2d_3x_16 as forcenet
def ik(initial_density, target_density, trainable=False):
# conv = conv_function("model", "model/smokeik/sim_000301/checkpoint_00014802/... |
1631878 | import os
class Registry:
def __init__(self, host, username, password):
self.cmd = 'net rpc registry -S %s -U "%s%%%s"' % (host, username, password)
def call(self, cmd, *args):
args = '"' + '" "'.join(args) + '"'
shell = ' '.join((self.cmd, cmd, args))
n, out, err = os.popen3(s... |
1631893 | import logging
from django.utils import timezone
from elasticsearch import Elasticsearch, NotFoundError, RequestError
from zentral.core.exceptions import ImproperlyConfigured
from .base import BaseExporter
logger = logging.getLogger("zentral.contrib.inventory.exporters.es_machine_snapshots")
MAX_EXPORTS_COUNT = 3
ES... |
1631919 | import glob
from pyPanair.preprocess import read_wgs
if __name__ == '__main__':
print("converting LaWGS to stl")
wgs_list = glob.glob("*.wgs")
for w in wgs_list:
wgs = read_wgs(w)
wgs.create_stl(w.replace(".wgs", ".stl"))
print("success!") |
1631959 | import sys
import fileinput
import argparse
import time
import itertools
import pickle
import random
import codecs
from collections import defaultdict
from sklearn import svm
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction import DictVectorizer
from scipy.sparse import coo_ma... |
1631969 | from enum import Enum
import re
try:
import requests
except ImportError:
raise RuntimeError('Requests is required for hibp.')
try:
import gevent
from gevent import monkey
from gevent.pool import Pool
except ImportError:
raise RuntimeError('Gevent is required for hibp.')
monkey.patch_all(threa... |
1631972 | from conans import CMake, ConanFile, tools
from conans.errors import ConanInvalidConfiguration
from glob import glob
import os
class SshtConan(ConanFile):
name = "ssht"
license = "GPL-3.0-or-later"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/astro-informatics... |
1631995 | from notebook_test_case import NotebooksTestCase
import unittest
class RunMostNotebooksTestCase(NotebooksTestCase):
TEST_PATHS = ['./notebooks/',
'./notebooks/solr/tmdb',
'./notebooks/elasticsearch/tmdb',
'./notebooks/elasticsearch/osc-blog']
IGNORED_NBS ... |
1632005 | from mrq.task import Task
from mrq.context import log
import sys
PY3 = sys.version_info > (3,)
class Simple(Task):
def run(self, params):
# Some systems may be configured like this.
if not PY3 and params.get("utf8_sys_stdout"):
import codecs
import sys
UTF8Wr... |
1632023 | from opts.viz_opts import VizOpts
from data_process.coco import CocoDataSet
from visualization.visualize import visualize_masks, visualize_keypoints, visualize_heatmap, visualize_paf
from data_process.coco_process_utils import BODY_PARTS
if __name__ == '__main__':
opts = VizOpts().parse()
for split in ['train'... |
1632120 | import sys
import numpy as np
import theano.tensor as T
from keras.layers import Input, Conv2D, Activation, Lambda, UpSampling2D, merge
from keras.models import Model
from keras.engine.topology import Layer
from neural_style.utils import floatX
class InstanceNormalization(Layer):
def __init__(self, **kwargs):
... |
1632127 | import matplotlib.pyplot as plot
import matplotlib.dates as md
from matplotlib.dates import date2num
import datetime
# from pylab import *
from numpy import polyfit
import numpy as np
f = open("deviations.csv")
values = []
timestamps = []
for (i, line) in enumerate(f):
if i >= 1:
lineArray = line.split(",... |
1632184 | from unittest import TestCase
from propara.evaluation.metrics import Metrics
class TestMetrics(TestCase):
def setUp(self):
self.metrics = Metrics()
self.metrics.tp_increment(1)
self.metrics.fp_increment(1)
self.metrics.tp_increment(1)
self.metrics.fn_increment(1)
... |
1632186 | import random
import unittest
import numpy as np
import torch
from code_soup.common.utils import Seeding
class TestSeeding(unittest.TestCase):
"""Test the seed function."""
def test_seed(self):
"""Test that the seed is set."""
random.seed(42)
initial_state = random.getstate()
... |
1632212 | from sqlalchemy import schema
from sqlalchemy import util
class CompareTable:
def __init__(self, table):
self.table = table
def __eq__(self, other):
if self.table.name != other.name or self.table.schema != other.schema:
return False
for c1, c2 in util.zip_longest(self.tab... |
1632227 | import copy
import ctypes
import gfootball.env as football_env
import torch
import torch.multiprocessing as _mp
from a2c_ppo_acktr.base_factory import get_base
from a2c_ppo_acktr.model import Policy
from create_env import create_atari_mjc_env
from gym.spaces.discrete import Discrete
mp = _mp.get_context('spawn')
Valu... |
1632290 | import pytest
from lcs.agents.xncs import Backpropagation, Configuration, Classifier, Effect, ClassifiersList
from lcs.agents.xcs import Condition
class TestBackpropagation:
@pytest.fixture
def cfg(self):
return Configuration(lmc=2, lem=0.2, number_of_actions=4)
def test_init(self, cfg):
... |
1632295 | from tensor2struct.languages.dsl.common.errors import ParsingError, ExecutionError
from tensor2struct.languages.dsl.common.util import START_SYMBOL, END_SYMBOL
|
1632379 | from pyvr.renderer import Renderer
from pyvr.actors import VolumeActor
from pyvr.actors import SliceActor
from pyvr.data.volume import load_volume
from pyvr.utils.video import write_video
if __name__ == '__main__':
volume_file = 'original-image.mhd'
volume = load_volume(volume_file)
clim = (-150, 350)
... |
1632396 | import torchvision.models as models
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append('../PNAS/')
from PNASnet import *
from genotypes import PNASNet
class PNASModel(nn.Module):
def __init__(self, num_channels=3, train_enc=False, load_weight=1):
super(PNASModel,... |
1632427 | from typing import Dict
import torch
from torch.optim.optimizer import Optimizer
from pytorch_optimizer.base_optimizer import BaseOptimizer
from pytorch_optimizer.types import CLOSURE, DEFAULTS, PARAMETERS
class SAM(Optimizer, BaseOptimizer):
"""
Reference : https://github.com/davda54/sam
Example :
... |
1632456 | import numpy as np
import unittest
from partitura import EXAMPLE_MUSICXML
from partitura import load_musicxml
from partitura.musicanalysis import estimate_spelling
def compare_spelling(spelling, notes):
comparisons = np.zeros((len(spelling), 3))
for i, (n, s) in enumerate(zip(notes, spelling)):
compa... |
1632492 | from utils.registry import Registry
"""
Feature Extractor.
"""
# Backbone
BACKBONES = Registry()
# FPN
FPN_BODY = Registry()
"""
ROI Head.
"""
# Box Head
ROI_CLS_HEADS = Registry()
ROI_CLS_OUTPUTS = Registry()
ROI_BOX_HEADS = Registry()
ROI_BOX_OUTPUTS = Registry()
# OPLD Head
ROI_OPLD_HEADS = Registry()
ROI_OPLD_... |
1632516 | import signal
import threading
import sys
def write(msg):
msg = msg + '\n' if not msg.endswith('\n') else msg
sys.stderr.write(msg)
sys.stderr.flush()
class TaskletMetrics(object):
'''This class allows a Tasklet to store any state that a Task may need to
have after the execution of its Tasklets.... |
1632530 | import os, sys, time, os.path, pyperclip, pyautogui, ctypes
from colorama import Fore
from selenium import webdriver
def autologin() :
os.system('cls' if os.name == 'nt' else 'clear')
autologintitle()
print(f"""{y}[{w}+{y}]{w} Enter the token of the account you want to connect to""")
entertoken... |
1632542 | import pandas as pd
from weedcoco.utils import get_task_types
EXPECTED_FIELDS = ["segmentation", "bounding box"]
class WeedCOCOStats:
def __init__(self, weedcoco):
self.annotations = self.compute_annotation_frame(weedcoco)
self.category_summary = self.compute_summary(
self.annotations... |
1632550 | from dataclasses import dataclass
from typing import Optional, List, Dict, Tuple, Union
from agate import Table
from dbt.contracts.connection import AdapterResponse
from dbt.adapters.base import AdapterConfig
from dbt.adapters.base.relation import BaseRelation
from dbt.adapters.spark.impl import SparkAdapter, LIST_SC... |
1632595 | import doctest
import os
import unittest
from pathlib import Path
from setuptools import find_packages, setup
requirements = ["black>=18.9b0", "loguru>=0.2.5"]
this_directory = Path(__file__).parent.resolve()
with open(Path(this_directory).joinpath("README.md"), encoding="utf-8") as readme_md:
README = readme_md... |
1632604 | from django.template import Library
from _1327.information_pages.models import InformationDocument
register = Library()
@register.filter
def can_user_see_author(document, user):
if document.show_author_to == InformationDocument.SHOW_AUTHOR_TO_EVERYONE:
return True
elif document.show_author_to == InformationDocu... |
1632625 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class AllTests(TranspileTestCase):
def test_all(self):
self.assertCodeExecution("print(all([None, True, False]))")
def test_all_true(self):
self.assertCodeExecution("print(all([1,True,3]))")
def test_all_false(self):
... |
1632674 | from collections import OrderedDict
import numpy as np
from ...data import Data
from ...instrument import Instrument
class Ice(Data):
r"""Loads ICE (NCNR) format ascii data file.
"""
def __init__(self):
super(Ice, self).__init__()
def load(self, filename, build_hkl=True, load_instrument=F... |
1632713 | import json
import botocore
from . import clients, resources, cloudwatch_logging
class ARN:
fields = "arn partition service region account_id resource".split()
_default_region, _default_account_id, _default_iam_username = None, None, None
def __init__(self, arn="arn:aws::::", **kwargs):
self.__di... |
1632780 | from __future__ import print_function
print("needsthis found")
print("data file: ", open('data/datafile.txt', 'r').read())
|
1632798 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from markitup.fields import MarkupField
@python_2_unicode_compatible
class Post(models.Model):
title = models.CharField(max_length=50)
body = MarkupField()
def __str__(self... |
1632858 | from collections import deque
from tests.entities import (DataClassIntImmutableDefault,
DataClassMutableDefaultDict,
DataClassMutableDefaultList, DataClassWithDeque,
DataClassWithDict, DataClassWithDictInt,
... |
1632877 | import FWCore.ParameterSet.Config as cms
from RecoEcal.EgammaClusterProducers.particleFlowSuperClusterECAL_cfi import *
particleFlowSuperClusterOOTECAL = particleFlowSuperClusterECAL.clone(
PFClusters = "particleFlowClusterOOTECAL",
ESAssociation = "particleFlowClusterOOTEC... |
1632884 | import dateutil.parser
from maestro_agent.services.maestro_api.run import (
Run,
RunApi,
RunStatus,
)
def test_maestro_run_get(mocker):
run_id = "1-2-3-4"
get_mock = mocker.patch(
"maestro_agent.services.maestro_api.MaestroApiClient.get",
)
RunApi.get(run_id)
get_mock.asser... |
1632903 | from typing import Dict, Any
from idewavecore.debug import Logger
from idewavecore.network import (
BaseServer,
ServerFactory,
)
from idewavecore.session import Storage
from .ProxyBuilder import ProxyBuilder
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021, Idewavecore'
cla... |
1633002 | import numpy as np
import torch
from pgbar import progress_bar
class RayS(object):
def __init__(self, model, epsilon=0.031, order=np.inf):
self.model = model
self.ord = order
self.epsilon = epsilon
self.sgn_t = None
self.d_t = None
self.x_final = None
self.q... |
1633009 | import gevent
import gevent.pool
import gevent.monkey
import requests
import pytest
import tests.fixtures as fxt
gevent.monkey.patch_socket(dns=True)
def test_catch_all_gevented_requests(vts_rec_on, movie_server, http_get):
"""Keep this test at the very end to avoid messing up with the rest of the
tests, si... |
1633011 | from django.conf.urls import patterns, url
from django.contrib.admindocs import views
urlpatterns = patterns('',
url('^$',
views.doc_index,
name='django-admindocs-docroot'
),
url('^bookmarklets/$',
views.bookmarklets,
name='django-admindocs-bookmarklets'
),
url('^tag... |
1633013 | from numpy import array
from pybimstab.astar import Astar
grid = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 0,... |
1633067 | import lldb
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbtest as lldbtest
import lldbsuite.test.lldbutil as lldbutil
import re
class TestCase(lldbtest.TestBase):
mydir = lldbtest.TestBase.compute_mydir(__file__)
@swiftTest
@skipIf(oslist=['windows', 'linux'])
def test(self):
... |
1633079 | from .alerts import Alerts
class ToolsNotifications:
def __init__(self, logger, ifttt_alerts):
self._logger = logger
self._ifttt_alerts = ifttt_alerts
self._alerts = Alerts(self._logger)
self._printer_was_printing_above_tool0_low = False # Variable used for tool0 cooling alerts
self._printer_alerted_reac... |
1633136 | import os
# Canidates for the builddir (relative to the path of this file),
# which we use to find some generated files:
builddir_canidates = [ "build", "b" ]
# Determine actual builddir
builddir = builddir_canidates[0]
for d in builddir_canidates:
if os.path.exists(d):
builddir = d
break
# This file is lo... |
1633155 | import io
import numpy as np
import tensorflow as tf
from hparams import hparams
from models import create_model
from util import audio, textinput
class Synthesizer:
def load(self, checkpoint_path, model_name='tacotron'):
print('Constructing model: %s' % model_name)
inputs = tf.placeholder(tf.int32, [1, Non... |
1633166 | from Adversary.utils import *
def test_flatten_unique():
l = [[1, 2], [1, 3, 4], [5]]
assert(flatten_unique(l) == [1, 2, 3, 4, 5])
def test_combinations_of_len():
l = [1, 2, 3]
assert(combinations_of_len(l, 2) == [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3)])
def test_fancy_titles():
cols = ['change... |
1633172 | import easypost
easypost.api_key = "API_KEY"
order = easypost.Order.create(
to_address={
"company": "Oakland Dmv Office",
"name": "Customer",
"street1": "5300 Claremont Ave",
"city": "Oakland",
"state": "CA",
"zip": "94618",
"country": "US",
"phone":... |
1633216 | def test_else_block():
a = 5
s = "blibli"
if s != "blabla":
print("ok")
'''TEST
els$
@0 else:
status: ok
'''
def test_import_keyword():
import os
'''TEST
imp$
@0 `import `
status: ok
'''
def test_no_import_as():
import os
'''TEST
import n... |
1633232 | from .load_files_from_local_data import load_files_from_local_data
def load_frontend_files_from_local_data(who_is_asking_file):
return load_files_from_local_data(who_is_asking_file, dir_type="frontend")
|
1633262 | import asyncio
import time
import traceback
from src import database, amino_async, configs
from src.utils import service_align, logger, file_logger
DEVICES = open(configs.DEVICES_PATH, "r").readlines()
async def login(account: tuple):
client = amino_async.Client()
email = account[0]
password = account[... |
1633286 | from datetime import datetime
import os
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.subdag_operator import SubDagOperator
from dsbox.examples.tree_disease_usecase.ml.feature_engineering import join_dataframes
from dsbox.examples.tree_disease_usecase.ml.model... |
1633348 | import torch
# from image_synthesis.data.base_dataset import ConcatDatasetWithIndex as ConcatDataset
from torch.utils.data import ConcatDataset
from image_synthesis.utils.misc import instantiate_from_config
from image_synthesis.distributed.distributed import is_distributed
def build_dataloader(config, args=None, retur... |
1633358 | import os.path
import json
from core import constants, log, json_util
from core.validators import validator_util
def validate(file_path, template):
log.log_subline_bold(f"Reading source file : '{file_path}'.")
source_data = json_util.read_json_data(file_path)
for language in constants.languages.values():
... |
1633370 | from setuptools import setup, find_packages, Command
version = __import__('pytest_sftpserver').get_version()
class Test(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import subprocess
raise SystemExit... |
1633410 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_databases(host):
with host.sudo():
# test if databases exist
databases = host.run('mysql -u root -e "show database... |
1633431 | class Solution:
digit_char_map = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z'],
}
def letterCombinati... |
1633439 | from setuptools import setup, find_packages
setup(
name='pyAHP',
version='0.1.2',
packages=find_packages(),
install_requires=[
'numpy>=1.14.0',
'scipy>=1.0.0'
],
author='<NAME>',
author_email='<EMAIL>',
description='Analytic Hierarchy Process solver',
license='MIT',
... |
1633452 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, start):
self.start = start
def detect_middle(self):
if self.start.next is None:
return self.start
i = self.start
j = self.start
... |
1633453 | import re
import os
import subprocess
from functools import lru_cache
from typing import Dict, List
import pandas as pd
from helpers import (
NOW,
RemoteCommand,
Settings,
create_settings,
nix_build,
spawn,
flamegraph_env,
read_stats,
write_stats,
scone_env
)
from network import... |
1633460 | import os
import textwrap
from django.utils.translation import ugettext_lazy as _
from orchestra.contrib.orchestration import ServiceController, replace
from . import WebAppServiceMixin
from .. import settings
class uWSGIPythonController(WebAppServiceMixin, ServiceController):
"""
<a href="http://uwsgi-doc... |
1633495 | import win32api, win32con, win32security, ntsecuritycon
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_TCB_NAME),
win32con.SE_PRIVILEGE_ENABLE... |
1633504 | from .vit_tiny_patch16_224 import model
model.patch_size = 14
model.embed_dim = 1408
model.mlp_ratio = 48 / 11
model.depth = 40
model.num_heads = 16
|
1633509 | def f_linear(x):
y = x
z = y
return z
def one_branch(x):
if x:
return 1
else:
return 2
def two_branch(x, y):
if x:
y += 1
else:
y += 2
if y:
return 1
else:
return 2
def nested(x, y):
if x:
if y:
return 0
... |
1633524 | from django.http import Http404
from django.shortcuts import render
from project_first_app.models import Owner, Car, DriverLicense, Ownership
def owner_detail(request, owner_id):
try:
p = Owner.objects.get(pk=owner_id)
except Owner.DoesNotExist:
raise Http404("Owner does not exist")
return... |
1633565 | from dataclasses import dataclass
from unittest import TestCase
from dataclass_factory import Factory, Schema
@dataclass
class Data:
a: str = ""
b: str = ""
c_: str = ""
_d: str = ""
class TestFactory(TestCase):
def test_only_mapping(self):
factory = Factory(
schemas={
... |
1633577 | import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.optim import lr_scheduler
import numpy as np
import contextlib
import math
from medseg.models.segmentation_models.... |
1633614 | class GeocodioError(Exception):
"""General but unknown error from Geocodio"""
pass
class GeocodioAuthError(GeocodioError):
"""HTTP 403 Access Forbidden, likely due to bad API key"""
pass
class GeocodioDataError(GeocodioError):
"""HTTP 422 Unprocessable Entity, likely poorly formed address"""
... |
1633628 | from .utils import NoCheckpointSetError
from .throttled_request import ThrottledRequestAlreadyFinished
from .throttler import \
ThrottlerStatusError, \
FullRequestsPoolError
__all__ = ["NoCheckpointSetError",
"ThrottledRequestAlreadyFinished",
"ThrottlerStatusError",
"FullReque... |
1633635 | import json
import os
import glob
TRANSLATIONS = {}
FALLBACK_LOCALE_CODE = 'en-US'
def I18n(app):
"""Initializes the I18n engine.
:param app: An object that answers to 'add_template_filter(fn)'.
"""
if TRANSLATIONS:
return
locales_path = os.path.join(
os.path.dirname(__file__)... |
1633641 | import os
import tornado.ioloop
import tornado.httpserver
import tornado.escape
from tornado.options import define, options
from application.server import Application
# Define command line arguments
define("port", default=3000, help="run on the given port", type=int)
def main():
# tornado.options.parse_command_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.