content
stringlengths
5
1.05M
import boto3 import time import server.server_plugins.resource_base as resource_base from server.common import constants from server.common import fm_logger # from server.dbmodule import db_handler TIMEOUT_COUNT = 400 fmlogger = fm_logger.Logging() class DynamoDBResourceHandler(resource_base.ResourceBase): de...
#!/usr/bin/env python import unittest from functools import reduce import numpy from pyscf import gto from pyscf import scf from pyscf import ao2mo from pyscf import fci mol = gto.Mole() mol.verbose = 0 mol.output = None#"out_h2o" mol.atom = [ ['H', ( 1.,-1. , 0. )], ['H', ( 0.,-1. ,-1. )], ['H'...
# pylint: disable=C0103 """ This module includes continuous-time models for a permmanent-magnet synchronous motor drive. The space-vector model is implemented in rotor coordinates. """ import numpy as np from helpers import complex2abc # %% class Drive: """ This class interconnects the subsyste...
import json import os import time import argparse import uuid import subprocess import sys import datetime import yaml from jinja2 import Environment, FileSystemLoader, Template import base64 import re import thread import threading import random import textwrap import logging import logging.config from multiproce...
''' HMMDeviceMap ''' from Products.DataCollector.plugins.CollectorPlugin import ( SnmpPlugin, GetMap ) class HMMDeviceMap(SnmpPlugin): ''' HMMDeviceMap ''' snmpGetMap = GetMap({ '.1.3.6.1.4.1.2011.2.82.1.82.2.2001.1.15.0': 'shelfSerialNumber', }) def proc...
"""Question: https://leetcode.com/problems/palindrome-number/ """ class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False copy, reverse = x, 0 while copy: reverse *= 10 reverse += copy % 10 copy = copy // 10 ...
import os os.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"] = "1" import numpy as np np.random.seed(1) import random random.seed(1) import pandas as pd import cv2 import timeit from os import path, makedirs, listdir import sys sys.setrecursionlimit(10000) from...
from handlers.group import GroupHandler from handlers.travel import TravelHandler, TrainingHandler from handlers.travel_result import TravelResultHandler
#!/usr/bin/python ###################################################################### # Ascii TMS Viewer # #-------------------------------------------------------------------- # Brian Hone | Initial Release #-------------------------------------------------------------------- # ...
# import lib.forest as forest import math import random import numpy as np import pandas as pd from lib.tree import Tree from lib.forest import RNF from lib.evalMetrics import * from sklearn.utils import shuffle import sys def cross_val_tree(df, tries): for i in range(tries): shuffle = df.sample(frac=1) ...
filename=input("Enter the File name:") i=filename.index('.') ext=filename[i+1:] di={"py":"Python","m":"matlab","doc":"document","jpg":"image","sch":"Pspice schematics","mp4":"video","mp3":"audio"} for j in di: if j==ext: print("The extension of the file is:",di[j]) break else: c...
from subprocess import Popen, DEVNULL import time if __name__ == '__main__': start_id = 5000 step = 1000 g_len = 1 while True: start = time.time() p_list = list() for i in range(g_len): p = Popen(['python', 'pikabu_parser_basic.py', str(start_id + (i)*step), str(sta...
import pytest from django.core.exceptions import ValidationError from zinc.models import Policy @pytest.mark.django_db def test_policy_name_validation_not_unique_first_chars(): Policy(name="dev01").save() with pytest.raises(ValidationError): Policy(name="dev011").full_clean() Policy(name="dev022...
# -*- coding: utf-8 -*- # # (c) 2016 Hareau SAS / Weenect, https://www.weenect.com # # This file is part of the weedi library # # MIT License : https://raw.githubusercontent.com/weenect/weedi/master/LICENSE.txt import os import unittest import weedi.exc import project.repository as repository import project.services...
import os from flask import Flask import db def create_app(test_config=None): # 创建、编译app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'my-easy-pic-bed.sqlite'), ) # ensure the instance fold...
# Copyright 2018 Northern.tech AS # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`quaternion` ================== .. module:: quaternion :platform: Unix, Windows :synopsis: .. moduleauthor:: hbldh <[email protected]> Created on 2015-06-03, 21:55 """ from __future__ import division from __future__ import print_function from _...
import sqlite3 def upper_word(raw): return raw.upper() conn = sqlite3.connect(':memory:') conn.create_function('upper', 1, upper_word) cur = conn.cursor() cur.execute('CREATE TABLE users (first_name char(20))') cur.execute('INSERT INTO users(first_name) VALUES ("Ivan"), ("Peter"), ("Mike")') cur.execute('SELECT...
from __future__ import annotations from typing import Optional __author__ = "Anton Höß" __copyright__ = "Copyright 2021" class ConnTemplate: def __init__(self, in_block_id: str, in_block_pin: int, out_block_id: str, out_block_pin: Optional[int]): self.__in_block_id: str = in_block_id self.__in_b...
x = input("Comando:") y = 20 for y in range(0, 20): print("[+]Testing http://mercury.picoctf.net:55079/") print("picoCTF{th4ts_4_l0t_0f_pl4c3s_2_lO0k_d375c750}")
# Copyright 2016 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...
# # Copyright (c) 2019-2020 Google LLC. All Rights Reserved. # Copyright (c) 2016-2018 Nest Labs 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 # # ...
# # SPDX-License-Identifier: MIT # import os import re import time import logging import bb.tinfoil from oeqa.selftest.case import OESelftestTestCase from oeqa.utils.commands import runCmd class TinfoilTests(OESelftestTestCase): """ Basic tests for the tinfoil API """ def test_getvar(self): with bb....
import yaml, re converter = { "int" : "std::to_string", "int32_t" : "std::to_string", "uint32_t" : "std::to_string", "int64_t" : "std::to_string", "uint64_t" : "std::to_string", "user_addr_t" : "std::to_string", "user_size_t" : "std::to_string", "dev_t" : "std::to_string", "es_...
# -*- coding: utf-8 -*- """ Created on Wed Nov 15 22:15:35 2017 @author: Stuart """ vessels = {} import json with open('facility_assumptions.json', 'r') as j: d = json.load(j) vessels = d["Vessels"] print(vessels)
# # Copyright (C) 2020-2021 Arm Limited or its affiliates and Contributors. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Definition of an SPDX File.""" from pathlib import Path from spdx.checksum import Algorithm from spdx.document import License from spdx.file import File, FileType from typing impo...
class DoiExcelData: _criteria1="" _criteria2="" _criteria3="" _criteria="" _total_issued_shares_underly_com_ht=0 _disclosure="" _is_disclosure_3_pct="" _is_disclosure_5_pct="" _company_date="" _long_short="" _business_unit="" _name_of_report_entity="" _name_of_sec_bro...
#!/usr/bin/env python import os import webapp2 from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import db #Data store model class GeoLocation(db.Model): user = db.UserProperty() date = db.DateTimeProperty(auto_now_add = True) #GeoPt object wh...
import os from ehive.runnable.IGFBaseProcess import IGFBaseProcess from igf_data.igfdb.collectionadaptor import CollectionAdaptor from igf_data.utils.tools.ppqt_utils import Ppqt_tools from igf_data.utils.fileutils import get_datestamp_label from igf_data.utils.analysis_collection_utils import Analysis_collection_utils...
import os,sys sys.path.append('/usr/local/lib/python2.7/site-packages') import pandas as pd import numpy as np import gym from keras.models import Sequential from keras.layers import Activation,Dense from keras.optimizers import Adam import random import time from gym import spaces import matplotlib.pyplot as plt #Wit...
#!/usr/bin/env python import rospy from SensorsListener import SensorsListener #import motores class Refletancia(): def __init__(self, sl): self.sl = sl def maisEsqBranco(self): return self.sl.getRefle(0) > 4 def esqBranco(self): return self.sl.getRefle(1) > 4 def dirBranco(self): return self...
""" Copyright 2020 The OneFlow 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 applicable law or agr...
""" Tests for salt.utils.boto3mod """ import random import string import salt.loader import salt.utils.boto3mod as boto3mod from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, s...
s = 0 for i in range(0,501): if(i%2 != 0): if(i%3 == 0): s += i print('A soma dos impares multiplos de 3 foi: {}'.format(s))
#!/usr/bin/env python # -*- coding: utf-8 -*- """errors.py """ __all__ = ( 'error_500' ) from flask import render_template def error_500(error): """ Called when an internel server error (500) occured when responding to a request. """ return render_template( 'errors/500.html', e...
import demistomock as demisto # noqa import ExpanseRefreshIssueAssets EXAMPLE_INCIDENT = { 'CustomFields': { 'expanseasset': [ {'assettype': 'Certificate', 'assetkey': 'fakeMD5', 'id': 'id-old-certificate'}, {'assettype': 'IpRange', 'assetkey': 'fakeIPRange', 'id': 'id-old-iprang...
import random from . import tokens from . import dealer """ The Button module manages the movement of the Dealer Button. """ class Button(tokens.Token): def __init__(self, table): tokens.Token.__init__(self, name="Button", table=table) self.seat = -1 # Start at -1 or None? def __repr__(sel...
''' =============================================================================== -- Author: Hamid Doostmohammadi, Azadeh Nazemi -- Create date: 01/11/2020 -- Description: This code is for T-distributed Stochastic Neighbor Embedding (t-SNE) which is a method for redcuing dimension for image...
from run.cochran import run_benchmark from . import benchmark_utils as bm_utils import subprocess #Performs the list of benchmarks and saves to results to output csv file def perform_benchmarks(benchmarks, experiment_iterations, output_file): statistics, csv_output = bm_utils.setup(output_file) benchmark_count...
''' 黑名单中的随机数 给定一个包含 [0,n) 中不重复整数的黑名单 blacklist ,写一个函数从 [0, n) 中返回一个不在 blacklist 中的随机整数。 对它进行优化使其尽量少调用系统方法 Math.random() 。 提示: 1 <= n <= 1000000000 0 <= blacklist.length < min(100000, N) [0, n) 不包含 n ,详细参见 interval notation 。 示例 1: 输入: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] 输出:[null,0,0,0] 示例 2: 输入: ["...
from django.contrib import admin from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets from armstrong.core.arm_sections.admin import SectionTreeAdminMixin from armstrong import hatband from armstrong.apps.related_content.admin import RelatedContentInline from .models import Ar...
from train import ex def main(): batch_size = 8 sequence_length = 327680 model_complexity = 48 piano_midis = list(range(8)) guitar_midis = list(range(24, 32)) bass_midis = list(range(32, 40)) brass_midis = list(range(57, 64)) reed_midis = list(range(64, 72)) ex.run( confi...
from django import forms #formulario no html de produtos class Produtos(forms.Form): nome = forms.CharField(label='Nome ') quantidade = forms.IntegerField(label='Quantidade ') preco = forms.IntegerField(label='Preço')
FALSE = 0 Enc_FALSE = b'\x00' TRUE = 1 Enc_TRUE = b'\x01' NULL = 2 Enc_NULL = b'\x02' INF = 3 Enc_INF = b'\x03' NEGINF = 4 Enc_NEGINF = b'\x04' NAN = 5 Enc_NAN = b'\x05' TERMINATED_LIST = 0x0c Enc_TERMINATED_LIST = b'\x0c' CUSTOM = 0x0e Enc_CUSTOM = b'\x0e' TERMINATOR = 0x0f Enc_TERMINATOR = b'\x0f' INT = 0x20 NEGINT =...
import numpy import numpy.fft import numpy.ma import math import scipy.stats import scipy.interpolate import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) def rect_make_FFT(rect_half_length, beta, outer_scale, sigma, m_func=None, s_func=None, scale_ratio=None, ...
""" Define testing utils """ IMAGE = "895885662937.dkr.ecr.us-west-2.amazonaws.com/spark/emr-5.32.0-20210129:2.4.7-amzn-0-vanilla" RELEASE_NAME = "emr-5.32" IMAGE_TYPE = "spark" INSPECT = dict() INSPECT['Id'] = 'sha:asdf' INSPECT['Created'] = '2020/04/22' INSPECT['Config'] = dict() INSPECT['Config']['User'] = 'user' ...
#!/usr/bin/env python3 -u import time import sys from vwradio import avrclient from vwradio.constants import Keys client = avrclient.make_client() if __name__ == '__main__': # build list of keycodes to try (one bit per key, max 32 bits) keycodes = [] keycode = 1 while len(keycodes) < 32: keyco...
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test ping message """ import time from test_framework.messages import ( msg_pong, ) from test_framewor...
import yaml from serilizer_lib.parsers.yaml.yaml_config import * #own parser # def dumps(s): # pass # # # def dump(s, fp): # pass # # # def load(fp): # pass # # # def loads(s): # # strings = s.split("\n") # ind = 0 # depth = 0 # def parse_obj(dep): # ans = {} # nonlocal stri...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from bottledaemon import daemon_run from bottle import route, request import time import os @route("/hello") def hello(): return "hello :: {0}\n".format( ...
from . import wrapper from .. util import log import random as rand class Sequence(wrapper.Indexed): def __init__(self, layout, random=False, length=None, **kwds): """ Arguments random -- If True, a random animation is selected each step length -- if length is a number, run all th...
#coding: utf-8 import argparse import os from solver import lightsoutsolver from solver import f2 from utils import validator if __name__ == '__main__': parser = argparse.ArgumentParser(description='LightsOut Solver') parser.add_argument('-s', type=int, choices=validator.range_check(low_limit=2), help='Lights...
#!/usr/bin/env python # # Copyright (c) 2014 10X Genomics, Inc. All rights reserved. # # Measure coverage in give regions # import tenkit.pandas as pd import numpy as np import tenkit.bio_io as tk_io import tenkit.bam as tk_bam import tenkit.stats as tk_stats import martian import tenkit.hdf5 as tk_hdf5 def mean_cover...
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os from appengine_wrappers import GetAppVersion from compiled_file_system import CompiledFileSystem from copy ...
from rabbitai.db_engine_specs.base import BaseEngineSpec, LimitMethod class TeradataEngineSpec(BaseEngineSpec): """Dialect for Teradata DB.""" engine = "teradata" engine_name = "Teradata" limit_method = LimitMethod.WRAP_SQL max_column_name_length = 30 # since 14.10 this is 128 _time_grain_e...
# Interaction of .pend_throw() with .throw() and .close() def gen(): i = 0 while 1: yield i i += 1 g = gen() try: g.pend_throw except AttributeError: print("SKIP") raise SystemExit g.pend_throw(1) try: g.throw(ValueError()) except ValueError: print("expected ValueError #1...
from .stream_interface import WbvalveStreamInterface __all__ = ['WbvalveStreamInterface']
# Microsoft Azure Linux Agent # # Copyright 2014 Microsoft Corporation # Copyright (c) 2016, 2017 by Delphix. All rights reserved. # Copyright 2019 Joyent, Inc. # # 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 ...
def perm(l): # error: first line indented for i in range(len(l)): # error: not indented s = l[:i] + l[i+1:] p = perm(l[:i] + l[i+1:]) # error: unexpected indent for x in p: r.append(l[i:i+1] + x) return r # error: incons...
from discord.ext import commands from discord.utils import get import discord import sys import subprocess import asyncio import datetime import re import random import requests import json import os if not os.path.isfile("settings.json"): sys.exit("'settings.json' not found!") else: with open("settings.json")...
# Copyright (c) 2021 - Jojo#7791 # Licensed under MIT import logging from typing import Dict, Iterable, Optional, Union from discord import Guild, Member, Role, User from redbot.core import Config from redbot.core.bot import Red from ...const import _config_structure # type:ignore __all__ = [ "add_to_blacklist...
from guard import Community, polity, default_parameters, generate_parameters import pytest @pytest.fixture def polity_10(): state = polity.Polity( [Community(default_parameters) for i in range(10)] ) return state @pytest.fixture def arbitrary_polity(): def _arbitrary_polity(size): ...
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import UnivariateSpline n, c, gflops = np.loadtxt('triad.txt', unpack=True) spline = UnivariateSpline(n, np.log10(gflops)) #spline.set_smoothing_factor(0.5) plt.semilogx(n, gflops, 'ko') #plt.semilogx(n, 10**spline(n), 'k', alpha=0.5) plt.xlabe...
import os import re import cv2 import torch import imgaug import numpy as np import matplotlib.pyplot as plt from termcolor import colored from imgaug import augmenters from torchvision import transforms from torch.utils.data import Dataset from torch.utils.data import DataLoader as DL from sklearn.model_selection imp...
import unittest import json from webhook import create_app from unittest.mock import call from unittest.mock import patch class TestRoadLocation(unittest.TestCase): @patch('webhook.views.rabbit', spec=['channel']) @patch('webhook.views.requests', spec=['post']) def test_location(self, request_mock, rabbi...
from random import randint from asciimatics.screen import Screen import time def demo(screen): for i in range(1,12953): with open("output/output"+str(i)+".txt",'r') as f: lines = f.readlines() count = 0; for line in lines: screen.print_at(line,0,count) ...
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../../..', 'wikidump')) import collections from wikidump.extractors import user_warnings_template INPUT_TEXT = """ <includeonly>This is a sample template</includeonly> <includeonly><noinclude>This is a sample template</noinclude> part 2</includeon...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import namedtuple, defaultdict, OrderedDict import logging import cgi import re import datetime log = logging.getLogger(__name__) class FragmentElement(object): pa...
lines = open('day-19.input') rules= {} messages = [] parsing_rules = True lines = enumerate(lines) while True: line = next(lines, None) if line == None: break line = line[1].strip() if line == '': parsing_rules = False continue if parsing_rules: tokens = line.spli...
from .login import loginPage from ..models import AccessAttemptAddons from axes.models import AccessAttempt from django.contrib import messages from django.shortcuts import redirect import datetime """ Authors: Conor Behard Roberts Description: Converts timedelta object into a readable string """ def strfdelta...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ============================================================================ # Nomen - Multi-purpose rename tool # Common core module # Copyright (C) 2018 by Ralf Kilian # Distributed under the MIT License (https://opensource.org/licenses/MIT) # # GitHub: https://github...
# -*- coding: utf-8 -*- from locust import task,TaskSet import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) import config from common.util import foreach,load_modules,Weight from behavior.client import Client # @task def stop(self): self.interrupt() def add_stop(cls): cls._stop...
import re from os import symlink from os.path import join as pjoin import os import shutil from .utils import (temp_working_dir, temp_dir, working_directory, eqsorted_, cat, assert_raises) from .test_ant_glob import makefiles from .. import links from ..links import (silent_makedirs, silent_unlink, silent_abs...
import pprint import re # noqa: F401 import six class StartWorkflowRequest(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name a...
from flask import Flask from flask import request from hildebrand import Glow app = Flask(__name__) glow = Glow() @app.route('/metrics') def Main(): return( "timestamp " + str(glow.getElecCurrent['data'][0][0]) + "\nconsumption " + str(glow.getElecCurrent['data'][0][1])) if __name__ == "__main__": app....
import numpy as np from utils import * def select_node_to_expand(tree, state_space): state_space = np.asarray(state_space) space_origin, space_range = state_space n_dim = len(space_origin) # sample a random point in the space random_point = np.random.rand(2) * space_range[0:2] # theta = np.ra...
#!/usr/bin/env python3 """Exporter of snippets for snippet crawler""" from BaseLogger import BaseLogger from DatabaseAccessor import DatabaseAccessor from contextlib import closing from csv import DictWriter from json import dump from os import remove from platform import node from time import strftime from zipfile im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # Хронология выхода игр from common import get_parsed_two_column_wikitable def is_match_table_func(table) -> bool: return 'TIMELINE OF RELEASE YEARS' in table.caption.text.strip().upper() url = 'https://en.wikipedia.org/wiki/The_Elder_S...
import unittest import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from tests.constants import INPUT_DATA_DIR from pm4py.log.importer import csv as csv_importer from pm4py.log.importer.utils im...
######################################## # CS/CNS/EE 155 2017 # Problem Set 5 # # Author: Avishek Dutta # Description: Set 5 ######################################## class Utility: ''' Utility for the problem files. ''' def __init__(): pass @staticmethod def load_sequence(n): ...
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your...
#!/usr/bin/env python # -*- coding: utf8 -*- from string import ascii_uppercase as up def solve(passwd): if len(passwd) < 2: return 'IMPOSSIBLE' for i in passwd: if passwd.count(i) > 1: return up sol = passwd[::-1] for i in up: if i not in sol: sol+=i return sol for case in range(int(input())): p...
a = [1,2,3,4] print a
###################################################################################################################### # 这次例子就是ORM的简单实现,重要部分已做注释 class Field(object): def __init__(self, name, type): print('Field name:',name) self.name = name self.type = type def __str__(self): re...
from typing import Dict, Any, Union, List import sys import math import pytorch_lightning as pl import torch import torch.nn.functional as F from torch import nn from deperceiver.datamodules import get_coco_api_from_dataset from deperceiver.metrics.coco_eval import CocoEvaluator from deperceiver.util.misc import Nest...
#!/usr/bin/env python3 import os import re curdir = os.path.dirname(os.path.realpath(__file__)) mem = {} def apply_mask(value, mask): ones_mask = int("".join(["1" if b=="1" else "0" for b in mask]), base=2) zeros_mask = int("".join(["0" if b=="0" else "1" for b in mask]), base=2) return (value|ones_mask...
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2021 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`484`-compliant **new type hint utilities** (i.e., callables generically applicable to :pep:`484`-compliant types...
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """Updating counts. """ #end_pymotw_header import collections c = collections.Counter('abcdaab') for letter in 'abcde': print '%s : %d' % (letter, c[letter])
# # Class for electron-migration limited SEI growth # import pybamm from .base_sei import BaseModel class ElectronMigrationLimited(BaseModel): """ Class for electron-migration limited SEI growth. Parameters ---------- param : parameter class The parameters to use for this submodel rea...
import logging from tellus.configuration import ( TELLUS_USER_MODIFIED, TELLUS_GO, TELLUS_ABOUT_TELL, TELLUS_USER, TELLUS_INTERNAL, TELLUS_APP_USERNAME, ) from tellus.sources import Source from tellus.tell import Tell from tellus.tells import TheresNoTellingException from tellus.tellus_sources....
from django.apps import AppConfig class ExportappConfig(AppConfig): name = 'django_exportapp' def ready(self): # super().ready() self.module.autodiscover_wrapper() # debug from .helper import exporter # print(exporter) # for i in exporter.list(): # ...
class TorsionList(list): def __init__(self, pose, torsion_setter, *args, **kwargs): self.pose = pose self.torsion_setter = torsion_setter super().__init__(*args, **kwargs) def __setitem__(self, index, value): if isinstance(index, int): if index >= 0: ...
if __name__ == '__main__': import os import time import RPi.GPIO as GPIO import systemd.daemon GPIO.setmode(GPIO.BOARD) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) systemd.daemon.notify('READY=1') while True: if GPIO.input(16) == GPIO.HIGH: os.system('/usr/bi...
from os import environ domain_root = environ.get('DOMAIN_ROOT') http_protocol = environ.get('HTTP_PROTOCOL', 'https') config = { 'SECRET_KEY': environ['SECRET_KEY'], 'HONEYCOMB_WRITEKEY': environ.get('HONEYCOMB_WRITEKEY', None), 'HONEYCOMB_DATASET': environ.get('HONEYCOMB_DATASET', 'rws'), 'HONEYCOMB_...
# # 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 agreed to in writing, software # ...
"""Geometry-related objects.""" import logging from math import pi, sqrt from more_itertools import pairwise import arcpy LOG = logging.getLogger(__name__) """logging.Logger: Module-level logger.""" RATIO = { "meter": { "foot": 0.3048, "feet": 0.3048, "ft": 0.3048, "yard": 0.914...
import unittest from yaml_interpreter import YAMLInterpretor class LoadYamlTest(unittest.TestCase): def setUp(self): self.si = YAMLInterpretor(fill_with_none=False) def test_load_yaml_to_2d_list(self): yaml = ''' a: x: 1 y: 2 ''' res = self.si.loa...
from django.contrib.admin import SimpleListFilter from django.contrib.redirects.models import Redirect from link_report import link_report_settings from .models import Sentry404Event class UrlListFilter(SimpleListFilter): title = 'Internal or External Source?' parameter_name = 'is_internal' def...
import numpy as np from tensorflow.keras import regularizers, Sequential, Model, Input from tensorflow.keras.layers import Dense, Flatten, Reshape from detectors.single_image_based_detectors.abs_single_image_autoencoder import AbstractSingleImageAD from detectors.single_image_based_detectors.autoencoder_batch_generato...
from dynatrace.main import Dynatrace from dynatrace.http_client import TOO_MANY_REQUESTS_WAIT