text
stringlengths
2
999k
from scipy import interpolate import numpy as np import matplotlib.pyplot as plt # z kolika vyorku udelam orezanou funkci samples = 6 # jakeho radu chci interpolacni polynom order = 4 inter_functions = [] # orezana osa x x_axis = np.linspace(0, 2 * np.pi, samples) # poctiva osa x se spoustou vzorku x_axis_true = np.li...
#!/usr/bin/env python # # Test hook to launch an irker instance (if it doesn't already exist) # just before shipping the notification. We start it in in another terminal # so you can watch the debug messages. Intended to be used in the root # directory of the irker repo. Probably only of interest only to irker # develo...
from __future__ import absolute_import from __future__ import division import argparse import sys import pwnlib pwnlib.args.free_form = False from pwn import * from pwnlib.commandline import common parser = common.parser_commands.add_parser( 'scramble', help = 'Shellcode encoder' ) parser.add_argument( ...
import time import pickle import uuid from taskue.utils import logging from redis import Redis from taskue.utils import RedisKeys from taskue.task import Task, TaskStatus class WorkflowStatus: CREATED = "Created" QUEUED = "Queued" RUNNING = "Running" PASSED = "Passed" FAILED = "Failed" DONE_ST...
from argparse import ArgumentParser, RawTextHelpFormatter from typing import Optional, Tuple import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.python.distribute.tpu_strategy import TPUStrategy import _path # noqa from imagemodel.common.reporter import PredictorReporter from imagemodel...
""" Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1:...
import time from functools import wraps def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """ Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/Py...
"""Common helper functions for typing and general numpy tools.""" import numpy as np from .utils import get_aliasing, check_boolean _alias_numpy = { np.add: 'sum', np.sum: 'sum', np.any: 'any', np.all: 'all', np.multiply: 'prod', np.prod: 'prod', np.amin: 'min', np.min: 'min', np.m...
import subprocess import sys import re import os repo_name_regex = r"^[_\-a-zA-Z0-9]+$" repo_name = "{{ cookiecutter.repo_name }}" initiate_repo = "{{ cookiecutter.initiate_repo }}" create_conda_env_config = "{{ cookiecutter.create_conda_env_config }}" conda_env_config_file = f"{repo_name}-env.yml" if not re.match(r...
import os, sys sys.path.insert(0, os.path.join("..","..")) from nodebox.graphics.context import * from nodebox.graphics import * # This example uses the points method to connect letters together. # It actually draws lines between points of each letter contour # that are a certain distance from eachother. def draw(ca...
import numpy as np class RandomAction: def __init__(self, all_actions: int): self.all_actions = all_actions def __call__(self, population): return np.random.randint(self.all_actions)
''' Module for reading SMART attribute values from hard drives. Requires smartctl.''' import subprocess def read_smart(dev): s = subprocess.Popen(['smartctl', '-A', dev], stdout=subprocess.PIPE).stdout.read() s = s.decode('utf-8') lines = s.split('\n') header = lines[6] global positions posit...
# 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 file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from utils import get_data, answers, print_answers from operator import itemgetter data = get_data(2020, 5).split('\n') find_highest = [] for ticket in data: count = 10 find_row = list(range(0, 128)) find_col = list(range(0, 8)) for t in ticket: if count > 0: r_ind = int(len(find_r...
from Neuron import Neuron from NeuronLayer import NeuronLayer from NeuronNetwork import NeuronNetwork import random # onderstaande gegevens zijn op basis van de uitwerkingen van les 6. print("andGate") o = Neuron([random.uniform(-1, 1), random.uniform(-1, 1)], random.uniform(-1, 1)) # [-0.5, 0.5], 1.5 OR [1, 1], -1....
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.common import Backend from lib.core.common import getLimitRange from lib.core.common import isAdminFromPrivileges from lib.core.common import isInferenceAvailabl...
# Lint as: python3 # Copyright 2021 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...
# qubit number=5 # total number=43 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 += H(0) # number=3 pr...
# from dask_ml.preprocessing import DummyEncoder from optimus.helpers.check import is_spark_dataframe from optimus.helpers.columns import parse_columns, name_col, get_output_cols, prepare_columns from optimus.helpers.constants import Actions from optimus.helpers.raiseit import RaiseIt from optimus.infer import is_, is...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ############################################################################# # Copyright (c): 2021, Huawei Tech. Co., Ltd. # FileName : source.py # Version : # Date : 2021-4-7 # Description : ##################################################################...
# vim: expandtab:ts=4:sw=4 from __future__ import absolute_import import numpy as np from . import linear_assignment def iou(bbox, candidates): """Computer intersection over union. Parameters ---------- bbox : ndarray A bounding box in format `(top left x, top left y, width, height)`. can...
# Created July 2015 # TEASER Development Team """ This script loads the VDI 6007 Room 8 as *.teaserjson and computes parameters. The parameters are then compared with the ones from Rouvel """ from teaser.project import Project import teaser.logic.utilities as utilities def parameter_room8(): prj = Project(Fals...
import vim from . import breakpoint from . import event from . import opts from . import session from . import util from .ui import vimui class DebuggerInterface: """Provides all methods used to control the debugger.""" def __init__(self): self.breakpoints = breakpoint.Store() self.ui = vimui...
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode try: from urllib.parse import parse_qs, urlsplit except ImportError: from urlparse import parse_qs, urlsplit import uuid from django.contrib.auth.models import AnonymousUser from django.core.management import call_...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ The DE0 Nano does not have an explicit USB port. Instead, you'll need to connect an external ULPI PHY breakout, such as https://www.waveshare.com/wiki/USB3300_USB_HS_Board. ...
#!/usr/bin/env micropython from rubikscolorresolver import resolve_colors import sys resolve_colors(sys.argv)
from nonebot import on_command , CommandSession import requests from nonebot.permission import * __plugin_name__ = '图书馆抢座' __plugin_usage__ = r""" 图书馆抢座 1.状态查询 作用:显示当前图书馆各自习室人数 格式:状态查询 以下功能需要先私聊机器人,发送:图书馆 1.我的当前状态 作用:显示你的图书馆预约最新状态 格式:预约状态 2.抢座 作用:自动抢座(如果检测到有座位直接抢) 格式:抢座 3.取消预约 作用:取消当前预约的座位 格式:取消预约 """ base_url = '...
# -*- coding: utf-8 -*- # This information is located in its own file so that it can be loaded # without importing the main package when its dependencies are not installed. # See: https://packaging.python.org/guides/single-sourcing-package-version __author__ = """Nils Hempelmann""" __email__ = 'info@nilshempelmann.de...
from unittest import TestCase from bricklayer.utils.commands import open_ldd_command import platform import mock class CommandsTest(TestCase): def test_it_creates_the_right_windows_command(self): with mock.patch('platform.system',return_value='Windows'): self.assertEquals(open_ldd_command("fil...
# Copyright (c) 2020 PaddlePaddle 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 app...
import os import subprocess import sys kolibri_dir = os.path.abspath(os.path.join('src', 'kolibri')) win_dir = os.path.abspath(os.path.join('dist', 'win', 'Kolibri')) kolibri_dest_dir = os.path.join(win_dir, 'kolibri') from .version import get_env_with_version_set def do_build(args): if 'android' in args and '-...
"""chatapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
import random n1 = str(input('Nome do primeiro Aluno: ')) n2 = str(input('Nome do segundo Aluno: ')) n3 = str(input('Nome do terceiro Aluno: ')) n4 = str(input('Nome do quarto Aluno: ')) lista = [n1,n2,n3,n4] escolhido = random.choice(lista) print('O Aluno escolhido foi {} .'.format(escolhido))
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest import salt.exceptions import saltext.vmware.utils.cluster as utils_cluster from pyVmomi import vim def test_get_clusters(service_instance, integration_test_config): datacenter_name = list(integration_test_config["datacenters"].keys...
from test import support from test.support import bigmemtest, _4G import unittest from io import BytesIO, DEFAULT_BUFFER_SIZE import os import pickle import glob import tempfile import pathlib import random import shutil import subprocess import threading from test.support import unlink import _compression import sys ...
import sys import io import httplib2 import os from mimetypes import MimeTypes from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import AccessTokenRefreshError, flow_from_clientsecrets try: from googleapiclient.errors import HttpError from apiclient impor...
import logging from datetime import datetime from typing import Optional, Generator, Tuple import shutil from dateutil.parser import isoparse from pathlib import Path import pandas as pd from collections import defaultdict import calplot from sqlite_utils import Database from summary import update_daily_summaries from ...
#!/usr/bin/env python from LinkedList import LinkedList class Queue(object): def __init__(self): self.items = LinkedList() def __str__(self): return str(self.items) def enqueue(self, item): self.items.insertAtEnd(item) def dequeue(self): dequeued = self.items.head ...
# 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 file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from abc import ABCMeta from argparse import ArgumentParser from warnings import warn import numpy as np import pydub import pytorch_lightning as pl import soundfile import torch import torch.nn as nn import torch.nn.functional as f import wandb from pytorch_lightning.loggers import WandbLogger import models.cunet_mod...
import unittest from jit import jit, j_types as j import ctypes @jit def inf1(a: j.f64): return a + 2 @jit def inf2(a: j.i32): return a + 2 class Test(unittest.TestCase): def test_inference(self): self.assertEqual(inf1(2), 4.0) self.assertEqual(inf2(2), 4) self.assertEqual(in...
import FWCore.ParameterSet.Config as cms # This config was generated automatically using generate2026Geometry.py # If you notice a mistake, please update the generating script, not just this config from Geometry.CMSCommonData.cmsExtendedGeometry2026D85XML_cfi import * from Geometry.TrackerNumberingBuilder.trackerNumb...
# Copyright 2020 Google LLC. 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 a...
"""Decide which plugins to use for authentication & installation""" from __future__ import print_function import os import logging import six import zope.component from certbot import errors from certbot import interfaces from certbot.display import util as display_util logger = logging.getLogger(__name__) z_util ...
from tests.flytekit.unit.common_tests.mixins import sample_registerable as _sample_registerable def test_instance_tracker(): assert _sample_registerable.example.instantiated_in == "tests.flytekit.unit.common_tests.mixins.sample_registerable" def test_auto_name_assignment(): _sample_registerable.example.auto...
from app import apfell, db_objects from sanic.response import json from app.database_models.model import Task, ATTACKCommand, ATTACKTask, Callback, Command from sanic_jwt.decorators import scoped, inject_user import app.database_models.model as db_model from sanic.exceptions import abort @apfell.route(apfell.config['...
import numpy as np import torch import warnings from .neurodiffeq import safe_diff as diff from ._version_utils import deprecated_alias class BaseCondition: r"""Base class for all conditions. A condition is a tool to `re-parameterize` the output(s) of a neural network. such that the re-parameterized outp...
import skimage.io as io import skimage.transform as skt import numpy as np from PIL import Image from src.models.class_patcher import patcher from src.utils.imgproc import * class patcher(patcher): def __init__(self, body='./body/body_lopolykon.png', **options): super().__init__('ロポリこん', body=body, pantie...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "celerytimer_test.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Dja...
import re import datetime timedeltaRegex = re.compile(r'((?P<days>\d+?)d)((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?') def parse_timedelta(delta_str): parts = timedeltaRegex.match(delta_str) if not parts: return parts = parts.groupdict() params = {} for name, param in par...
#!/usr/bin/env python import argparse import logging import os import re import sys import click def valid_date(date_string): DATE_INPUT_FORMAT = "%d-%m-%Y" DATE_INPUT_FORMAT_ALT = "%Y-%m-%dT%H:%M" from datetime import datetime try: return datetime.strptime(date_string, DATE_INPUT_FORMAT) ...
# -*- coding: utf-8 -*- # # 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 file # to you under the Apache License, Version 2.0 (the #...
import json, requests from anime_downloader.sites.anime import Anime, AnimeEpisode, SearchResult from anime_downloader.sites import helpers class AnimeOnline(Anime, sitename = 'animeonline360'): sitename = 'animeonline360' @classmethod def search(cls, query): try: r = hel...
import pytest import os from openl3.cli import positive_int, positive_float, get_file_list, parse_args,\ run, main from argparse import ArgumentTypeError from openl3.openl3_exceptions import OpenL3Error import tempfile import numpy as np from unittest.mock import patch TEST_DIR = os.path.dirnam...
from typing import List, Optional import tiledb from .annotation_dataframe import AnnotationDataFrame from .assay_matrix import AssayMatrix from .tiledb_group import TileDBGroup class AssayMatrixGroup(TileDBGroup): """ Nominally for `X` and `raw/X` elements. You can find element names using soma.X.keys(); ...
from easygraphics import * init_graph(headless=True) img = create_image(800, 600) set_target(img) set_fill_color(Color.RED) draw_circle(200, 200, 50) save_image("test.png") close_image(img) close_graph()
# Copyright 2018 - 2019 Fabian Wenzelmann # # 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 ...
# coding=utf-8 import os import shutil import skimage import skimage.io import skimage.transform import numpy as np def get_all_files(path): all_file = [] for dirpath, dirnames, filenames in os.walk(path): for name in filenames: if name.endswith('.jpg'): all_file.append(os...
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ Exceptions for errors raised while handling backends and jobs. """ from qiskit import QiskitError class JobError(Qiski...
# %% """ <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/select_by_attributes.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td>...
#!/usr/bin/env python3 import numpy as np import scipy.interpolate import math import bdsim import unittest import numpy.testing as nt class BlockTest(unittest.TestCase): pass class BlockDiagramTest(unittest.TestCase): pass class WiringTest(unittest.TestCase): def test_connect_1(self): bd = ...
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: @reference: https://github.com/tkipf/pygcn; https://github.com/dawnranger/pytorch-AGNN """ from __future__ import division from __future__ import print_function import argparse import time import numpy as np import torch import torch.nn.func...
import os curr_path = os.path.dirname(os.path.realpath(__file__)) os.chdir(curr_path) from models import DeepDoubleSarsa, Double_Sarsa, Expected_Double_Sarsa, ReplayBuffer import numpy as np import matplotlib.pyplot as plt import random import operator as op import torch from torch.autograd import Variable episode...
from typing import List, Dict from asgard.clients.apps.client import AppsClient from asgard.workers.autoscaler.cloudinterface import CloudInterface from asgard.workers.converters.asgard_converter import ( AppConverter, AppStatsConverter, DecisionConverter, ) from asgard.workers.models.app_stats import AppS...
#!/router/bin/python from .trex_general_test import CTRexGeneral_Test, CTRexScenario from .trex_nbar_test import CTRexNbarBase from CPlatform import CStaticRouteConfig from .tests_exceptions import * #import sys import time from nose.tools import nottest # Testing client cfg ARP resolve. Actually, just need to check t...
# Copyright 2018-2020 Descartes Labs. # # 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 ...
from prismriver.plugin.common import Plugin from prismriver.struct import Song # todo: load lyrics translations class MusixmatchPlugin(Plugin): ID = 'musixmatch' RANK = 6 def __init__(self, config): super(MusixmatchPlugin, self).__init__('Musixmatch', config) def search_song(self, artist, t...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
#!BPY # Copyright (c) 2020 SuperTuxKart author(s) # # 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...
from typing import Callable, Dict, Optional, Tuple from rest_framework.decorators import action from rest_framework.exceptions import NotFound from rest_framework.request import Request from rest_framework.response import Response from ee.clickhouse.client import sync_execute from ee.clickhouse.models.person import d...
# -*- coding: utf-8 -*- # Author: XuMing <xuming624@qq.com> # Brief: Corpus for model import sys from codecs import open from collections import Counter # Define constants associated with the usual special tokens. PAD_TOKEN = 'PAD' GO_TOKEN = 'GO' EOS_TOKEN = 'EOS' UNK_TOKEN = 'UNK' def save_word_dict(dict_data, sa...
''' Enchant Spelling: Implements spelling backend based on enchant. ''' import enchant from kivy.core.spelling import SpellingBase, NoSuchLangError from kivy.compat import PY2 class SpellingEnchant(SpellingBase): ''' Spelling backend based on the enchant library. ''' def __init__(self, language=No...
# from __future__ import division # import unittest # import numpy as np # # from mock import Mock # from itertools import product # from os.path import dirname, join, abspath, exists # import sys # ROOTDIR = dirname(dirname(dirname(abspath(__file__)))) # sys.path.append(dirname(dirname(__file__))) # print dirname(dirn...
import tensorflow as tf def Conv_1D_Block(x, model_width, kernel, strides): # 1D Convolutional Block with BatchNormalization x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation('relu')(x) x = tf.keras.layers.Conv1D(model_width, kernel, strides=strides, padding="same", kernel_ini...
import logging import networkx import itertools from angr.utils import weakref import claripy l = logging.getLogger(name=__name__) class StateHierarchy(object): def __init__(self): # The New Order self._graph = networkx.DiGraph() self._leaves = set() # nodes with no children sel...
import FWCore.ParameterSet.Config as cms from RecoEgamma.EgammaElectronProducers.defaultLowPtGsfElectronID_cfi import defaultLowPtGsfElectronID lowPtGsfElectronID = defaultLowPtGsfElectronID.clone( ModelNames = cms.vstring(['']), ModelWeights = cms.vstring([ 'RecoEgamma/ElectronIdentification/data...
"""Core Learning regression tests for RLlib (torch and tf). Runs Atari/PyBullet benchmarks for the most popular algorithms. """ import json import os from pathlib import Path from ray.rllib.utils.test_utils import run_learning_tests_from_yaml if __name__ == "__main__": # Get path of this very script to look for...
''' This program is used to recognize the driver's status (one of the 10 statuses) based on the image using pre-trained VGG16 deep convolutional neural network (CNN). This program is modified from the blog post: "Building powerful image classification models using very little data" from blog.keras.io. This p...
from setuptools import setup setup( name='rsa', version='1.0', description='Implementación del criptosistema RSA', url="https://github.com/JohannGordillo/RSA-Cryptosystem", license="MIT", author='Johann Gordillo', author_email='jgordillo@ciencias.unam.mx', packages=['rsa'] )
# Copyright (c) 2017 Alessandro Duca # # See the file LICENCE for copying permission. import re import logging LOGGER = logging.getLogger(__name__) def normalize_path(path): normpath = re.sub(r'/+', '/', path) result = re.sub(r'(^/)|(/$)', '', normpath) return result class NameError(Exception): pa...
#Crie um programa que leia o ano de nascimento de sete pessoas. # final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores. contotal = 0 maiores = 0 menores = 0 from datetime import date ano = date.today().year for c in range(1, 8): nascimento = int(input(f'Em que ano a {c}ª pessoa ...
#!/usr/bin/env python # Notes on formulas # ----------------- # # There are four output types of formulas: # # 1. string # 2. number # 3. date — never a date range, unlike date properties # 4. boolean # Notes on rollups # ---------------- # # There are four signatures of rollup functions: # # 1. any -> array[any] # ...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# Copyright (c) 2020 Huawei Technologies Co., Ltd # Copyright (c) 2019, Facebook CORPORATION. # All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/lice...
#Copyright 2019 Google LLC # # 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 agreed to in writing, so...
from time import * def linear(n): """ linear O(n)""" cont=0 for i in range (n): cont=cont+1 print ("COUNTER",cont,end=" ") def quadratic(n): """ quadratic O(n**2)""" cont=0 for i in range (n): for j in range (n): cont=cont+1 print ("COUNTER",c...
import os import random random.seed(int(os.getenv("SEED"), 16)) from prjxray import util from prjxray.db import Database def gen_sites(): db = Database(util.get_db_root(), util.get_part()) grid = db.grid() for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinf...
# encoding: utf-8 # Copyright (c) 2008, Eric Moritz <eric@themoritzfamily.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copy...
# Generated by Django 3.2 on 2021-04-24 06:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_...
N = int(input()) print(sum([int(i) for i in input()]))
#!/usr/bin/env python # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Implementation for `pmg config` CLI. """ import glob import os import shutil import subprocess import sys from urllib.request import urlretrieve from monty.serialization import dumpfn, loadfn from...
""" CLI引数を解釈するutilです。 """ import os import sys from argparse import ArgumentParser, Namespace from collections import OrderedDict from typing import Any, List, Dict, NamedTuple, Callable, Optional from abc import ABC, abstractmethod import importlib import pathlib import yaml class _Args(NamedTuple): args: List[...
# 练习Python访问互联网的API import requests import json base_url = "https://api.github.com" def get_url(url): return base_url+url resp = requests.get(get_url("/users?page=0&per_page=1'")) result = resp.text print(resp.url , "返回结果为:" , json.dumps(result))
#!/usr/bin/env python3 # coding:utf-8 def solve(strings): d = {} for c, n in zip(range(65, 91), range(0, 52, 2)): d[chr(c)] = n d[chr(c+32)] = n+1 return ''.join(sorted(strings, key=lambda x: d[x])) if __name__ == "__main__": strings = "easqWAwaeq" # AaaeeqqsWw print(solve(strin...
#! /usr/bin/env python3 # developed by Gabi Zapodeanu, TSA, GPO, Cisco Systems # This file contains the Spark Auth, Tropo Key, Google Developer Key SPARK_URL = 'https://api.ciscospark.com/v1' SPARK_AUTH = 'Bearer ' + 'Paste your Spark token here' GOOGLE_API_KEY = 'Paste your Google developer API key here' DNAC...
#!/usr/bin/env python """ Copyright 2018 Johns Hopkins University (Author: Jesus Villalba) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import sys import os import argparse import time import logging import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from mp...
import json import random import time import itertools from ethereum import utils from ethereum.utils import parse_as_bin, big_endian_to_int from ethereum.meta import apply_block from ethereum.common import update_block_env_variables from ethereum.messages import apply_transaction import rlp from rlp.utils import encod...
# Tests for the Part model # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.test import TestCase from django.core.exceptions import ValidationError import os from .models import Part, PartTestTemplate from .models import rename_part_image, ...
""" SoftLayer.tests.managers.hardware_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import copy import mock import SoftLayer from SoftLayer import fixtures from SoftLayer import managers from SoftLayer import testing MINIMAL_TEST_CREATE_ARGS = { 'si...