id
stringlengths
3
8
content
stringlengths
100
981k
11416777
import json import torch from allennlp.fairness.bias_utils import load_words, load_word_pairs from allennlp.common.file_utils import cached_path from allennlp.common.testing.test_case import AllenNlpTestCase from allennlp.data import Instance, Token from allennlp.data.batch import Batch from allennlp.data import Voca...
11416789
import re from typing import IO, Iterator, Optional, List, Tuple, Set from interfaces import ConnectionIDSink from core import wl from core.output import Output from core.util import * class WlPatterns: instance = None def __init__(self) -> None: int_re = r'(?P<int>-?\d+)' float_re = r'(?P<fl...
11416823
import os import sys sys.path.insert(0, os.path.abspath('.')) extensions = ['sphinx.ext.autosummary'] autosummary_generate = True autosummary_filename_map = { "autosummary_dummy_module": "module_mangled", "autosummary_dummy_module.bar": "bar" }
11416831
import numpy as np import torch import unittest from network.module import (ActNorm, LinearZeros, Conv2d, Conv2dZeros, Invertible1x1Conv, Permutation2d, Split2d, Squeeze2d) from misc import ops class TestModule(unittest.TestCase): def test_actnorm(self): # initial variables ...
11416840
import numpy as np import torch from dataclasses import dataclass from typing import List from jiant.tasks.core import ( BaseExample, BaseTokenizedExample, BaseDataRow, BatchMixin, Task, TaskTypes, ) from jiant.tasks.lib.templates.shared import ( labels_to_bimap, add_cls_token, crea...
11416869
import cgi def main(): if cgi.dictionary is None or not cgi.dictionary.has_key('file'): show_form() else: show_file() def show_form(error = ''): if error != '': error = '\t\t\t' + error + ' cannot be displayed.<br>\n' cgi.html('''<html> \t<head> \t\t<title> \t\t\tPython Script ...
11416912
from threading import Semaphore mutex = Semaphore(1) track = Semaphore(0) planes = [] landing_tracks = [] active_landing_tracks = 0
11416927
import struct_value b = struct_value.Bar() b.a.x = 3 if b.a.x != 3: raise RuntimeError b.b.x = 3 if b.b.x != 3: raise RuntimeError # Test dynamically added attributes - Github pull request #320 b.added = 123 if b.added != 123: raise RuntimeError("Wrong attribute value") if not b.__dict__.has_key("add...
11416930
from datetime import datetime, time from city_scrapers_core.constants import BOARD, COMMITTEE from city_scrapers_core.items import Meeting from city_scrapers_core.spiders import CityScrapersSpider class ChiMetroPierExpositionSpider(CityScrapersSpider): name = "chi_metro_pier_exposition" agency = "Chicago Met...
11416955
import unittest import shutil import sys import os from pathlib import Path import filecmp from azure.storage.blob import BlockBlobService # Allow us to import utils config_dir = str(Path.cwd().parent / "utils") if config_dir not in sys.path: sys.path.append(config_dir) from config import Config tag_dir = str(Pa...
11416977
from .utils.Classes.RegEx import RegEx from .utils.assert_string import assert_string def is_btc_address(input: str) -> bool: input = assert_string(input) bech32 = RegEx("^(bc1)[a-z0-9]{25,39}$") base58 = RegEx("^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$") if input.startswith('bc1'): return bech32.m...
11417002
def evaluate_equation_process_add_sub(operation): return (operation == '+' or operation == '-') def evaluate_equation_process(equation, return_on_first_found): operators = {'/': (lambda a, b: a / b), '*': (lambda a, b: a * b), '+': (lambda a, b: a + b), '-': ...
11417006
import logging import os import time class Logger: def __init__(self, logdir, rank, type='torch', debug=False, filename=None, summary=True, step=None): self.logger = None self.type = type self.rank = rank self.step = step self.logdir_results = os.path.join("logs", "results"...
11417141
def f(x): try: f(x) except: f(x) try: f(x) except Exception: f(x) try: f(x) except Exception as e: f(x, e)
11417271
import asyncpg from typing import Any, NoReturn from discord.utils import MISSING from donphan import create_pool, create_db, MaybeAcquire, OPTIONAL_CODECS from .tables import * from .emoji import * from .scheduler import * class NoDatabase(MaybeAcquire): def __init__(self, *args: Any, **kwargs: Any): ...
11417284
import numpy as np from matplotlib import pyplot as plt from evolute import GeneticPopulation from evolute.evaluation import SimpleFitness TARGET = np.ones(10) * 0.5 pop = GeneticPopulation(loci=10, fitness_wrapper=SimpleFitness(lambda ind: np.linalg.norm(ind - TARGET))) history = pop.run(1...
11417290
import seamless from seamless.core import macro_mode_on from seamless.core import context, cell, transformer, unilink from seamless import get_hash seamless.set_ncores(0) from seamless import communion_server communion_server.configure_master( transformation_job=True, transformation_status=True, ) with macro_...
11417343
import unittest from rma.jemalloc import Jemalloc class JemallocTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_align(self): data = [[79, 80], [253, 256], [512, 512], [513, 768], [3645, 3840], [4098, 8192], [4200304, 8388608]] for give...
11417377
from ...core.enum.ea_mode import EAMode from ...core.enum.op_size import OpSize from ...core.enum import ea_mode_bin from ...core.enum.ea_mode_bin import parse_ea_from_binary from ...simulator.m68k import M68K from ...core.opcodes.opcode import Opcode from ...core.util.split_bits import split_bits from ...core.util imp...
11417414
import logging import os import numpy as np from das_framework.driver import AbstractDASErrorMetrics import programs.metrics.error_metrics_node as em import programs.metrics.metric_group as mgmod import sys import time from pyspark.sql import Row import ast import json import pickle CONFIG_DELIM = ", " BLANK = "" NATI...
11417416
import numpy as np import warnings from .base_regularizer import BaseRegularizer class TopicPriorRegularizer(BaseRegularizer): """ TopicPriorRegularizer adds prior beta_t to every column in Phi matrix of ARTM model. Thus every phi_wt has preassigned prior probability of being attached to topic t. ...
11417422
import os.path import numpy as np import torch import torch.nn as nn from torch.optim import Optimizer from torch.autograd import Variable import torch.autograd as autograd from torch.utils.data import DataLoader from tensorboardX import SummaryWriter """ This module implements Wasserstein Generative Adversarial Net...
11417472
import argparse import pkg_resources try: # pip < 20 from pip._internal.req import parse_requirements from pip._internal.download import PipSession except: # pip >= 20 from pip._internal.req import parse_requirements from pip._internal.network.session import PipSession def combine_requirements...
11417577
import numpy as np from numpy.linalg import inv from utils.JES3D_transform_utils import file_lines_to_list import copy def read_cam(str): cam = {} wrds=str.split(' ') if not len(wrds)==14: return cam vals = [float(w) for w in wrds] cam['id'] = vals[0]+1 cam['f'] = vals[1] cam['R'] = ...
11417581
from ..utils import validate_activation_code from django.utils.http import urlsafe_base64_decode as uid_decoder from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers, exceptions class VerifyEmailSerializeras(serializers.Serializer): activation_code = serializers.CharFie...
11417583
class InstanceData(object): """ Holds instance data associated with a performance counter sample. InstanceData(instanceName: str,sample: CounterSample) """ @staticmethod def __new__(self,instanceName,sample): """ __new__(cls: type,instanceName: str,sample: CounterSample) """ pass InstanceName...
11417585
from bottle import tob from .bottle_tools import ServerTestBase from tests.examples import quickstart import unittest from urllib.parse import unquote from urllib.parse import parse_qs class test_quickstart(ServerTestBase): def setUp(self): import importlib importlib.reload(quickstart) sup...
11417599
from django.test import SimpleTestCase from crits.relationships.handlers import forge_relationship, update_relationship_reasons, update_relationship_confidences from crits.core.user import CRITsUser from crits.campaigns.campaign import Campaign from crits.vocabulary.relationships import RelationshipTypes TUSER_NAME =...
11417607
import unittest from PyStacks.PyStacks.template import templateCF class TestTemplate(unittest.TestCase): def test_templateCF_ACM(self): resources = { "certificatemanager": { "shopkablamocomau": { "domainname": "shop.kablamo.com.au", "do...
11417623
from .util.metadata_helper import load_metadata def get_dataset_class(name): if name == 'RoboNet': from .robonet_dataset import RoboNetDataset return RoboNetDataset elif name == 'AnnotatedRoboNet': from .variants.annotation_benchmark_dataset import AnnotationBenchmarkDataset re...
11417682
from mock.mock import patch import os import pytest import ca_test_common import ceph_osd fake_cluster = 'ceph' fake_container_binary = 'podman' fake_container_image = 'quay.ceph.io/ceph/daemon:latest' fake_id = '42' fake_ids = ['0', '7', '13'] fake_user = 'client.admin' fake_keyring = '/etc/ceph/{}.{}.keyring'.format...
11417752
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: trie = {} def update_trie(word, trie_node): for letter in word: if letter not in trie_node: trie_node[letter] = {} trie_node = trie_node...
11417755
from lego.apps.action_handlers.handler import Handler from lego.apps.action_handlers.registry import register_handler from lego.apps.feeds.activity import Activity from lego.apps.feeds.feed_manager import feed_manager from lego.apps.feeds.models import NotificationFeed, PersonalFeed from lego.apps.feeds.verbs import An...
11417757
import os from bentoctl.exceptions import BentoctlException BENTOML_DOCKER_FILE_PATH = "./env/docker/Dockerfile" def create_deployable_from_local_bentostore( bento_path: str, destination_dir: str, # pylint: disable=unused-argument bento_metadata: dict, # pylint: disable=unused-argument overwrite_d...
11417832
import numpy as np from tools.utils import Helper import matplotlib.pyplot as plt from scipy.spatial.distance import cdist import sys import argparse import tensorflow as tf def tf_fake_iou(X: tf.Tensor, centroids: tf.Tensor) -> tf.Tensor: """ calc the fake iou between x and centroids Parameters --------...
11417841
from flask import g, request, session from social.backends.utils import user_backends_data from social.apps.flask_app.utils import get_helper from social.utils import module_member def backends(): """Load Social Auth current user data to context under the key 'backends'. Will return the output of social.back...
11417913
from click.testing import CliRunner import yadage.manualcli import os import jq import json def test_manual_remove(tmpdir): runner = CliRunner() workdir = os.path.join(str(tmpdir), "workdir") metadir = os.path.join(str(tmpdir), "metadir") statefile = os.path.join(str(tmpdir), "state.json") result ...
11417923
import time from webwhatsapi import WhatsAPIDriver print "waiting for QR" driver = WhatsAPIDriver() driver.firstrun() driver.view_unread() print "bot started" while True: time.sleep(1) print('checking for more messages') for contact in driver.view_unread(): for message in contact[u'messages']: driver.send_to_wh...
11417925
import sys, random, os, scipy.io, pickle, argparse, time sys.path.extend(['sampler/', 'utils/']) import numpy as np from tqdm import tqdm from sklearn.externals import joblib import tensorflow as tf from sklearn.utils import shuffle from bnn import evaluate, grad_bnn, logp_bnn from load_uci import load_uci_data from ks...
11417961
import math import dgl import pytorch_lightning as pl import torch as th import torch.nn as nn import torch.nn.functional as F class NodeExplainerModule(nn.Module): """ A Pytorch module for explaining a node's prediction based on its computational graph and node features. Use two masks: One mask on edges...
11417965
import typing as t import nnf from nnf.util import T_NNF, Name class Builder: """Automatically deduplicates NNF nodes as you make them, to save memory. Usage: >>> builder = Builder() >>> var = builder.Var('A') >>> var2 = builder.Var('A') >>> var is var2 True As long as the Builder...
11418013
import os from unittest.mock import patch from util.job import get_job_id def test_create_job_id(): assert get_job_id() == os.getenv('JOB_ID'), 'job id is created' @patch.dict('os.environ', {'JOB_ID': 'job_123'}) def test_retrieve_job_id(): assert get_job_id() == 'job_123', 'job id is retrieved'
11418015
from typing import Dict, Tuple import random import string import sha3 from ecdsa import SigningKey, SECP256k1 from secp256k1 import PrivateKey from .blockchain_pb2 import Transaction, UnverifiedTransaction, Crypto from .util import param_to_str, param_to_bytes class SignerBase: def __init__(self, version: int ...
11418031
from compas.datastructures import HalfFace # ============================================================================== # Fixtures # ============================================================================== # ============================================================================== # Tests - Schema & j...
11418034
import numpy as np import matplotlib.pyplot as plt import matplotlib from .comodulogram import multiple_band_pass from .utils.peak_finder import peak_finder from .utils.validation import check_consistent_shape, check_array from .utils.validation import check_is_fitted from .utils.viz import add_colorbar, mpl_palette ...
11418043
import networkx as nx import numpy as np import matplotlib.pyplot as plt import sklearn.metrics from heptrkx import pairwise fontsize=16 minor_size=14 def get_pos(Gp): pos = {} for node in Gp.nodes(): r, phi, z = Gp.node[node]['pos'][:3] x = r * np.cos(phi) y = r * np.sin(phi) ...
11418049
import matplotlib import matplotlib.pyplot as plt import math import signatory import torch matplotlib.rc('text', usetex=True) matplotlib.rc('font', size=10) def save(name): plt.tight_layout() plt.savefig(name) plt.close() time = torch.linspace(0, 1, 10) path = torch.stack([torch.cos(math.pi * time), t...
11418064
from nose.tools import * import networkx as nx import networkx.algorithms.approximation as a def test_min_maximal_matching(): # smoke test G = nx.Graph() assert_equal(len(a.min_maximal_matching(G)), 0)
11418067
import yara from app.services.matches_converter import MatchesConverter def test_convert(): rule = yara.compile(source='rule foo: bar {strings: $a = "lmn" condition: $a}') matches = rule.match(data="abcdefgjiklmnoprstuvwxyz") converted = MatchesConverter.convert(matches) assert isinstance(converted,...
11418086
import torch from torch import nn import torch.nn.functional as F class BroadcastDecoder(nn.Module): def __init__(self, config): super().__init__() self.im_size = 32 self.scale = 4 self.num_class = config.num_class self.init_grid() self.g = nn.Sequential( ...
11418127
from os import system def sign_apk(apk_path): proc = system( 'jarsigner -verbose -sigalg SHA1withRSA -storepass android \ -digestalg SHA1 -keystore sign/key.keystore %s androiddebugkey ' % apk_path ) return proc == 0
11418148
import os import re from django.conf import settings from jinja2 import Template def generate_contracts(token): context = { 'TOKEN_CLASS_NAME': token.class_name, 'TOKEN_PUBLIC_NAME': token.public_name, 'CROWDSALE_CLASS_NAME': token.crowdsale_class_name, 'TOKEN_SYMBOL_NAME': token....
11418154
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "TOF" addresses_name = ( "2021-03-15T11:44:05.081204/Torfaen polling_station_export-2021-03-15.csv" ) stations_name = ( "2021-03-15T11:44:05.081204/Torfaen pollin...
11418175
import numpy as np from numpy.testing import assert_equal from trackpy.masks import slice_image, mask_image from trackpy.tests.common import StrictTestCase class TestSlicing(StrictTestCase): def test_slicing_2D(self): im = np.empty((9, 9)) # center for radius in range(1, 5): ...
11418197
from django.core.management.base import BaseCommand from lxml import etree import os import uuid # import core from core.models import Transformation, ValidationScenario class Command(BaseCommand): help = 'Bootstrap Combine with some demo Transformation and Validation scenarios' # def add_arguments(self, pa...
11418229
import itertools def chunks(iterable, size=100): """Split iterable into equal-sized chunks.""" iterator = iter(iterable) chunk = list(itertools.islice(iterator, size)) while chunk: yield chunk chunk = list(itertools.islice(iterator, size))
11418249
import info class subinfo(info.infoclass): def setTargets(self): for ver in ["1.5.9"]: self.targets[ver] = f"https://github.com/anholt/libepoxy/releases/download/{ver}/libepoxy-{ver}.tar.xz" self.targetInstSrc[ ver ] = "libepoxy-" + ver self.targetDigests['1.5.9'] = (['d168a...
11418289
import logging from typing import List import click from aiohttp import web from schemathesis.cli import CSVOption try: from . import _graphql, openapi except ImportError as exc: # try/except for cases when there is a different ImportError in the block before, that # doesn't imply another running environ...
11418293
from datasets.SOT.constructor.base_interface import SingleObjectTrackingDatasetConstructor import os from datasets.types.data_split import DataSplit from miscellanies.natural_keys import natural_keys import numpy as np from .data_specs.LaSOT_attr import LaSOT_attribute_names, LaSOT_attribute_values, LaSOT_attribute_sho...
11418298
import pandas as pd # get structured data def get_data(val): botName = val['botName'] entity = pd.io.json.json_normalize(val['entity_data'], record_path='data', meta='name') train = pd.io.json.json_normalize(val['intent_data']).drop(['entities'], axis=1).drop_duplicates() intent_entity = list(set(pd.i...
11418371
import torch import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import itertools import numpy as np import random def soft_max(vec, mask): batch_size = vec.size(0) _, idx = torch.max(vec, 1) # B * 1 idx = idx.view(batch_size, 1) max_score = torch.gather(vec, 1, idx) # B * 1 max_...
11418422
import sys import os sys.path.append( os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) ) from pyspark.sql import DataFrame from pyspark.sql.functions import split, col, lit from sparkplus.core.udfs import * from pyspark.sql.functions import when class AddressDataFrame(object): ""...
11418438
from skimage.util.dtype import convert from skimage.transform import resize def resize_image(img, new_width, new_height): """Resize image to a ``new_width`` and ``new_height``. Args: img (np.array): An image. new_width (int): New width. new_height (int): New height. Retur...
11418471
from .mapper import ApiResponse, ApiResponseInterface from .mapper.types import Timestamp, AnyType from .model import Caption, Comment __all__ = ['MediaCommentsResponse'] class MediaCommentsResponseInterface(ApiResponseInterface): comments: [Comment] comment_count: int comment_likes_enabled: bool nex...
11418509
import numpy as np def circular(diameter): """ Calculates the equivalent diameter and projected capture area of a circular turbine Parameters ------------ diameter : int/float Turbine diameter [m] Returns --------- equivalent_diameter : float Equivalent...
11418532
import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from codes.models.modules import ScaledDotProductAttention, LayerNormalization import math from codes.utils import constants as Constants import pdb # select device automatically device = torch.device("cuda:0" if torch.cuda...
11418578
import os from pathlib import Path from typing import Dict, Optional, Union import torch import torch.nn as nn from torch.tensor import Tensor from neuro_comma.pretrained import PRETRAINED_MODELS Path_type = Union[Path, str, os.PathLike] class CorrectionModel(nn.Module): def __init__(self, pre...
11418594
from .height_compression import HeightCompression __all__ = { 'HeightCompression': HeightCompression, }
11418605
from typing import List, Optional from flask_accepts import responds from flask_restx import Namespace, Resource from .models import ShowcaseItem from .schema import ShowcaseItemSchema from .service import all_showcase_items_ids, showcase_full_item_by_uid from .showcase_utils import showcase_item_from_db api = Names...
11418625
from abc import abstractmethod from abc import ABC import RootPath class Dictionary(ABC): ROOT_PATH = RootPath.get_root().joinpath("Dataset/Dictionary/") def __init__(self, dictionary_name: str): self.dictionary_name = dictionary_name @abstractmethod def has_dictionary(self): pass ...
11418635
import sys, os import time import logging import itertools import re # lib_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'python-iterator-repeater') # sys.path.append(lib_path) STAGING_PATH = '.' FILE_LIST_SLEEP_INTERVAL = 5 LOG_LEVEL = 'DEBUG' logging.basicConfig(level=LOG_LEVEL...
11418650
import gaptrain as gt from autode.wrappers.keywords import GradientKeywords gt.GTConfig.n_cores = 20 system = gt.System(box_size=[10, 10, 10]) system.add_molecules(gt.Molecule('AcOH.xyz')) # data, gap = gt.active.train(system, # method_name='xtb', # temp=1000) # data.sa...
11418672
from ._base import _rule class Name: reserved = {} tokens = ('NAME',) # Tokens @_rule(r'[a-zA-Z_][a-zA-Z0-9_]*') def t_NAME(self, t): t.type = self.reserved.get(t.value.upper(), 'NAME') return t
11418748
import numpy as np from pylj import pairwise as heavy from pylj import forcefields as ff from numba import jit def initialise( number_of_particles, temperature, box_length, init_conf, timestep_length=1e-14, mass=39.948, constants=[1.363e-134, 9.273e-78], forcefield=ff.lennard_jones, ):...
11418932
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.ImageCollection('COPERNICUS/S2') \ .filterDate('2017-01-01', '2017-01-02').median() \ .divide(10000).visualize(**{'bands': ['B12', 'B8', 'B4'], 'min': 0.05, 'max': 0.5}) Map.setCenter(35.2, 31,...
11419010
import os import numpy as np import re # For cvode RHS output class DataSaver(object): comment_symbol = '# ' def __init__(self, sim, filename, entities=None): self.sim = sim self.filename = filename precision = 12 charwidth = 18 self.float_format = "%" + str(charwi...
11419025
import torch import torch.nn as nn class ChannelAttention(nn.Module): def __init__(self, in_planes, ratio=16): super(ChannelAttention, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc = nn.Sequential( nn.Conv2d(in...
11419047
import os import unittest from collections import namedtuple from unittest import mock from .. import * from mike.mkdocs_utils import docs_version_var class MockPlugins: BasePlugin = object # Mock importing `mkdocs.plugins`, since it can't be imported normally. real_import = __import__ with mock.patch('builtin...
11419048
import numpy, copy from scipy.optimize import linprog def run_lp(als, rotDir, dTdTau, dMzdTau, ndof, ncontrols, \ x_rotor, y_rotor, MzSurface, linp_dict ): """ This function uses a linear programming formulation to calculate the maximum thrust ratio and torque ratio for an eVTOL motor wrt nom...
11419059
import pathlib import subprocess from abc import ABC, abstractmethod from typing import Sequence from .exceptions import CommandNotFoundError, RunTargetFileNotSupported from .reporter import Reporter class CommandBase(ABC): @property @abstractmethod def name(self) -> str: ... @abstractmethod...
11419064
import io import pathlib import zipfile import requests import textwrap class ClientPortalGateway(): def __init__(self) -> None: """Initializes the client portal object. """ self._resources_folder = pathlib.Path(__file__).parents[1].joinpath( 'resources' ).resolve() def ...
11419069
import os import sys from copy import deepcopy import yaml def load(): try: with open('hamper.conf') as config_file: config = yaml.load(config_file) except IOError: config = {} config = replace_env_vars(config) # Fill in data from the env: for k, v in os.environ.item...
11419109
import json import logging from flask import jsonify, request, url_for from flask_restful import Resource from sqlalchemy import inspect from sqlalchemy.exc import NoInspectionAvailable from werkzeug.exceptions import BadRequest, NotFound from rdr_service import app_util from rdr_service.config import GAE_PROJECT fro...
11419123
from pyradioconfig.parts.bobcat.calculators.calc_viterbi import Calc_Viterbi_Bobcat from math import * class Calc_Viterbi_Sol(Calc_Viterbi_Bobcat): def calc_swcoeffen_reg(self, model): afc1shot_en = model.vars.MODEM_AFC_AFCONESHOT.value fefilt_selected = model.vars.fefilt_selected.value ...
11419130
from social.backends.rdio import RdioOAuth1 as RdioOAuth1Backend, \ RdioOAuth2 as RdioOAuth2Backend
11419135
from __future__ import print_function, division import os import numpy as np import warnings from astropy.io.votable import parse from astropy.io.votable.tree import VOTableFile, Resource, Field, Param from astropy.io.votable.tree import Table as VOTable from .exceptions import TableException from .helpers import sm...
11419136
import os import time import multiprocessing as mp import multiprocessing.pool import buzzard as buzz import numpy as np import scipy.ndimage import example_tools from part1 import test_raster def main(): return # None of the features shown here are implemented yet path = example_tools.create_random_elevatio...
11419143
class CLI(object): def __init__(self): self.modes = { 'request': self.request, 'response': self.response, 'parse': { 'request': self.parse_request, 'response': self.parse_response, } }
11419197
from {{ cookiecutter.underscored }} import example_function def test_example_function(): assert example_function() == 2
11419214
from ipykernel.comm import Comm from ipywidgets import Widget #----------------------------------------------------------------------------- # Utility stuff from ipywidgets tests # # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. #-----------------------------------...
11419243
import unittest from minfraud.request import maybe_hash_email class TestRequest(unittest.TestCase): def test_maybe_hash_email(self): tests = [ { "name": "no email", "input": {"device": {"ip_address": "1.1.1.1"}}, "expected": {"device": {"ip_addr...
11419269
from django.core.management.base import BaseCommand from daiquiri.core.constants import GROUPS from daiquiri.core.utils import setup_group class Command(BaseCommand): def handle(self, *args, **options): for name in GROUPS: group, created = setup_group(name) if created: ...
11419282
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_width_needs_to_be_one_or_more(self): with self.assertRaises(ValueError) as cm: Crossword(0, 10) self.assertEqual(str(cm.exception), "Width needs to be at least one") de...
11419288
import sublime, sublime_plugin, os ST3 = int(sublime.version()) >= 3000 class SublimeFileBrowserFixUpPaths(sublime_plugin.TextCommand): ''' usage: open console and run: view.run_command('sublime_file_browser_fix_up_paths') purpose: ensure that all paths end with os.sep ''' def run(self, ed...
11419293
import tensorflow as tf import numpy from scipy import misc import models def optimistic_restore(session, save_file): reader = tf.train.NewCheckpointReader(save_file) saved_shapes = reader.get_variable_to_shape_map() var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables() if var...
11419299
import nox.sessions PYTHON_VERSIONS = ['3.7', '3.8', '3.9'] SQLALCHEMY_VERSIONS = [ *(f'1.2.{x}' for x in range(0, 1 + 19)), *(f'1.3.{x}' for x in range(0, 1 + 24)), # '1.4.0b3', # not yet ] SQLALCHEMY_VERSIONS.remove('1.2.9') # bug nox.options.reuse_existing_virtualenvs = True nox.options.sessions = [...
11419310
from django.templatetags.static import static as get_static_url from django.shortcuts import redirect from .exceptions import UnknownMessageTypeError from .models import Dispatch from .signals import sig_unsubscribe_failed, sig_mark_read_failed def _generic_view(message_method, fail_signal, request, message_id, disp...
11419357
def find_missing_number(sequence): if not sequence: return 0 try: sequence = set(int(a) for a in sequence.split()) except ValueError: return 1 for b in xrange(1, max(sequence) + 1): if b not in sequence: return b return 0
11419380
import random while True: a=random.randint(1,100) b=None while a!=b: b=int(input("Guess a Number between (1-100): ")) if a<b: print("Your guess is too high") elif a>b: print("Your guess is too low") print("Congratulations! You gussed the number...
11419385
import unittest from tests.recipes.recipe_lib_test import BaseTestForMakeRecipe class TestLibxml2Recipe(BaseTestForMakeRecipe, unittest.TestCase): """ An unittest for recipe :mod:`~pythonforandroid.recipes.libxml2` """ recipe_name = "libxml2" sh_command_calls = ["./autogen.sh", "autoreconf", "./co...