id
stringlengths
3
8
content
stringlengths
100
981k
168322
import networkx import numpy import chainer from chainer_chemistry.dataset.graph_dataset.base_graph_dataset import PaddingGraphDataset, SparseGraphDataset # NOQA from chainer_chemistry.dataset.graph_dataset.base_graph_data import PaddingGraphData, SparseGraphData # NOQA from chainer_chemistry.dataset.graph_dataset.f...
168478
from opentera.db.Base import db, BaseModel from enum import Enum import random from datetime import datetime, timedelta import uuid class TeraSessionStatus(Enum): STATUS_NOTSTARTED = 0 STATUS_INPROGRESS = 1 STATUS_COMPLETED = 2 STATUS_CANCELLED = 3 STATUS_TERMINATED = 4 class TeraSession(db.Mod...
168480
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.minard_troops import minard_troops def test_minard_troops(): """Test module minard_troops.py by downloading minard_troops.csv and testing sha...
168481
import sys from decorator import decorator from fabric.api import env, hide, parallel, run, settings from fabric.tasks import execute env.shell = '/bin/bash -l -c -o pipefail' env.keepalive = 60 env.timeout = 60 def parallel_task(server_side=True): @decorator def _parallel_task(task, *args, **kargs): ...
168492
from __future__ import absolute_import from django.db import models from django.utils.translation import ugettext_lazy from smsgateway.enums import (OPERATOR_CHOICES, OPERATOR_UNKNOWN, GATEWAY_CHOICES, DIRECTION_CHOICES, DIRECTION_INBOUND, PRIORITIES, PRIORITY_MEDIUM, PRIORITY_DEFERRED) ...
168525
from tqdm import tqdm import torch as tc import pdb import os , sys import math import fitlog import re from utils.scorer import get_f1 from utils.train_util import pad_sents , get_data_from_batch from utils.write_keyfile import write_keyfile def before_test(C , logger , dataset , models): if isinstance(models , tc...
168533
from django.contrib import admin from reversion.admin import VersionAdmin from django.contrib.flatpages.admin import FlatPage, FlatPageAdmin from .models import HostedPicture admin.site.unregister(FlatPage) @admin.register(FlatPage) class FlatPageVersionedAdmin(VersionAdmin, FlatPageAdmin): pass @admin.regist...
168535
import unittest import subprocess class TestPapermill(unittest.TestCase): def test_papermill(self): result = subprocess.run([ 'papermill', '/input/tests/data/notebook.ipynb', '-', ], stdout=subprocess.PIPE) self.assertEqual(0, result.returncode) ...
168596
from rest_framework import serializers from .models import * class ChickenSerializer(serializers.ModelSerializer): class Meta: model = Chicken fields = '__all__' class WorkerSerializer(serializers.ModelSerializer): class Meta: model = Worker fields = '__all__' class BreedSerializer(serializers.ModelSerial...
168611
from rest_framework import decorators, permissions, status, viewsets from rest_framework.response import Response from lego.apps.feeds.attr_cache import AttrCache from .feed_manager import feed_manager from .models import NotificationFeed, PersonalFeed, UserFeed from .serializers import ( AggregatedFeedSerializer...
168632
import numpy as np def flux(x): return 0.5 * np.square(x) def minf(a,b): # if b<=0: # return flux(b) # elif a>=0: # return flux(a) # else: # return 0.0 return (b <= 0) * flux(b) + (a >= 0) * flux(a) def maxf(a,b): return np.maximum(flux(a),flux(b))
168634
from .base import MetricSelector class SemanticSimilarity(MetricSelector): """ :English: :py:class:`.UniversalSentenceEncoder` """ def _select(self, lang): if lang.name == "english": from ..algorithms.usencoder import UniversalSentenceEncoder return UniversalSentenceEnco...
168661
import argparse import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Normal from torch.autograd import grad from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler from tensorboardX import SummaryWriter...
168680
from manimlib.imports import * class Scene_(Scene): CONFIG = { "camera_config": { "background_color": WHITE } } class NF24P3358(Scene_): def construct(self): line = Line(LEFT*3, RIGHT*3, color=BLACK) nodes = VGroup( *[ Circle(radius=...
168681
from keanu.vertex import Gamma from keanu import BayesNet from keanu.network_io import ProtobufLoader, JsonLoader, ProtobufSaver, DotSaver, JsonSaver def test_can_save_and_load(tmpdir) -> None: PROTO_FILE_NAME = str(tmpdir.join("test.proto")) JSON_FILE_NAME = str(tmpdir.join("test.json")) DOT_FILE_NAME = s...
168688
import re import six from sqlalchemy import inspect from jet_bridge_base.exceptions.validation_error import ValidationError def serialize_validation_error(exc): def process(e, root=False): if isinstance(e.detail, dict): return dict(map(lambda x: (x[0], process(x[1])), e.detail.items())) ...
168690
import random import bintrees import threading from itertools import count from collections import Counter import tensorflow as tf from joblib import Parallel, delayed from lib.ops import get_available_gpus from lib.trainer import SampleBasedTrainer class MultiGPUTrainer: def __init__(self, name, make_model, ...
168735
import asyncio def main(): print("Creating our event loop") loop = asyncio.get_event_loop() loop.run_forever() print("Our Loop will now run forever, this will never execute") if __name__ == '__main__': main()
168738
from functools import wraps from django.http.response import HttpResponse from atlassian_jwt_auth.frameworks.django.decorators import with_asap def validate_asap(issuers=None, subjects=None, required=True): """Decorator to allow endpoint-specific ASAP authorization, assuming ASAP authentication has already ...
168758
import os import typing class MetadataToPsvTransformer: """ Abstract class for transforming DSS metadata to PSV rows. """ PSV_EXT = ".psv" OUTPUT_DIRNAME = "output" LOG_DIRNAME = "logs" def __init__(self, staging_dir): self.staging_dir = staging_dir self.output_dir = os.pa...
168767
str = "RahulShettyAcademy.com" str1 = "Consulting firm" str3 = "RahulShetty" print(str[1]) #a print(str[0:5]) # if you want substring in python print(str+str1) # concatenation print(str3 in str) # substring check var = str.split(".") print(var) print(var[0]) str4 = " great " print(str4.strip()) print(str4.ls...
168801
from activfuncs import plot, x import numpy as np def softplus(x): return np.log(1+np.exp(x)) plot(softplus, yaxis=(-0.4, 1.4))
168834
import os import json from easydict import EasyDict from pprint import pprint from utils.dirs import create_dirs def get_config_from_json(json_file): """ Get the config from a json file :param json_file: the path of the config file :return: config(namespace), config(dictionary) """ # parse ...
168924
import unittest M = None MN = None MN2 = None class NestedTest(unittest.TestCase): """ Verifies we can create instance from nested proto file. https://github.com/appnexus/pyrobuf/issues/55 """ @classmethod def setUpClass(cls): global M global MN global MN2 fro...
168931
from datetime import datetime, date import django.test from contracts.models import Contract, Entity, ProcedureType from contracts.views_data import * from contracts.views_analysis import ANALYSIS class TestAnalysis(django.test.TestCase): def test_contracts_price_histogram(self): Contract.objects.creat...
168933
import operator import unittest import cyordereddict class TestOrderedDict(unittest.TestCase): def setUp(self): data = [('x', 0), ('y', 1), ('z', 2)] self.dicts = [] try: import collections self.dicts.append(collections.OrderedDict(data)) except AttributeEr...
168937
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'somesecretkey' LAZYLOAD_LDA = False ALLOW_ANON = True DEFAULT_LDA_MODEL = 'Demo' DEFAULT_DB = 'Demo Keyword-based Model' # Flask-Uploads configs - used in /app/__init__.p...
168945
import os import argparse parser = argparse.ArgumentParser() parser.add_argument("--model", type=str) parser.add_argument("--data_dir", type=str) args = parser.parse_args() for file in os.listdir(args.data_dir): cmd = 'python scripts/evaluate_feats.py ' if 'test' in file: cmd += ' --reference ' + os.p...
168951
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('smsbillables', '0010_gateway_fee_amount_null'), ] operations = [ migrations.AlterField( model_name='smsbillable', name='date_created', field=models.DateT...
168958
class Config: def __init__(self): self.DARKNET_PATH = "lib/pyyolo/darknet" self.DATACFG = "data/obj.data" self.CFGFILE = "cfg/yolo-obj.cfg" self.WEIGHTFILE_SKETCH = "models/yolo-obj_final_sketch.weights" self.WEIGHTFILE_TEMPLATES = "models/yolo-obj_45000.weights" self...
169009
from typing import Any, List from boa3.builtin.interop.contract import create_multisig_account from boa3.builtin.type import ECPoint, UInt160 def main(minimum_sigs: int, public_keys: List[ECPoint], arg: Any) -> UInt160: return create_multisig_account(minimum_sigs, public_keys, arg)
169032
class RemoteDockerException(RuntimeError): pass class InstanceNotRunning(RemoteDockerException): pass
169043
import math import torch.nn as nn from rls.nn.activations import Act_REGISTER, default_act Vec_REGISTER = {} class VectorIdentityNetwork(nn.Sequential): def __init__(self, in_dim, *args, **kwargs): super().__init__() self.h_dim = self.in_dim = in_dim self.add_module(f'identity', nn.Ide...
169050
import numpy as np def run_optimizer(opt, cost_f, iterations, *args, **kwargs): errors = [cost_f.eval(cost_f.x_start, cost_f.y_start)] xs,ys= [cost_f.x_start],[cost_f.y_start] for epochs in range(iterations): x, y= opt.step(*args, **kwargs) xs.append(x) ys.append(y) errors....
169059
def run_api_workflow_with_assertions(workflow_specification, current_request, test_context): current_request_result = current_request(test_context) if current_request_result is not None and current_request_result["continue_workflow"]: run_api_workflow_with_assertions( workflow_specification,...
169092
import torch import typing def check_vector(x, name): if not torch.is_tensor(x): raise RuntimeError('{} needs to be a Tensor'.format(name)) if x.dim() != 1: raise RuntimeError('{} needs to be a vector (one-dimensional Tensor)'.format(name)) def check_scalar(x, name): if not torch.is_tens...
169150
import warnings class LogWrapper(object): def __init__(self, logger, context): self.logger = logger self.context = context def __call__(self, key, value): warnings.warn( "Calling context.iopipe.log() has been deprecated, use " "context.iopipe.metric() instead" ...
169153
from functools import partial import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_sched from .fastai_optim import OptimWrapper from .learning_schedules_fastai import CosineWarmupLR, OneCycle class FusedOptimizer(optim.Optimizer): def __init__(self, all_params, lr=None, weight...
169166
from datetime import datetime import numpy as np import pandas as pd from sklearn.utils import shuffle from data_process import data_process_utils from data_process.census_process.census_data_creation_config import census_data_creation from data_process.census_process.census_degree_process_utils import consistentize_...
169210
from singlecellmultiomics.modularDemultiplexer.baseDemultiplexMethods import UmiBarcodeDemuxMethod # Cell seq 1 with 6bp UMI class CELSeq1_c8_u4(UmiBarcodeDemuxMethod): def __init__(self, barcodeFileParser, **kwargs): self.barcodeFileAlias = 'celseq1' UmiBarcodeDemuxMethod.__init__( se...
169250
from soccerdepth.data.dataset_loader import get_set import numpy as np import utils.files as file_utils from os.path import join import argparse from soccerdepth.models.hourglass import hg8 from soccerdepth.models.utils import weights_init from soccerdepth.data.data_utils import image_logger_converter_visdom import to...
169330
from nose.tools import eq_, ok_ from django.core.urlresolvers import reverse from .base import ManageTestCase class TestTasksTester(ManageTestCase): def test_dashboard(self): url = reverse('manage:tasks_tester') response = self.client.get(url) eq_(response.status_code, 200) res...
169342
import logging import multiprocessing import time from radosgw_agent import worker from radosgw_agent import client from radosgw_agent.util import get_dev_logger from radosgw_agent.exceptions import NotFound, HttpError log = logging.getLogger(__name__) dev_log = get_dev_logger(__name__) # the replica log api only s...
169356
import math from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union import moderngl as mgl import numpy as np import vpype as vp from ._utils import ColorType, load_program, load_texture_array if TYPE_CHECKING: # pragma: no cover from .engine import Engine ResourceType = Union[mgl.Buffer, mgl.Text...
169383
from unittest import TestCase from numpy import array, ndarray from numpy.testing import assert_array_equal from trigger import accel_value, trigger_time class TriggerTimeTest(TestCase): def test_estimates_when_function_exceeds(self): function = 10 t = array([1599574034]) trig_level = 100 ...
169482
from aetherling.helpers.nameCleanup import cleanName from magma import * from magma.frontend.coreir_ import GetCoreIRBackend from aetherling.modules.hydrate import Dehydrate, Hydrate from mantle.coreir.memory import DefineRAM, getRAMAddrWidth __all__ = ['DefineRAMAnyType', 'RAMAnyType'] @cache_definition def DefineR...
169483
from pySDC.projects.parallelSDC.newton_vs_sdc import main as main_newton_vs_sdc from pySDC.projects.parallelSDC.newton_vs_sdc import plot_graphs as plot_graphs_newton_vs_sdc from pySDC.projects.parallelSDC.nonlinear_playground import main, plot_graphs def test_main(): main() plot_graphs() def test_newton_vs_...
169485
from __future__ import division from __future__ import absolute_import from builtins import object from past.utils import old_div from nose.tools import (assert_equal, assert_not_equal, raises, assert_almost_equal) from nose.plugins.skip import SkipTest from .test_helpers import assert_items_alm...
169499
from __future__ import with_statement # this is to work with python2.5 from validation import vworkspace with vworkspace() as w: w.props.flatten_code_unroll = False w.all_functions.validate_phases("coarse_grain_parallelization","flatten_code","coarse_grain_parallelization","loop_fusion")
169510
from typing import List from veniq.ast_framework import ASTNodeType, AST from veniq.ast_framework.ast_node import ASTNode class ClassicSetter: """ The method's name starts with set. There are attributes assigning in the method. Also, asserts are ignored. """ suitable_nodes: List[ASTNodeType] = [ ...
169517
from helpers import render def aboutus(request): return render(request, {}, 'news/aboutus.html') def help(request): return render(request, {}, 'news/help.html') def buttons(request): return render(request, {}, 'news/buttons.html')
169559
from __future__ import print_function from pymel.core import hide, showHidden, selected, select from .. import core from ..nodeApi import fossilNodes class QuickHideControls(object): ''' Toggle the visibility of the selected rig controls. ''' controlsToHide = [] hideMain = False mainSha...
169595
import os import boto3 from common import AWSServiceCollector, AWS_REGIONS_SET sns = boto3.client('sns') sts = boto3.client('sts') class ElasticBeanstalkCollector(AWSServiceCollector): boto3_service_name = 'elasticbeanstalk' def _collect_assets(self): # collect Elastic Beanstalk domains and endpoi...
169613
from boa3.builtin import public from boa3.builtin.interop.contract import CallFlags @public def main(flag: str) -> CallFlags: call_flags: CallFlags if flag == 'ALL': call_flags = CallFlags.ALL elif flag == 'READ_ONLY': call_flags = CallFlags.READ_ONLY elif flag == 'STATES': cal...
169628
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class DialogDemo(QMainWindow): def __init__(self, parent=None): super(DialogDemo, self).__init__(parent) self.setWindowTitle("Dialog demo") self.resize(600, 400) self.button...
169664
from .repos import ApiTokenRepo from .responses import ApiTokenResponse, ApiTokensResponse, SensitiveApiTokenResponse from .data import ApiTokenData, SensitiveApiTokenData from .forms import ApiTokenCreateForm
169675
import os import sys import unittest from nose.config import Config from nose.plugins import doctests from mock import Bucket class TestDoctestErrorHandling(unittest.TestCase): def setUp(self): self._path = sys.path[:] here = os.path.dirname(__file__) testdir = os.path.join(here, 'support'...
169683
import os os.system("clear") print("\nassembling crt0...\n") if(os.system("sdasz80 -o crt0_fap.s") != 0): exit() print("\ncompiling hellofap.c...\n") # code-loc is where main() is, data-loc is where RAM starts if os.system("sdcc -mz80 --code-loc 0x200 --data-loc 0xc000 --no-std-crt0 crt0_fap.rel hellofap.c") != 0:...
169694
import os import sys from setuptools import setup setup( name='apple-mango', version='0.2', url='https://github.com/legshort/apple-mango/', license='MIT', author='<NAME>', author_email='<EMAIL>', description='Light weight BDD Pattern', classifiers=[ 'Programming Language :: Pyt...
169700
import numpy as np from forge.blade.action import action from forge.blade.systems import skill, droptable class Entity(): def __init__(self, pos): self.pos = pos self.alive = True self.skills = skill.Skills() self.entityIndex=0 self.health = -1 self.lastAttacker = None def a...
169723
import time import os import sys import requests COLORS = {\ "black":"\u001b[30;1m", "red": "\u001b[31;1m", "green":"\u001b[32m", "yellow":"\u001b[33;1m", "blue":"\u001b[34;1m", "magenta":"\u001b[35m", "cyan": "\u001b[36m", "white":"\u001b[37m", "yellow-background":"\u001b[43m", "black-background":"\u00...
169737
import torch import torch.nn as nn import torch.nn.functional as F class Transformer(nn.Module): def __init__(self, vocab_size: int, max_seq_len: int, embed_dim: int, hidden_dim: int, n_layer: int, n_head: int, ff_dim: int, embed_drop: float, hidden_drop: float): super().__init__() self.tok_embedd...
169828
import os from pyscf.pbc.gto import Cell from pyscf.pbc.scf import KRHF from pyscf.pbc.tdscf import KTDHF from pyscf.pbc.tdscf import krhf_slow_gamma as ktd import unittest from numpy import testing import numpy from test_common import retrieve_m, retrieve_m_hf, assert_vectors_close, tdhf_frozen_mask class DiamondT...
169843
import numpy as np from collections import namedtuple from itertools import product import pybullet as p from pybullet_planning.utils import CLIENT, BASE_LINK, UNKNOWN_FILE, OBJ_MESH_CACHE from pybullet_planning.utils import implies ##################################### # Bounding box AABB = namedtuple('AABB', ['lo...
169854
import tensorflow as tf import argparse import tensorflow as tf import environments from agent import PPOAgent from policy import * def print_summary(ep_count, rew): print("Episode: %s. Reward: %s" % (ep_count, rew)) def start(env): MASTER_NAME = "master-0" tf.reset_default_graph() with tf.Sessi...
169864
def is_armstrong_number(number): return sum(pow(int(digit), len(str(number))) for digit in str(number)) == number
169890
from externals.moduleman.plugin import moduleman_plugin import itertools class piterator_void: text="void" def count(self): return self.__count def __init__(self, *i): self._dic = i self.__count = max(map(lambda x:x.count(), i)) self.it = self._dic[0] def next(self): return (self.it.next(),) ...
169895
from collections import namedtuple from utils import lerp class RGB(namedtuple('RGB', 'r g b')): """ stores color as a integer triple from range [0, 255] """ class Color(namedtuple('Color', 'r g b')): """ stores color as a float triple from range [0.0, 1.0] """ def rgb12(self): r = int(self.r *...
169919
import pyos def onStart(s, a): global state, app, editor state = s app = a editor = Editor() def save(): editor.save() class Editor(object): def __init__(self): self.path = "" self.fobj = None self.saved = False self.textField = pyos.G...
169921
class EmptyDicomSeriesException(Exception): """ Exception that is raised when the given folder does not contain dcm-files. """ def __init__(self, *args): if not args: args = ('The specified path does not contain dcm-files. Please ensure that ' 'the path points to...
169939
import numpy as np import glob cannon_teff = np.array([]) cannon_logg = np.array([]) cannon_feh = np.array([]) cannon_alpha = np.array([]) tr_teff = np.array([]) tr_logg = np.array([]) tr_feh = np.array([]) tr_alpha = np.array([]) a = glob.glob("./*tr_label.npz") a.sort() for filename in a: labels = np.load(fil...
169980
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from smart_settings import Namespace from .literals import DEFAULT_MAXIMUM_TITLE_LENGTH namespace = Namespace(name='appearance', label=_('Appearance')) setting_max_title_length = namespace.add_setting( global_name='A...
169988
from collections import OrderedDict import torch from torch import nn import torch.nn.functional as F from exp import ex from utils import jsonl_to_json, mean from data.batcher import make_feature_lm_batch_with_keywords, ConvertToken from .modules import Attention, GRU from .scn_rnn import SCNLSTM from .transformer_...
170044
import os import typing from contextlib import suppress from pathlib import Path from qtpy.QtWidgets import QDialog, QFileDialog, QGridLayout, QPushButton, QStackedWidget from PartSegCore.io_utils import SaveBase from .algorithms_description import FormWidget from .custom_load_dialog import IORegister, LoadRegisterF...
170074
from security_monkey.tests import SecurityMonkeyTestCase from security_monkey.auditor import Entity from security_monkey.auditors.resource_policy_auditor import ResourcePolicyAuditor from security_monkey import db from security_monkey.watcher import ChangeItem from security_monkey.datastore import Datastore from securi...
170094
import pytest from botx import SystemEvents pytest_plugins = ("tests.test_collecting.fixtures",) def test_registration_handler_for_several_system_events( handler_as_function, extract_collector, collector_cls, ): system_events = { SystemEvents.chat_created, SystemEvents.file_transfer,...
170095
from typing import Optional, Tuple # noinspection PyUnreachableCode if False: # noinspection PyUnresolvedReferences from _stubs import * class Rack: def __init__(self, ownerComp): self.ownerComp = ownerComp @property def RackTools(self): return self.ownerComp.op('rack_tools') @property def RackToolsPane(se...
170104
from .workspaceStructure import WorkspaceStructure class Bond(WorkspaceStructure): # pylint: disable=too-many-arguments def __init__(self, ctx, source, destination, bondCategory, bondFacet, sourceDescriptor, destinationDescriptor): WorkspaceStructure.__init__(self, ctx) slipne...
170173
from insights.parsers import sap_host_profile, SkipException from insights.parsers.sap_host_profile import SAPHostProfile from insights.tests import context_wrap import doctest import pytest HOST_PROFILE_DOC = """ SAPSYSTEMNAME = SAP SAPSYSTEM = 99 service/porttypes = SAPHostControl SAPOscol SAPCCMS DIR_LIBRARY = DIR_...
170201
from __future__ import unicode_literals import matplotlib.pyplot as plt import fileinput import sys # # Displays one ore more CSV files in a graph. Intended to be used # with the `bench_tables.rs` example. # # Accepts data from STDIN and additional files can be passed in as # command line arguments. A use ca...
170248
import unittest import random from collection.set import Set class TestSet(unittest.TestCase): def setUp(self): self.set = Set() def test_constructor(self): self.assertTrue(self.set.is_empty()) self.assertEquals(0, len(self.set)) def test_one_add(self): element = 'foo' ...
170250
import factory from intake import models from django.contrib.auth.models import User from .status_notification_factory import StatusNotificationFactory class StatusUpdateFactory(factory.DjangoModelFactory): status_type = factory.Iterator(models.StatusType.objects.filter( is_a_status_update_choice=True)) ...
170280
import struct import sys import matplotlib.pyplot as plt import numpy as np import mmap import os if len(sys.argv) < 2: print("Usage: %s <path>" %(sys.argv[0])) file = sys.argv[1] filename = file.split("/")[-1] arr = np.memmap(file, dtype='float64', mode='r') plt.plot(arr) plt.title(filename) print("saving="+fi...
170282
import os import discord from discord.ext import commands from discord.ext.commands import BucketType, cooldown import motor.motor_asyncio import nest_asyncio import json with open('./data.json') as f: d1 = json.load(f) with open('./market.json') as f: d2 = json.load(f) items = {} for x in d2["IoT"]: i =...
170323
import time from functools import partial from operator import is_not import requests from lxml import html from lxml.cssselect import CSSSelector from reppy.cache import RobotsCache from reppy.exceptions import ConnectionException try: from urlparse import urlparse, urljoin except ImportError: from urllib.par...
170344
from flask_app import hello_world SWAGGER_SETTINGS = { 'title': 'Flask Test Application API', 'version': '1.0.0', 'basePath': '/', 'host': '', 'consumes': [ 'application/json', 'application/x-www-form-urlencoded', 'multipart/form-data', ], 'produce': [ 'appl...
170352
import numpy as np import os import csv import argparse import torchvision.transforms as transforms from PIL import Image def loading_ucf_lists(): dataset_root = "/home/ubuntu/data/ucf101" split = 'split_1' # data frame root dataset_frame_root = os.path.join(dataset_root, 'rawframes') # data lis...
170360
import tensorflow as tf slim = tf.contrib.slim from helper_net.inception_v4 import * import pickle import numpy as np def get_weights(): checkpoint_file = '../checkpoints/inception_v4.ckpt' sess = tf.Session() arg_scope = inception_v4_arg_scope() input_tensor = tf.placeholder(tf.float32, (None, 299, 299, 3)) with...
170407
import comet_ml # noqa: F401 import pytest import numpy as np import torch from conftest import create_dataset, create_image from traintool.image_classification.preprocessing import ( recognize_data_format, torch_to_numpy, numpy_to_torch, files_to_numpy, files_to_torch, load_image, recogn...
170409
from cms.models.pluginmodel import CMSPlugin from django.db import models class VerticalSpacerPlugin(CMSPlugin): smart_space = models.PositiveIntegerField( "Default Space", default=0, help_text="in px, for desktop, height on other devices is calculated automatically", ) space_xs =...
170466
import pytest from redis.exceptions import WatchError def test_ok(redis): client = redis.ext.client pipeline = client.pipeline() pipeline.set('test', 1) pipeline.sadd('test2', 2) pipeline.execute() assert client.get('test') == b'1' assert redis.dict == {b'test': b'1', b'test2': {b'2'}} ...
170474
import torch from torch import nn from torch.nn import Parameter jit_scripts = {} class StochasticModule(torch.nn.Module): def __init__(self, *args, **kwargs): super(StochasticModule, self).__init__(*args, **kwargs) class BDropout(StochasticModule): """ Extends the base Dropout layer by ad...
170506
import sublime, sublime_plugin import shlex, os from ..libs import util from ..libs import Terminal from ..libs import javaScriptEnhancements from ..libs.global_vars import * class JavascriptEnhancementsExecuteOnTerminalCommand(): custom_name = "" cli = "" path_cli = "" settings_name = "" placeholders = {...
170513
from typing import Callable, List from .header import Header from .method import MethodType from .responses import Response, no_content class AllowHeader(Header, type=str, http_name='allow'): ... def make_options_controller( methods: List[MethodType], ) -> Callable[[], Response]: def controller() -> Re...
170558
from random import randint import pytest from ms.algo.mergesort_thread import sort as sort_thread from ms.algo.mergesort_proc import sort as sort_proc # the following helps when running $ pytest -vv tests sort_thread.__name__ = 'Sort Thread' sort_proc.__name__ = 'Sort Proc' @pytest.fixture(params=[sort_thread, so...
170634
import logging import example_app from jivago.jivago_application import JivagoApplication if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) app = JivagoApplication(example_app, debug=True) app.run_dev()
170674
import unittest import copy from typing import Optional, List, Callable, Tuple import torch import torch.nn as nn import torch.distributed as dist import torch.multiprocessing as mp import torch.nn.parallel as parallel from torch import Tensor import torchshard as ts from testing import dist_worker, assertEqual, set...
170675
class Chain(): def __init__(self, val): self.val = val def add(self, b): self.val += b return self def sub(self, b): self.val -= b return self def mul(self, b): self.val *= b return self print(Chain(5).add(5).sub(2).mul(10))
170715
import unittest import tock from tock.grammars import * from tock.syntax import String class TestGrammar(unittest.TestCase): def test_init(self): g = Grammar() g.set_start_nonterminal('S') g.add_nonterminal('T') g.add_rule('S', 'a S b') g.add_rule('S', 'T') g.add_rul...
170755
sc.addPyFile('magichour.zip') from magichour.api.dist.events.eventEval import event_eval_rdd from magichour.api.local.util.namedtuples import DistributedLogLine logLineURI = 'hdfs://namenode/magichour/tbird.500.templateEvalRDD' rddlogLines = sc.pickleFile(logLineURI) eventDefURI = 'hdfs://namenode/magichour/tbird.5...