filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_31051
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
the-stack_106_31052
# coding: utf-8 # # Copyright © 2012-2015 Ejwa Software. All rights reserved. # # This file is part of gitinspector. # # gitinspector is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
the-stack_106_31053
import unittest import pickle from common import MTurkCommon class TestHITPersistence(MTurkCommon): def create_hit_result(self): return self.conn.create_hit( question=self.get_question(), **self.get_hit_params() ) def test_pickle_hit_result(self): result = self.create_hit_result() new_resu...
the-stack_106_31054
import os import sys from math import gcd from functools import reduce # # Complete the getTotalX function below. # def lcm(a, b): a = int(a) b = int(b) return a * b / gcd(a,b) def lcms(numbers): return reduce(lcm, numbers) def dividedByB(b, factor): for i in b: if i % factor != 0: ...
the-stack_106_31057
from shu.kanunu import KanunuScraper from shu.base import Node class MyScraper(KanunuScraper): def get_title_and_links(self, doc): table = doc('dl') for anchor in table('dd a'): yield ( anchor.text_content(), str(self.base_url / anchor.get('href'))) ...
the-stack_106_31058
import sys import time from typing import Optional import click from chia.rpc.full_node_rpc_client import FullNodeRpcClient from chia.rpc.wallet_rpc_client import WalletRpcClient from chia.util.byte_types import hexstr_to_bytes from chia.util.config import load_config from chia.util.default_root import DEFAULT_ROOT_P...
the-stack_106_31059
import sys if sys.version_info.major == 2: # the `flatten` function can be found in compiler library: # `from compiler.ast import flatten` from collections import Iterable def flatten(iterable): for i in iterable: # if type(t) is list or type(t) is tuple: # strict check ...
the-stack_106_31060
#!/usr/bin/env python ################################################################################# # Copyright 2016-2019 ARM Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #...
the-stack_106_31062
""" # Copyright 2022 Red Hat # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
the-stack_106_31063
""" flask_excel ~~~~~~~~~~~~~~~~~~~ A flask extension that provides one application programming interface to read and write data in different excel file formats :copyright: (c) 2015-2017 by Onni Software Ltd and its contributors :license: New BSD License """ try: # if in py2 from urlli...
the-stack_106_31064
import math import os import pickle import shutil import tempfile from contextlib import contextmanager from itertools import permutations import pytest from numpy.testing import assert_almost_equal from pyproj import Geod try: from shapely.geometry import ( LinearRing, LineString, MultiL...
the-stack_106_31065
import logging import numpy as np import re logger = logging.getLogger(__name__) def strike_symbol(strike): R = np.zeros((2, 2)) R[0, 0] = np.cos(np.deg2rad(-strike)) R[0, 1] = -np.sin(np.deg2rad(-strike)) R[1, 0] = np.sin(np.deg2rad(-strike)) R[1, 1] = np.cos(np.deg2rad(-strike)) R = np.zer...
the-stack_106_31068
import json.encoder as json_encoder import types from json import JSONEncoder from typing import Final # noinspection PyUnresolvedReferences ENCODE_BASESTRING_ASCII: Final = json_encoder.encode_basestring_ascii # noinspection PyUnresolvedReferences ENCODE_BASESTRING: Final = json_encoder.encode_basestring # noinspecti...
the-stack_106_31069
import pytest from dataclasses import dataclass from uuid import uuid4 from tests.utils import ( do_rpc_call as do_rpc_call_fixture ) from asyncio_rpc.models import RPCCall, RPCStack from asyncio_rpc.client import WrappedException from asyncio_rpc.server import DefaultExecutor do_rpc_call = do_rpc_call_fixture...
the-stack_106_31070
import torch import torch.nn.functional as F import torch.optim as optim from torchvision.models import vgg16 import time import os import psutil import numpy as np from exp_config import random_input_generator, MONITOR_INTERVAL, NUM_ITERS, BATCH_SIZE, LERANING_RATE # set gpu_id 0 device = torch.device("cuda:0" if tor...
the-stack_106_31072
#-*- coding: UTF-8 -*- import theano import theano.tensor as T import numpy import cPickle class UsrEmbLayer(object): def __init__(self, rng, n_usr, dim, name, prefix=None): self.name = name if prefix == None: U_values = numpy.zeros((n_usr+1,dim),dtype=numpy.float32) U = ...
the-stack_106_31073
import Logs import Options import Utils class CompilerTraits(object): def get_warnings_flags(self, level): """get_warnings_flags(level) -> list of cflags""" raise NotImplementedError def get_optimization_flags(self, level): """get_optimization_flags(level) -> list of cflags""" raise NotImplementedError d...
the-stack_106_31075
# Copyright 2013-2014, Simon Kennedy, sffjunkie+code@gmail.com # # Part of 'hiss' the asynchronous notification library """ Currently the following schemes are supported ========= ================================ ``gtnp`` Growl Network Transfer Protocol ``pb`` Pushbullet ``po`` Pushover...
the-stack_106_31076
import unittest from hstest.check_result import correct from hstest.dynamic.dynamic_test import dynamic_test from hstest.dynamic.output.infinite_loop_detector import loop_detector from hstest.stage_test import StageTest from hstest.testing.tested_program import TestedProgram class InfiniteLoopTestNotWorking(StageTes...
the-stack_106_31077
''' Dshell external file class/utils for use in rippers, dumpers, etc. @author: amm ''' import os from dshell import Blob from shutil import move from hashlib import md5 ''' Mode Constants ''' FILEONDISK = 1 # Object refers to file already written to disk FILEINMEMORY = 2 # Object contains file contents in data m...
the-stack_106_31080
# qubit number=4 # total number=32 import pyquil from pyquil.api import local_forest_runtime, QVMConnection from pyquil import Program, get_qc from pyquil.gates import * import numpy as np conn = QVMConnection() def make_circuit()-> Program: prog = Program() # circuit begin prog += CNOT(0,3) # number=29 ...
the-stack_106_31083
import sys from sklearn.linear_model import Ridge import numpy as np from modules.utils import overlap_ratio class BBRegressor(): def __init__(self, img_size, alpha=1000, overlap=[0.6, 1], scale=[1, 2]): self.img_size = img_size self.alpha = alpha self.overlap_range = overlap self...
the-stack_106_31085
import tkinter as tk import tkinter.ttk as ttk import logging from cep_price_console.utils.log_utils import CustomAdapter, debug class CntrUploadTab (object): logger = CustomAdapter(logging.getLogger(str(__name__)), None) @debug(lvl=logging.NOTSET, prefix='') def __init__(self, master, tab_text, tab_stat...
the-stack_106_31087
import pathlib from setuptools import setup VERSION = '0.1.10' HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup(name='google_nest_sdm_jm', version=VERSION, description='Library for the Google Nest SDM API', long_description=README, long_description_content_...
the-stack_106_31088
import sys from typing import List, Any from argparse import ArgumentParser, Namespace, _SubParsersAction from pathlib import Path from os.path import join from utils import shellcode_encoder from cli.enums import SHELLCODE_HELP from inject import Injector def run(args: List[Any]): options = { "should_res...
the-stack_106_31089
""" This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as testing instructions are located at http://amzn.to/1LzFrj6 For additional samples, visit the Alexa Skills Kit Getting Started guide at http://amzn.to/1LG...
the-stack_106_31090
#!/usr/bin/env python import io import os # Imports the Google Cloud client library from google.cloud import vision from google.cloud.vision import types # get Image out of pillow from PIL import Image # Instantiates a client client = vision.ImageAnnotatorClient() if __name__ == "__main__": # The name of the ima...
the-stack_106_31094
import sys import py2app __all__ = ['infoPlistDict'] def infoPlistDict(CFBundleExecutable, plist={}): CFBundleExecutable = CFBundleExecutable NSPrincipalClass = ''.join(CFBundleExecutable.split()) version = sys.version[:3] pdict = dict( CFBundleDevelopmentRegion='English', CFBundleDispl...
the-stack_106_31096
import re import sqlite3 from datetime import datetime class GamePipeline: @classmethod def from_crawler(cls, crawler): settings = crawler.settings db = settings.get('DATABASE') drop = settings.getbool('DROP') return cls(db, drop) def __init__(self, db, drop): self...
the-stack_106_31098
# Process html tags from .state_inline import StateInline from ..common.html_re import HTML_TAG_RE from ..common.utils import charCodeAt def isLetter(ch: int): lc = ch | 0x20 # to lower case # /* a */ and /* z */ return (lc >= 0x61) and (lc <= 0x7A) def html_inline(state: StateInline, silent: bool): ...
the-stack_106_31099
import googleMapApiAdapter as gMapApi from loc import loc from RVGraph import RVGraph from RTVGraph import RTVGraph from assignTrips import AssignTrips class DynamicTripVehicleAssignmentMatcher: def __init__(self, constraints_param, useGridWorld=False): ''' constraints_param: { ...
the-stack_106_31100
# Import import numpy as np import time import json import torch import argparse from torch import nn from torch import optim import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms, models from PIL import Image device = torch.device('cuda:0' if torch.cuda.is_a...
the-stack_106_31101
import os for dirs in os.listdir(os.curdir): if os.path.isfile(dirs): continue count = 0 file1 = open(dirs + "/protection_curve.csv") for line in file1: count+=1 if count == 11: trident_11 = float(line) if count == 22: trident_22 = float(line) print(dirs + "," +str(trident_11) + "," +str(trid...
the-stack_106_31103
import pathlib import setuptools # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # This call to setup() does all the work setuptools.setup( name="rx-scheduler", version="0.0.1", description="Function interva...
the-stack_106_31105
#!coding: utf-8 import os import shutil import textwrap from . import engines from . import provision from .. import util from ..script import Script from ..script import ScriptDirectory from ..util.compat import get_current_bytecode_suffixes from ..util.compat import has_pep3147 from ..util.compat import u def _ge...
the-stack_106_31107
#runas solve(500) #pythran export solve(int) def solve(nfact): prime_list = [2, 3, 5, 7, 11, 13, 17, 19, 23] # Ensure that this is initialised with at least 1 prime prime_dict = dict.fromkeys(prime_list, 1) def _isprime(n): ''' Raw check to see if n is prime. Assumes that prime_list is already p...
the-stack_106_31108
# Search for lines that contain 'New Revision: ' followed by a number # Then turn the number into a float and append it to nums # Finally print the length and the average of nums import re fname = input('Enter file:') hand = open(fname) nums = list() for line in hand: line = line.rstrip() x = re.findall('New Re...
the-stack_106_31110
#@+leo-ver=5-thin #@+node:mork.20041010095009: * @file ../plugins/xsltWithNodes.py #@+<< docstring >> #@+node:ekr.20050226120104: ** << docstring >> """ Adds the Outline:XSLT menu containing XSLT-related commands. This menu contains the following items: - Set StyleSheet Node: - Selects the current node as the xsl...
the-stack_106_31111
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab from __future__ import unicode_literals, division, absolute_import, print_function from .compatibility_utils import PY2, bstr, utf8_str if PY2: range = xrange import os import struct # note: struct pack, unpack, unp...
the-stack_106_31112
# coding=utf-8 """SQLAlchemy session.""" from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from kombu.utils.compat import register_after_fork ModelBase = decl...
the-stack_106_31115
#!/usr/bin/env python3 # -*-coding:utf-8-*- import os import core.template content = """ Character sheet =============== Name: {name} Name again: {name} Age: {age} """ def test_get_tags(tmpdir): template_file = os.path.join(str(tmpdir.realpath()), 'test_template.md') with open(template_file, 'w') as ou...
the-stack_106_31116
#coding=utf-8 # Copyright (c) 2018 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
the-stack_106_31118
import sys import pytest import ibis from pandas.util import testing as tm pa = pytest.importorskip('pyarrow') import pyarrow.parquet as pq # noqa: E402 from ibis.file.parquet import ParquetClient, ParquetTable # noqa: E402 from ibis.file.client import ( FileDatabase, execute_and_reset as execute) # noqa: E402...
the-stack_106_31119
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import sys import click from polyaxon_cli.cli.check import check_polyaxonfile, check_polyaxonfile_kind from polyaxon_cli.cli.project import get_project_or_local from polyaxon_cli.client import PolyaxonClient from polyaxon_cli.cl...
the-stack_106_31123
""" Postgresql workload class """ import logging import random from prettytable import PrettyTable from ocs_ci.ocs.ripsaw import RipSaw from ocs_ci.utility.utils import TimeoutSampler, run_cmd from ocs_ci.ocs.utils import get_pod_name_by_pattern from ocs_ci.utility import utils, templating from ocs_ci.ocs.exceptions i...
the-stack_106_31125
"""Copyright 2020 ETH Zurich, Seonwook Park Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
the-stack_106_31126
'''Base sequence classes.''' import collections import coral from coral.sequence._sequence import Sequence from coral.constants.molecular_bio import COMPLEMENTS class NucleicAcid(Sequence): '''Abstract sequence container for a single nucleic acid sequence molecule.''' def __init__(self, sequence, materia...
the-stack_106_31128
# -*- coding: utf-8 -*- """ pygments.styles.native ~~~~~~~~~~~~~~~~~~~~~~ pygments version of my "native" vim theme. :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, ...
the-stack_106_31130
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Brian Coca <brian.coca+dev@gmail.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1....
the-stack_106_31133
# (c) 2012-2018, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your option) any later version. # ...
the-stack_106_31135
import glob import os import dill import matplotlib.pyplot as plt import mosaiks.config as c import numpy as np import pandas as pd import seaborn as sns from cartopy import crs as ccrs from matplotlib import ticker # plotting variables cs = c.world_app_order c_by_app = [getattr(c, i) for i in cs] applications = [co...
the-stack_106_31136
# -*- coding: utf-8 -*- __doc__="将Rhino中的Mesh 导入 Revit 中" from rpw.extras.rhino import Rhino as rc from pyrevit import forms ,DB,UI,_HostApplication,revit from RhinoToRevit import RhinoToRevit as RhToRe import rpw from rpw import db from rpw.ui.forms import FlexForm, Label, ComboBox, TextBox, TextBox,Separator, Button...
the-stack_106_31137
#!/usr/bin/python """ (C) Copyright 2020 Intel Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
the-stack_106_31138
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
the-stack_106_31143
import logging import sys import urllib.request import urllib.parse import urllib.error import requests from requests.auth import HTTPBasicAuth from six import string_types, text_type from redash.query_runner import * from redash.utils import json_dumps, json_loads try: import http.client as http_client except I...
the-stack_106_31145
import argparse import json def validate_parallel_run_config(parallel_run_config): max_concurrency = 20 if (parallel_run_config.process_count_per_node * parallel_run_config.node_count) > max_concurrency: print("Please decrease concurrency to maximum of 20 as currently AutoML does not support it.") ...
the-stack_106_31147
import argparse def parse_args(): parser = argparse.ArgumentParser( description='Mimic image or video in your terminal') parser.add_argument( 'path', type=str, help=('the path of the picture/video use "{0}" like "frame{0}.jpg" if ' 'the images name is frame1.jpg, f...
the-stack_106_31150
#!/usr/bin/env python # -*- coding: utf-8 -*- # 06/13/2021 # Author: Sian Xiao & Hao Tian """ Two examples for function atomCount 1PJ3: fileDirection = '../data/pockets/1PJ3_out/pockets/pocket1_atm.pdb' info = 'Chain A:GLN64,ARG67,ILE88,ARG91,LEU95; Chain B:PHE1127,ARG1128' return = 1...
the-stack_106_31151
""" @author: magician @file: card_demo.py @date: 2020/9/28 """ import collections import random Card = collections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: """ FrenchDeck """ ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() ...
the-stack_106_31152
from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from urllib import request from urllib.parse import urljoin, urlparse, quote from lxml import html import logging import redis import sys import os import re __r = redis.StrictRedis(host='localhost', port=6379, db=0) __pool =...
the-stack_106_31153
"""Adding new operation types Revision ID: 1cf750b30c08 Revises: e35c7cf01cb4 Create Date: 2021-11-02 23:51:07.308510 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1cf750b30c08' down_revision = 'e35c7cf01cb4' branch_labels = None depends_on = None def upgr...
the-stack_106_31155
# -*- coding: utf-8 -*- """ Created on Wed Apr 17 10:34:50 2019 @author: GAllison This script performs the overall task of creating a FracFocus database from the raw excel collection and creating the tables used to make data sets. Change the file handles at the top of core.Data_set_constructor to point to appropriat...
the-stack_106_31156
from corehq.apps.reports.filters.dates import DatespanFilter from corehq.apps.reports.standard import CustomProjectReport, ProjectReportParametersMixin, DatespanMixin from custom.intrahealth.filters import FicheLocationFilter2 from custom.intrahealth.reports.utils import IntraHealthLocationMixin, IntraHealthReportConfi...
the-stack_106_31157
"""Parallel coordinates plot showing posterior points with and without divergences marked.""" import numpy as np from scipy.stats import rankdata from ..data import convert_to_dataset from ..labels import BaseLabeller from ..sel_utils import xarray_to_ndarray from ..rcparams import rcParams from ..stats.stats_utils im...
the-stack_106_31161
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Nekozilla is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Nekozilla is distributed...
the-stack_106_31162
""" # SOURCE https://github.com/parzival-roethlein/prmaya # DESCRIPTION Temporarily sets (Panel > Show > types) while: - dragging the translate/rotate/scale tools - timeline dragging - timeline playback The purpose is to have a clear view of the deforming geometry Technical: Creates a scriptJob (SelectionChanged) a...
the-stack_106_31163
''' Переставить min и max ''' def exchangeMinMax(a): minEl = float('inf') minId = -1 maxEl = float('-inf') maxId = -1 for i in range(len(a)): if (a[i] > maxEl): maxEl = a[i] maxId = i if (a[i] < minEl): minEl = a[i] minId = i (a[m...
the-stack_106_31164
#!/usr/bin/env python # # DRAGONS # gempy.scripts # showpars.py # ------------------------------------------------------...
the-stack_106_31165
from typing import TYPE_CHECKING, Dict, List, Union from modules.base import K8sServiceModuleProcessor, LocalK8sModuleProcessor from modules.linker_helper import LinkerHelper from opta.core.kubernetes import create_namespace_if_not_exists, list_namespaces from opta.exceptions import UserErrors if TYPE_CHECKING: f...
the-stack_106_31166
"""The type file for image collection.""" from snovault import ( collection, load_schema, ) from .base import ( Item, # lab_award_attribution_embed_list ) from snovault.attachment import ItemWithAttachment @collection( name='images', unique_key='image:filename', properties={ 'titl...
the-stack_106_31171
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json from frappe.model.document import Document from frappe import _ class DeletedDocument(Document): pass @frappe.whitelist() d...
the-stack_106_31172
"""Functions to rescale data depending on the user's needs""" import numpy as np import pandas as pd from sklearn.preprocessing import scale ################################################################################ # Functions for pandas objects #################################################################...
the-stack_106_31175
# encoding='utf-8' ''' /** * This is the solution of No.79 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/word-search * <p> * The description of problem is as follow: * ========================================================================================...
the-stack_106_31176
"""`Domain models` setup script.""" import os import re from setuptools import setup from setuptools import Command # Getting description: with open('README.rst') as readme_file: description = readme_file.read() # Getting requirements: with open('requirements.txt') as version: requirements = version.readli...
the-stack_106_31179
import numpy as np import cv2 from enum import Enum class Models(Enum): ssd_lite = 'ssd_lite' tiny_yolo = 'tiny_yolo' tf_lite = 'tf_lite' def __str__(self): return self.value @staticmethod def from_string(s): try: return Models[s] except KeyError: ...
the-stack_106_31180
# -*- coding: utf-8 -*- """Functions for loading STARS and ACCACIA datasets of PMCs.""" from octant.core import OctantTrack import pandas as pd import mypaths def read_stars_file(fname=mypaths.starsdir / "PolarLow_tracks_North_2002_2011"): """Read data into a `pandas.DataFrame` from the standard file.""" d...
the-stack_106_31181
""" !!!!!!!!!!!!!!!!!!!!!!!!!!! DEPRECATED! DON'T USE THIS !!!!!!!!!!!!!!!!!!!!!!!!!!! This example is just here for aiding in migration to v0.2.0. see examples/napari_image_arithmetic.py instead """ from enum import Enum import numpy from napari import Viewer, gui_qt from napari.layers import Image from magicgui ...
the-stack_106_31183
from __future__ import print_function, absolute_import from future.standard_library import hooks import os import copy from shutil import rmtree from tempfile import mkdtemp from datetime import datetime from numpy import empty, float32, datetime64, timedelta64, argmin, abs, array from rasterio import open as rasopen...
the-stack_106_31184
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
the-stack_106_31185
import time import torch from transformer.transformer import Transformer if __name__ == '__main__': checkpoint = 'BEST_checkpoint.tar' print('loading {}...'.format(checkpoint)) start = time.time() checkpoint = torch.load(checkpoint) print('elapsed {} sec'.format(time.time() - start)) model = ...
the-stack_106_31186
import os import multiprocessing from ConfigParser import SafeConfigParser class Config(object): """ An object to load and represent the configuration of the current scraper. This loads scraper configuration from the environment and a per-user configuration file (``~/.scraperkit.ini``). """ def __ini...
the-stack_106_31187
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
the-stack_106_31189
import numpy as np import pandas as pd import re def stack_chunks(dat_list): ''' For preserving categories instead of converting to objects. If you concat categories w/ different levels (or even the same in a different order), it silently converts to object ''' columns, dtypes = dat_list[0].co...
the-stack_106_31190
""" Pairwise sequence alignment of Avidin with Streptavidin ======================================================= This script performs a pairwise sequence alignment of avidin (*Gallus gallus*) with streptavidin (*Streptomyces lavendulae*). """ # Code source: Patrick Kunzmann # License: BSD 3 clause import matplotl...
the-stack_106_31192
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'altgraph==0.17', 'asn1crypt...
the-stack_106_31193
class Animal: def __init__(self, kind, color, name): # constructor method/a new instance of animal # slef is like this from JS self.kind = kind self.name = name self.color = color def description(self): print("%s is a %s with color %s" % (self.name, self.kind, se...
the-stack_106_31194
"""Tests using pytest_resilient_circuits""" # -*- coding: utf-8 -*- # Copyright © IBM Corporation 2010, 2019 from __future__ import print_function, unicode_literals import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResu...
the-stack_106_31195
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # In this example, an image is centered at (0,0,0) before a # rotation is applied to ensure that the rotation occurs about # the center of the image. reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8,0.8,1.5)...
the-stack_106_31196
import json import logging from hashlib import sha1 from .score_cache import ScoreCache logger = logging.getLogger("ores.score_caches.redis") TTL = 60 * 60 * 24 * 365 * 16 # 16 years PREFIX = "ores" class Redis(ScoreCache): def __init__(self, redis, ttl=None, prefix=None): self.redis = redis ...
the-stack_106_31200
from xml.etree import ElementTree root = ElementTree.fromstring(input()) colors = {"red": 0, "green": 0, "blue": 0} def getcubes(root, value): colors[root.attrib['color']] += value for child in root: getcubes(child, value+1) getcubes(root,1) print(colors["red"], colors["green"], colors["blue"])
the-stack_106_31201
import re from asteval import Interpreter import astropy.units as u from astropy.modeling import models from qtpy.QtCore import QSortFilterProxyModel, Qt, Signal from qtpy.QtGui import QStandardItem, QStandardItemModel, QValidator class ModelFittingModel(QStandardItemModel): """ Internel Qt model containing ...
the-stack_106_31203
# Copyright (c) 2017 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
the-stack_106_31206
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: HJK @file: basic.py @time: 2019-05-07 """ """ Basic song object """ import os import re import datetime import logging import click import requests from . import config from .utils import colorize class BasicSong: """ Define the basic propert...
the-stack_106_31208
import sys import requests import json from random import randrange def updateMap(num = None): if(num is not None): #is parameter passed dictToSend = num else: dictToSend = str(randrange(1, 9)) #update using random number json.loads(dictToSend) #convert to json output = None try: res = requests.post('http...
the-stack_106_31209
from cv2 import flip from scipy.ndimage import rotate import numpy as np rotate_angles = [0, 90, 180, 270] def tta(image): images = [] for rotate_angle in rotate_angles: img = rotate(image, rotate_angle) if rotate_angle != 0 else image images.append(img) return np.array(images) def back_...
the-stack_106_31211
import os def make_tsv(metadata, save_path): metadata = [str(x) for x in metadata] with open(os.path.join(save_path, 'metadata.tsv'), 'w') as f: for x in metadata: f.write(x + '\n') # https://github.com/tensorflow/tensorboard/issues/44 image label will be squared def make_sprite(label_img...
the-stack_106_31212
from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from app.api import crud, deps, push, schemas from app.db.repository import Repository router = APIRouter() @router.get("/", response_model=List[schemas.BookInDBBase]) def get_books(db: Repository = Depends(deps.get_db)) -> Any: ...
the-stack_106_31213
import unittest import i18npy import os class TestModule(unittest.TestCase): def __init__(self, *args, **kwargs): global i18n super().__init__(*args, **kwargs) p = os.path.dirname(__file__) jp_translation_path = os.path.join(p, "translations/jp.json") i18n = i18npy.i18n_lo...
the-stack_106_31216
import numpy as np import torch import torch.nn.functional as F from torchdistlog import logging from scipy.special import comb # sklearn from sklearn.cluster import KMeans from sklearn.neighbors import NearestNeighbors from sklearn.decomposition import PCA # faiss try: import faiss except ModuleNotFoundError: ...
the-stack_106_31217
# -------------------------------------------------------- # SiamMask # Licensed under The MIT License # Written by Qiang Wang (wangqiang2015 at ia.ac.cn) # -------------------------------------------------------- import glob import time import sys sys.path.append("experiments/siammask_sharp") sys.path.append(".") from...