id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3285739 | import lib, os, argparse
class Handler(lib.BaseHandler):
def __init__(self, args):
super(Handler, self).__init__(args)
if (not self.args.cert_path or not self.args.key_path):
if not self.args.host:
self.key = "{}/key.pem".format(self.args.cert_dir)
self.... |
3285740 | import os.path
import pandas as pd
from framework.utils import *
def load_etf_metadata(fname="../data/etfs.msgpack"):
global etf_metadata_df
etf_metadata_df = None
if not os.path.isfile(fname):
fname = "data/etfs.msgpack"
if not os.path.isfile(fname):
warn("etfs.msgpack not foun... |
3285750 | import socks
import socket
import requests
import threading
import random
import ssl
import time
from colorama import Fore
print(Fore.RED + """
____ ______ ____ _____ ________ ___ __ __
/ __ \__ __/ ____/____/ __ \____ / ___/____ /_ __/ /_/ | _____/ //_/
... |
3285756 | from PuzzleLib.Containers.Container import Container
from PuzzleLib.Containers.Graph import Graph
from PuzzleLib.Containers.Parallel import Parallel
from PuzzleLib.Containers.Sequential import Sequential
|
3285805 | import sys
from pathlib import Path
import pytest
import robocop.exceptions
@pytest.fixture
def test_data():
return Path(__file__).parent.parent / "test_data"
class TestExternalRules:
def test_loading_external_rule(self, robocop_pre_load, test_data): # noqa
robocop_pre_load.config.ext_rules = {st... |
3285816 | from zipline.pipeline.common import SID_FIELD_NAME, TS_FIELD_NAME
from zipline.pipeline.loaders.blaze.core import ffill_query_in_range
from zipline.pipeline.loaders.utils import (
normalize_data_query_bounds,
normalize_timestamp_to_query_time,
)
def load_raw_data(assets,
dates,
... |
3285817 | import skia
import pytest
@pytest.fixture
def recorder():
return skia.PictureRecorder()
def test_Picture_init():
assert isinstance(skia.Picture(skia.Rect(100, 100)), skia.Picture)
def test_Picture_playback(picture, canvas):
picture.playback(canvas)
def test_Picture_cullRect(picture):
assert isin... |
3285837 | import json
from parameters import Params
def init(train=1):
#global settings
if train==1:
with open("configNetwork.json", 'r') as f:
settings = json.load(f)
#print(settings)
if train==0:
with open("configNetwork_eval.json", 'r') as f:
settings = json.load(f)
... |
3285846 | import typing
from os.path import basename, dirname, isdir, isfile
from pathlib import Path
from qtpy.QtWidgets import QFileDialog
from PartSegCore.io_utils import LoadBase
if typing.TYPE_CHECKING: # pragma: no cover
from PartSeg.common_backend.base_settings import BaseSettings
class LoadProperty(typing.Named... |
3285865 | from danspeech.deepspeech.model import DeepSpeech
from danspeech.utils.data_utils import get_model
MODEL_PACKAGE = "https://github.com/danspeech/danspeech/releases/download/v0.01-alpha/GPUStreamingRNN.pth"
def GPUStreamingRNN(cache_dir=None):
"""
DanSpeech model with lookahead, which works as a real-time str... |
3285921 | import pp
from pp.component import Component
from typing import Tuple
@pp.autoname
def mmi2x2(
wg_width: float = 0.5,
width_taper: float = 0.95,
length_taper: float = 10.0,
length_mmi: float = 15.45,
width_mmi: float = 2.1,
gap_mmi: float = 0.2,
layer: Tuple[int, int] = pp.LAYER.WG,
) -> C... |
3285951 | from __future__ import print_function
from Plugins.Extensions.Widgets.Widget import Widget
from Components.Label import Label
class TestWidget(Widget):
def __init__(self, session):
Widget.__init__(self, session, name="Static Text Widget", description="Example of a simple Widget with static text", version=... |
3285976 | import string
SAFE_CHAR_VALUES = {
*"[]()^ #%&!@+={}'`~-_",
*string.ascii_letters,
*string.digits,
}
def escape_name(name: str, escape="_"):
return "".join(char if char in SAFE_CHAR_VALUES else escape
for char in name)
def format_name(fmt: str, data: dict):
transformed_data = {
... |
3285991 | import boto3
import json
import click
import jmespath
import time
# Updates needed- IPV6, an IP range that includes port 22
# Also add fix in case requested IP range is already in there
@click.command()
@click.option('--access', help='AWS Access Key. Otherwise will use the standard credentials path for the AWS CLI.')
... |
3286023 | def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
substring = ""
previous = ""
length = 0
for char in s:
if char not in substring:
print(char, 'not in ', substring)
substring += char
length = len(substring) if length < len(subst... |
3286037 | import sys, os, socket
import crcmod
import struct
from pwnlib.elf import ELF
def makeMsg(msgId, cookie, parts):
body = "".join(map(lambda x: chr(len(x)+1) + x, parts))
base = cookie + struct.pack(">H", msgId) + body
cs = crc8(base)
msg = "\x0A\x00" + chr(len(base)) + chr(cs) + base
return chr... |
3286055 | import tensorflow as tf
from .registry import register
from .utils import HParams
@register
def default():
return HParams(
model=None,
sys=None,
env=None,
agent=None,
reward_augmentation=None,
lr={"lr": 0.001},
lr_decay={"lr": "no_decay"},
output_dir=None,
memo... |
3286067 | import numpy as np
from scipy.integrate import ode
from scipy.special import binom
from .utils import differentiate, integrate
def pool_data(Xin, poly_order=2, use_sine=False, include_constant=True, varname='x'):
if poly_order > 5:
poly_order = 5
if Xin.ndim == 1:
T = 1
n = Xin.size
... |
3286071 | from idaapi import PluginForm
from PySide import QtGui, QtCore
class MyPluginFormClass(PluginForm):
def OnCreate(self, form):
"""
Called when the plugin form is created
"""
# Get parent widget
self.parent = self.FormToPySideWidget(form)
self.PopulateForm()
def... |
3286089 | from awrams.utils.messaging.robust import PollingChild, SharedMemClient, Chunk, to_chunks
import netCDF4 as nc
#from awra import db_open_with
#+++ Need to use NCD (as opposed to h5py) when writing to LSD compressed datasets
db_opener = nc.Dataset#db_open_with()
FILL_VALUE = -999.
class MultifileChunkWriter(PollingCh... |
3286103 | import bridge
import requests_mock
BRIDGE_IP = '127.0.0.1'
USERNAME = 'fake'
LIGHTS = {u'1': {u'name': u'fake',
u'state': {u'alert': u'none',
u'bri': 254,
u'hue': 17738,
u'on': True,
u'sat'... |
3286195 | import os
import sys
import time
import json
import logging
import threading
import multiprocessing as mp
from ..utils import save, load, AutoTorchEarlyStop
import distributed
from distributed import Queue, Variable
from distributed.comm.core import CommClosedError
logger = logging.getLogger(__name__)
__all__ = ['Dis... |
3286228 | from Data.WorldPosData import *
from Data.SlotObjectData import *
class InvSwapPacket:
def __init__(self):
self.type = "INVSWAP"
self.time = 0
self.pos = WorldPosData()
self.slotObject1 = SlotObjectData()
self.slotObject2 = SlotObjectData()
def write(self, wr... |
3286235 | import stk
import numpy as np
def test_put_caching(mongo_client):
database_name = '_test_put_caching'
mongo_client.drop_database(database_name)
database = stk.ConstructedMoleculeMongoDb(
mongo_client=mongo_client,
database=database_name,
)
molecule = stk.BuildingBlock('BrCCCBr', [... |
3286251 | import wx
class PublishPhotoOptionsDialog( wx.Dialog ):
def __init__( self, parent, webPublish, id=wx.ID_ANY ):
super().__init__( parent, id, title='CrossMgr Video Photo Publish' )
sizer = wx.BoxSizer( wx.VERTICAL )
explainText = []
explainText.append( "Write Photos to a folder." )
if webPublish:
e... |
3286315 | from .common import Common
class Production(Common):
# Site
# https://docs.djangoproject.com/en/2.0/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
|
3286319 | from __future__ import absolute_import
import argparse
import logging
import os
import sys
from .. import io
LOG = logging.getLogger()
def run(result_fn_list_fn, gathered_fn):
thatdir = os.path.dirname(result_fn_list_fn)
thisdir = os.path.dirname(gathered_fn)
result_fn_list = io.deserialize(result_fn_li... |
3286339 | from django.shortcuts import render
from . import models
from . import serializers
from rest_framework import viewsets, status, mixins, generics
# Create your views here.
class EventViewSet(generics.ListAPIView):
"""Manage Events in the database"""
serializer_class = serializers.EventSerializer
queryset... |
3286343 | description = 'Setup for polarization with He cells'
group = 'lowlevel'
includes = ['detector']
sysconfig = dict(
datasinks = ['hepolsink'],
)
devices = dict(
hepolsink = device('nicos_mlz.poli.devices.he3cell.HePolSink',
description = 'Sink that saves monitor ratio for '
'polarization calcu... |
3286364 | import os.path
import sys
from itertools import tee
from pathlib import Path
from zipfile import ZipFile
import logging
import boto3
import click
from loguru import logger
from rich.console import Console
from smart_open import open
from ._core import load_test_label, load_test, \
load_train, CORPUS_SIZE
console... |
3286376 | from django.template.loader import get_template
from django.template import Context
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def generate_message_from_template(template, context):
context["STATIC_URL"] = settings.STATIC_URL
# Mandrill is set up to inline the CSS and genera... |
3286419 | import numpy as np
from opticalflow.core.data_aug import RadialDistortion
def __build_distortion(method: str, **kwargs):
if method == 'radial':
if not kwargs:
kwargs = {'ks': [0, 1e-5, 0, 1e-14, 0, 1e-15]}
distortion = RadialDistortion(**kwargs)
else:
raise NotImplementedE... |
3286421 | from setuptools import setup
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return [line for line in lineiter if line and not line.startswith("#")]
setup(
name='deep-adots',
author='<NAME>, <NAME>, <NA... |
3286453 | from typing import Dict, Union
from .reference import Reference
from .response import Response
Responses = Dict[str, Union[Response, Reference]]
"""
A container for the expected responses of an operation.
The container maps a HTTP response code to the expected response.
The documentation is not necessarily expected ... |
3286458 | import math
import torch
import torch.nn as nn
from collections import OrderedDict
from torchvision.models.resnet import BasicBlock
from .base import Backbone
class SpatialCrossMapLRN(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, k=1, ACROSS_CHANNELS=True):
super(SpatialCrossMapLRN, s... |
3286472 | import pytest
import torch
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmcls.models.backbones import ResNet_CIFAR
def check_norm_state(modules, train_state):
"""Check if norm layer is in correct train state."""
for mod in modules:
if isinstance(mod, _BatchNorm):
if mod.training... |
3286482 | import os
import json
import pickle
import torch
from pytorch_pretrained_bert import BertTokenizer
from collections import defaultdict
### this file is to convert the raw woz data into the format required for prepross.py
bert=True
bert_type='bert-large-uncased'
tokenizer=BertTokenizer.from_pretrained(bert_type)
def _t... |
3286485 | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import *
generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter",
pythiaPylistVerbosity = cms.untracked.int32(0),
pythiaHepMCVerbosity = cm... |
3286506 | from enforce_typing import enforce_types
import pytest
from util.mathutil import * # pylint: disable=wildcard-import
@enforce_types
def testIsNumber():
for x in [-2, 0, 2, 20000, -2.1, -2.0, 0.0, 2.0, 2.1, 2e6]:
assert isNumber(x)
for x in [[], [1, 2], {}, {1: 2, 2: 3}, None, "", "foo"]:
a... |
3286532 | import this
from tkinter import *
from tkinter import messagebox
rot13 = str.maketrans(
"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm",
)
def main_window(root: Tk):
frame = Frame(root)
frame.pack()
zen_button = Button(frame, text="P... |
3286541 | import boto3
import json
import base64
import os
kms = boto3.client('kms')
bad_request = {
'statusCode': 400,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({'error': 'Invalid argument'})
}
def encrypt(key, message):
'''encrypt leverages KMS encrypt and base64-encod... |
3286546 | from biothings.tests.web import BiothingsDataTest
class TestAnnotationGET(BiothingsDataTest):
host = 'mygene.info'
prefix = 'v3'
def test_101(self):
res = self.request('gene/1017').json()
attr_li = [
'HGNC', 'MIM', '_id', 'accession', 'alias',
'ec', 'ensembl', 'e... |
3286552 | import tensorflow as tf
import h5py
import numpy as np
# Read
dfd_dataset = h5py.File('datasets/dataset.hdf5', "r")
train_data = np.array(dfd_dataset["train_data"][:], dtype = np.float32)
train_label = np.array(dfd_dataset["train_label"][:])
test_data = np.array(dfd_dataset["test_data"][:], dtype = np.float32)
test_... |
3286585 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
import tensorflow as tf
from cleverhans.devtools.checks import CleverHansTest
from runner import RunnerMultiGPU
class TestRunnerMul... |
3286588 | import unittest
import array
import sys
import jpyutil
jpyutil.init_jvm(jvm_maxmem='512M', jvm_classpath=['target/test-classes'])
import jpy
try:
import numpy as np
except:
np = None
def annotate_fixture_methods(type, method):
# print('annotate_fixture_methods: type =', type, ', method =', method.name... |
3286596 | def on(self, event, handler):
self._events = self._events
handlers = self._events[event] = self._events[event] if event in self._events else []
handlers.append(handler)
def off(self, event, handler):
handlers = self._events[event] = self._events[event] if event in self._events else []
handlers.rem... |
3286616 | import sys
sys.path.append('../../common')
from env_indigo import *
indigo = Indigo()
print("*** Molecules ***")
def handleMolecule(mol):
print('%0.3f %0.3f %0.3f %s %s' % (
mol.molecularWeight(), mol.monoisotopicMass(), mol.mostAbundantMass(), mol.grossFormula(), mol.massComposition()))
def handleMol... |
3286656 | import sys
from SteamworksParser import steamworksparser
import interfaces
import constants
import enums
import structs
import typedefs
import output_dummy_files
def main():
if len(sys.argv) == 2:
path = sys.argv[1]
elif len(sys.argv) == 1:
path = "steam"
else:
print("Usage: Steamwo... |
3286674 | import os
import nipype.interfaces.utility as util
from CPAC.utils.interfaces.function import Function
from CPAC.pipeline import nipype_pipeline_engine as pe
def run_surface(post_freesurfer_folder,
freesurfer_folder,
subject,
t1w_restore_image,
atlas_spa... |
3286678 | import os
import pickle
import warnings
import platform
import tempfile
import numpy as np
from pytransform3d.rotations import (
q_id, active_matrix_from_intrinsic_euler_xyz, random_quaternion)
from pytransform3d.transformations import (
random_transform, invert_transform, concat, transform_from_pq,
transfo... |
3286686 | from __future__ import absolute_import
from __future__ import print_function
import os
import json
import unittest
from pybufrkit.tables import TableGroupCacheManager
from pybufrkit.templatecompiler import TemplateCompiler, loads_compiled_template
from pybufrkit.decoder import Decoder
BASE_DIR = os.path.dirname(__fil... |
3286688 | import logging
import random
import time
from kazoo.exceptions import (
ConnectionClosedError,
ConnectionLoss,
KazooException,
OperationTimeoutError,
SessionExpiredError,
)
log = logging.getLogger(__name__)
class ForceRetryError(Exception):
"""Raised when some recipe logic wants to force a ... |
3286707 | from common import *
test_x = np.linspace(0, 2 * np.pi)
x2 = np.atleast_2d(2 + 2 * np.random.rand(n)).T
y2 = np.cos(x) + 0.1 * np.random.randn(n, 1)
gp.add(x2, y2)
pred = gp.predict(np.atleast_2d(test_x).T, what=('mean', 'mse'))
mean = np.squeeze(pred['mean']) # There is only one output dimension.
mse = pred['mse']... |
3286713 | import numpy as np
import onnx
import pytest
import torch
from torch import nn
from onnx.backend.test.case.node.pad import pad_impl
from onnx2pytorch.helpers import to_onnx
from onnx2pytorch.utils import (
is_constant,
get_ops_names,
get_selection,
assign_values_to_dim,
get_activation_value,
ex... |
3286718 | from contextlib import ExitStack
from os import path
from tarfile import TarFile
from tempfile import TemporaryDirectory
from django.test import TestCase
from django_archive import archivers
class BaseTestCase(TestCase):
"""
Base class for tests
"""
def setUp(self):
"""
Initialize th... |
3286738 | import os
import pathlib
from functools import partial
from napari.utils.translations import trans
from napari_plugin_engine import napari_hook_implementation
CELLPOSE_DATA = [
('rgb_3D.tif', trans._('Cells (3D+2Ch)')),
('rgb_2D.png', trans._('Cells 2D')),
]
def _load_cellpose_data(image_name, dname):
# ... |
3286740 | import sys
import time
import amanobot
from amanobot.loop import MessageLoop
from amanobot.delegate import per_inline_from_id, create_open, pave_event_space
"""
$ python3 inline.py <token>
It demonstrates answering inline query and getting chosen inline results.
"""
class InlineHandler(amanobot.helper.InlineUserHand... |
3286750 | import os
import sys
import copy
import logging
from checker import *
from .ofp import register_ofp_creators
from .ofp import OfpBase
# YAML:
# role_request:
# role: 0x0
# generation_id: 0
SCE_ROLE_REQUEST = "role_request"
@register_ofp_creators(SCE_ROLE_REQUEST)
class OfpRoleRequestCreator(OfpBase):
@cla... |
3286763 | import datetime
import json
from app import db
from app.lib.models.webpush import WebPushSubscriptionModel, WebPushLogModel
from pywebpush import webpush, WebPushException
class WebPushManager:
def __init__(self, vapid_private, admin_email, icon):
self.vapid_private = vapid_private
self.admin_emai... |
3286783 | movie = {
'title' : 'Life of Brian',
'year' : 1979,
'cast' : ['John','Eric','Michael','George','Terry']
}
print(movie['title']) #Life of Brian
#print(movie['budget']) #KeyError: 'budget'
print(movie.get('budget')) #None
print(movie.get('budget','not found')) #not found ---default value
movie['title'] = 'T... |
3286802 | import unittest
from cert_verifier import verifier, StepStatus
# Final result is last position in results array
VERIFICATION_RESULT_INDEX = -1
# second to last
AUTHENTICITY_RESULT_INDEX = -2
# revocation 3rd to last
REVOCATION_RESULT_INDEX = -3
# integrity is first check
INTEGRITY_RESULT_INDEX = 0
class TestVerify(u... |
3286846 | import safe_grid_agents.common as common
import safe_grid_agents.parsing as parsing
import safe_grid_agents.ssrl as ssrl
|
3286863 | import numpy as np
import theano as th
import theano.tensor as tt
from .ctc import CTCLayer
from . import layers
from . import updates
class NeuralNet():
def __init__(self, n_dims, n_classes,
mid_layer, mid_layer_args,
use_log_space=True,
optimizer='sgd', optimiz... |
3286900 | import json
import sys
import ethereum.tools.new_statetest_utils as new_statetest_utils
import ethereum.tools.testutils as testutils
from ethereum.slogging import get_logger, configure_logging
logger = get_logger()
# customize VM log output to your needs
# hint: use 'py.test' with the '-s' option to dump logs to the c... |
3286933 | from typing import Callable
from typing import Dict
from typing import List
from cleo.commands.command import Command
from ..exceptions import CommandNotFoundException
from .command_loader import CommandLoader
class FactoryCommandLoader(CommandLoader):
"""
A simple command loader using factories to instanti... |
3286967 | import pytest
import raccoon as rc
from raccoon.utils import assert_frame_equal
try:
# noinspection PyUnresolvedReferences
from blist import blist
except ImportError:
pytest.skip("blist is not installed, skipping tests.", allow_module_level=True)
def test_use_blist():
def check_blist():
asse... |
3286973 | import abc
from collections import OrderedDict
import numpy as np
from gym.spaces import Box
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.envs.wrappers import ProxyEnv
from rlkit.core.serializable import Serializable
from rlkit.core import logger as default_logger
class MultitaskEnv(object,... |
3287038 | LICENSES = {
"AAL": "AAL",
"AFL-1.2": "AFL-1.2",
"AFL-2.0": "AFL-2.0",
"AFL-2.1": "AFL-2.1",
"AFL-3.0": "AFL-3.0",
"AGPL-3.0": "AGPL-3.0",
"ANTLR-PD": "ANTLR-PD",
"APL-1.0": "APL-1.0",
"APL2": "Apache-2.0",
"APSL-1.0": "APSL-1.0",
"APSL-1.1": "APSL-1.1",
"APSL-1.2": "APSL... |
3287051 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from cats.models import Breed, Cat
from cats.forms impor... |
3287087 | from .__head__ import *
class MixturePol(BasePol):
def __init__(self, domain, pol_list, mixing_prob):
self.name = "mixture"
self.domain = domain
self.policies = [pol(domain) for pol in pol_list]
self.mixing = torch.distributions.categorical.Categorical(probs=mixing_prob)
def... |
3287096 | from thing.esi import ESI
from thing.models.esitoken import ESIToken
from thing.tasks import ESI_CharacterInfo
token = ESIToken.objects.get(name="Capri Sun <PASSWORD>")
|
3287099 | import sys
import os
import glob
import tarfile
import shutil
import h5py
import dateutil.parser
import datetime
import time
#logging
import logging
logger = logging.getLogger('poretools')
### Some notes on nanopore FAST5 file format:
### start_time used to be represented in seconds, when stored in the /Analyses subd... |
3287102 | from django.conf import settings
from django.db import models
from django.db.models import Q
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext, gettext_lazy as _
from feincms import translations
from feincms.... |
3287104 | from dataclasses import fields
from typing import Any, Iterator, Tuple
from . import ast
def iter_dataclass_fields(node: ast._Node) -> Iterator[Tuple[str, Any]]:
"""
Loops over all fields of the given node, yielding the field's name and
the current value.
Yields:
Tuples of ``(fieldname, valu... |
3287176 | from typing import Optional
import numpy as np
import pandas as pd
from tqdm import tqdm
from ..evaluators import UserwiseEvaluator
from .BaseTrainer import BaseTrainer
class MFTrainer(BaseTrainer):
def fit(
self,
n_batch: int = 500,
n_epoch: int = 10,
valid_evaluator: Optional[U... |
3287194 | from functools import partial
from sklearn.metrics import f1_score
from torch import nn
from transformers import AutoModel
from emmental.scorer import Scorer
from emmental.task import EmmentalTask
criterion = nn.BCEWithLogitsLoss()
class FeatureExtractor(nn.Module):
def __init__(self, feature_extractor):
... |
3287198 | import json
import logging
import os
import pickle
import numpy as np
import tensorflow.lite as tfl
from bert_serving.client import BertClient
from deeppavlov.models.embedders.elmo_embedder import ELMoEmbedder
from gensim.models import KeyedVectors
from isanlp.annotation import Event, TaggedSpan
from scipy.optimize im... |
3287216 | def fibonacci(num):
num1 = 0
num2 = 1
series = 0
i = 0
while i<=num:
print(series);
num1 = num2;
num2 = series;
series = num1 + num2;
i+= 1
# running function after taking user input
num = int(input('Enter how many numbers needed in Fibonacci series : '))
fibo... |
3287221 | import clingo
import logging
import sys
class GroundProgramPrinter:
def __init__(self):
# first collect rules
self.rules = []
self.weightrules = []
# then get atom mapping
# (clasp non-fact atoms)
self.int2atom = {} # int to str
def __output(self, what):
sys.stderr.write(what+'\n')
... |
3287246 | import os
import pymongo
from pymongo import MongoClient
import math
import random
class Db:
# Constructor
def __init__(self, **kwargs):
self.__host = kwargs.get("host",os.environ["MONGO_INITDB_HOSTNAME"])
self.__user = kwargs.get("headers", os.environ["MONGO_INITDB_ROOT_USERNAME"])
sel... |
3287259 | import pytest
from tests.tf_tests.unit import BaseUnitTest, TENSORFLOW_SUPPORTED, TENSORFLOW_AVAILABLE, fp
import numpy as np
class TestTFDataLoader(BaseUnitTest):
def test_pass(self, fp):
from deeplite.profiler.utils import Device
fp.expecting_common_inputs = False
with pytest.raises(TypeE... |
3287262 | import os,sys
# change the path accoring to the test folder in system
sys.path.append('/home/ubuntu/fogflow/test/UnitTest')
from datetime import datetime
import copy
import json
import requests
import time
import pytest
import data
import sys
# change it by broker ip and port
brokerIp="http://192.168.100.120:8070"
#... |
3287280 | from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector
from openrecipes.spiders.loveandoliveoil_spider import Loveandoliveoil_Mixin
class LoveandoliveoilfeedSpider(BaseSpider, Loveandoliveoil_Mixin):
name = "loveandoliveoil.feed"
allowed_domains = [... |
3287317 | import json
import time
import os
import zmq
class MessagePart:
__slots__ = 'content_type', 'compression_algorithm', 'compression_level', 'payload'
def __init__(self):
for f in ('content_type', 'compression_algorithm', 'payload'): setattr(self, f, '')
self.compression_level = 0
def parse(se... |
3287336 | import contextlib
import errno
import os
import signal
DEFAULT_TIMEOUT_MESSAGE = os.strerror(errno.ETIME)
class timeout(contextlib.ContextDecorator):
def __init__(
self,
seconds,
*,
timeout_message=DEFAULT_TIMEOUT_MESSAGE,
suppress_timeout_errors=False,
):
self.... |
3287347 | import argparse
import copy
import json
import os
from os.path import join
import sys
import matplotlib.image
from tqdm import tqdm
from PIL import Image
import torch
import torch.utils.data as data
import torchvision.utils as vutils
import torch.nn.functional as F
from torchvision import transforms
from AttGAN.data... |
3287430 | from os import path
import pytest
from anchore_engine.db.entities.policy_engine import (
CpeV2Vulnerability,
FeedGroupMetadata,
FeedMetadata,
FixedArtifact,
Vulnerability,
)
CURRENT_DIR = path.dirname(path.abspath(__file__))
FEEDS_DATA_PATH_PREFIX = path.join("data", "v1", "service", "feeds")
DB... |
3287442 | from flask import Flask, jsonify
import pyodbc
import os
app = Flask(__name__)
@app.errorhandler(Exception)
def exception_handler(exc):
return repr(exc)
class Database:
def listProductNames(self):
host = os.getenv('SQLSERVER_DATABASE_HOST')
databaseName = os.getenv('SQLSERVER_DATABASE_NAME')
... |
3287456 | import src.main.config
import os
import pandas as pd
import numpy as np
from pprint import pprint
def main(mode,classifier):
if classifier == "DT":
file_type = ".txt"
seperator = "\t"
column = 4
else:
file_type = ".csv"
seperator = ","
column = 6
data = pd.r... |
3287486 | from __future__ import division
from __future__ import print_function
import pickle
import numpy as np
import os.path as osp
import scipy.io as sio
def make_abs_path(f, d):
return osp.join(osp.dirname(osp.realpath(f)), d)
def get_suffix(filename):
"""a.jpg -> jpg"""
pos = filename.rfind('.')
if pos... |
3287500 | from os import path
from pydm import Display
class MacroAddition(Display):
def __init__(self, parent=None, args=None, macros=None):
super(MacroAddition, self).__init__(parent=parent, macros=macros)
self.ui.resultLabel.setText("{}".format(float(macros['a']) + float(macros['b'])))
def ui_fil... |
3287505 | from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path, re_path
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name='dummy.html')
urlpatterns = [
path('not-prefixed/', view, name='not-prefixed... |
3287511 | import os
import Annotations
from CGATReport.Tracker import *
from IntervalReport import *
##########################################################################
##########################################################################
##########################################################################
# ... |
3287574 | from __future__ import unicode_literals
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class FeedlyAccount(ProviderAccount):
def get_avatar_url(self):
return self.account.extra_data.get("picture")
def to_str... |
3287577 | import os
from docker.client import DockerClient
from docker.errors import NotFound
from docker.models.containers import Container
CONTAINER_NAME = "uwsgi-nginx-flask-test"
def get_logs(container: Container) -> str:
logs = container.logs()
return logs.decode("utf-8")
def get_nginx_config(container: Contai... |
3287580 | TX_TRUST_LOW = 1
TX_TRUST_MEDIUM = 6
TX_TRUST_HIGH = 30
class Unspent:
"""Represents an unspent transaction output (UTXO)."""
__slots__ = ('amount', 'confirmations', 'script', 'txid', 'txindex')
def __init__(self, amount, confirmations, script, txid, txindex):
self.amount = amount
self.co... |
3287585 | r"""
sine-Gordon Y-system plotter
This class builds the triangulations associated to sine-Gordon and reduced
sine-Gordon Y-systems as constructed in [NS]_.
AUTHORS:
- <NAME> (2014-07-18): initial version
EXAMPLES:
A reduced sine-Gordon example with 3 generations::
sage: Y = SineGordonYsystem('A',(6,4,3)); Y
... |
3287623 | import json
import pathlib
import struct
import soundfile
import scipy.signal
import numpy as np
import oddvoices.phonology
def midi_note_to_hertz(midi_note):
return 440 * 2 ** ((midi_note - 69) / 12)
def seconds_to_timestamp(seconds):
minutes = int(seconds / 60)
remaining_seconds = seconds - minutes * ... |
3287677 | from powerdataclass import PowerDataclass, field_handler, type_handler
def test_pdc_metaclass_pdc_meta_collapses_pdc_meta():
class PDC(PowerDataclass):
pass
class PDC2(PDC):
class Meta:
a = 1
class PDC3(PDC2):
class Meta:
a = 2
b = 3
asser... |
3287691 | from django.conf.urls import patterns, url
from radpress.views import (
ArticleArchiveView, ArticleDetailView, ArticleListView, PreviewView,
PageDetailView, SearchView, ZenModeView, ZenModeUpdateView)
from radpress.feeds import ArticleFeed
urlpatterns = patterns(
'',
url(r'^$',
view=ArticleLis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.