text
stringlengths
2
999k
import re from st2actions.runners.pythonrunner import Action REGEX_PATTERN = '^([0-9A-Fa-f]+)$' class ExtractAction(Action): def run(self, text): words = [word for word in text.split(' ') if len(word) >= 32] for word in words: if re.search(REGEX_PATTERN, word): retu...
''' import examplemod as mod # Here we have to used object.function() format mod.do_a_thing() ''' from mod_dir.examplemod import do_a_thing, do_another_thing # Here we have to used object.function() format # thr examplemod.py is in directory mod_dir --> this is basically working with mod...
# Copyright 2021 ZBW – Leibniz Information Centre for Economics # # 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...
import unittest import numpy as np import pandas as pd import datetime import collections from dama.data.it import Iterator, BatchIterator, Slice from dama.data.ds import Data from dama.connexions.core import GroupManager from dama.fmtypes import DEFAUL_GROUP_NAME from dama.utils.core import Chunks from dama.utils.seq...
from flask import request, g, jsonify from flask_cors import cross_origin from alerta.auth.decorators import permission from alerta.exceptions import ApiError, RejectException from alerta.models.alert import Alert from alerta.utils.api import process_alert, add_remote_ip, assign_customer from . import webhooks # { ...
# Copyright 2017 Battelle Energy Alliance, 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 agreed t...
from player.layer import ID_LAYER from base import BaseTestCase class TestOrder(BaseTestCase): _auto_include = False _settings = {'layer.order.test': 'l1 l2 l3'} def test_custom_dir(self): self.config.add_layer( 'test', 'l1', path='player:tests/dir1/') self.config.add_layer(...
import warnings from ._conf import PYRAMID_PARAMS from ._funcs import _get_crs, _verify_shape_bounds from ._types import Bounds, Shape class GridDefinition(object): """Object representing the tile pyramid source grid.""" def __init__( self, grid=None, shape=None, bounds=None, srs=None, is_global=Fal...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
from six.moves import configparser import torch def loadConfig(path): #========= Load settings from Config file config = configparser.RawConfigParser() config.read(path) #[data paths] path_dataset = config.get('data paths', 'path_dataset') #[experiment name] name = config.get('experiment...
def create_tables(): comm = {"criar_cliente": """ CREATE TABLE IF NOT EXISTS cliente ( clie_id SERIAL PRIMARY KEY, clie_cpf_cnpj VARCHAR(15) NOT NULL UNIQUE, clie_nome VARCHAR(60) NOT NULL, clie_fone VARCHAR(40), ...
if __name__ == '__main__': n = int(input()) ans = "" for i in range(1, n + 1): ans += str(i) print(ans)
# License: BSD 3-Clause from .study import OpenMLStudy, OpenMLBenchmarkSuite from .functions import ( get_study, get_suite, create_study, create_benchmark_suite, update_study_status, update_suite_status, attach_to_study, attach_to_suite, detach_from_study, detach_from_suite, ...
#!/usr/bin/env python3 """ Instruction Format <Function Type > < DEST0 N ID > < DEST0 INDEX > < DEST1 N ID > < DEST1 INDEX > < DEST2 N ID > < DEST2 INDEX > < SRC0 N ID > < SRC0 INDEX > < SRC1 N ID > < SRC1 INDEX > < SRC2 N ID > < SRC2 INDEX > ------------------------------ <Function Type> can be of the type: FN...
""" Crie um programa que leia nome e duas notas de vários alunos e guarte tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente.""" lista_main = [] while True: nome = str(input('Nome: ')) nota1 = float(inp...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Flavor', fields=[ ('id', models.AutoField(verbo...
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2019 all rights reserved # # factories from .Project import Project as project # end of file
from flask import Flask from flask import request from flask import send_from_directory from flask.wrappers import Response import json app = Flask(__name__) from flask import send_file import firebase_admin from firebase_admin import credentials from firebase_admin import db import time from multiprocessing import Pro...
########################################################################## ## Prediction Package Tests ########################################################################## # to execute tests, run from *project* root. This runs all test packages # (this one and any other in the /tests folder) # # nosetests --ve...
import functools import itertools import re from ispyb import sqlalchemy # if we replace uuid with count do not include 0 in the count because it will break some bool checks for None WrapperID = itertools.count(1) class Table: def __init__( self, columns, primary_key, unique=Non...
#!/usr/bin/python3 # INSTRUCTIONS # 1. Install Python3 for Windows # https://www.python.org/downloads/release/python-380/ # 2. Download webdriver for you Chrome version Help > About Chrome # https://sites.google.com/a/chromium.org/chromedriver/downloads # 3. Unzip and place the chromedriver in the same folder a...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.15.9 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six fr...
# commented out to prevent build from breaking # this test is known to be broken, see comments in test #from .test_form_api import *
import pandas as pd sales=pd.read_csv('train_data.csv',sep='\s*,\s*',engine='python') #读取CSV X=sales['X'].values #存csv的第一列 Y=sales['Y'].values #存csv的第二列 #初始化赋值 s1 = 0 s2 = 0 s3 = 0 s4 = 0 n = 4 ####你需要根据的数据量进行修改 #循环累加 for i in range(n): s1 = s1 + X[i]*Y[i] s2 = s2 + X[i] s3 = s3 + Y[i] s4 = s4 + X[i...
# -*- coding: utf-8 -*- # Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Emerge hook to pre-parse and verify license information. Called from src/scripts/hooks/install/gen-package-licenses.sh as part...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 VMware, 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/lic...
import threading import time import unittest from urllib.request import urlopen import requests import pytest from vcr_stub_server.stub_server_handler import BuildHandlerClassWithCassette from vcr_stub_server.cassettes.vcrpy_cassette import VcrpyCassette from http.server import HTTPServer @pytest.fixture(scope="mod...
""" Codes are from: https://github.com/jaxony/unet-pytorch/blob/master/model.py """ from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn import init def conv3x3(in_channels, out_channels, stride=1,...
from livesettings import * from django.utils.translation import ugettext_lazy as _ gettext = lambda s:s _strings = (gettext('CreditCard'), gettext('Credit Card')) PAYMENT_GROUP = ConfigurationGroup('PAYMENT_TRUSTCOMMERCE', _('TrustCommerce Payment Settings'), ordering=102) config_register_list( StringVa...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/farm/shared_tatooine_flora_large.iff" result.attribute_template...
# -*- coding: utf-8 -*- """Tests for all choice generators.""" from fauxfactory import gen_choice import string import unittest class TestChoices(unittest.TestCase): """Test choices generator.""" def test_gen_choice_1(self): """ @Test: Select a random value from integer values @Fea...
#!/usr/bin/env python3 # Copyright 2018 Johns Hopkins University (author: Ashish Arora) # Apache 2.0 # It contains utility functions for scoring. These functions are called from score.py from shapely.geometry.polygon import Polygon import numpy as np from PIL import Image def _evaluate_mask_image(mask_ref_arr, mas...
class Message(object): __slots__ = ('id', 'sender', 'recipients', 'created_at', 'body') def __init__(self, id, sender, recipients, created_at, body): self.id = id self.sender = sender self.recipients = recipients self.created_at = created_at self.body = body def ...
#!/usr/bin/env python3 from os import path import codecs from setuptools import setup, find_packages import keyper def run_setup(): """Run package setup.""" here = path.abspath(path.dirname(__file__)) # Get the long description from the README file try: with codecs.open(path.join(here, 'RE...
# -------------- import pandas as pd import scipy.stats as stats import math import numpy as np import warnings warnings.filterwarnings('ignore') #Sample_Size sample_size=2000 #Z_Critical Score z_critical = stats.norm.ppf(q = 0.95) # path [File location variable] data = pd.read_csv(path) #p...
# We will register here processors for the message types by name VM_ENGINE_REGISTER = dict() def register_vm_engine(engine_name, engine_class): """ Verifies a message is valid before forwarding it, handling it (should it be different?). """ VM_ENGINE_REGISTER[engine_name] = engine_class
import json import re # Tests indices of coincidence of substrings with lengths up to 10 # returns the length with the highest index of coincidence def getKeyLen(cipherText): maxIndex = 0 keyLen = 1 for m in range(1, 11): frequencies=[0 for i in range(26)] numChars = 0 index = 0 ...
#!/usr/bin/env python3 """ This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function APIs. If called from the command line, it prints the platform information concatenated as single string to stdout. The output format is useable as pa...
from typing import List, Dict, Tuple, Sequence, Iterable import pandas as pd import numpy as np class DataFrameCleaner(object): def __init__(self): pass def clean(self, df: pd.DataFrame) -> pd.DataFrame: result = (df. pipe(self.copy_df). pipe(self.drop_missin...
from random import shuffle from django.test import TestCase from supplier.models import Supplier from _helpers.tests import SUPPLIER, generate_phone, json_names_to_dic , numbers_generator class SupplierTest(TestCase): def setUp(self) -> None: return super().setUp() def test_create_supplier(self):...
"""Private module that determines how data is encoded and serialized, to be able to send it over a wire, or save to disk""" import base64 import io import json import numbers import pickle import uuid import struct import collections.abc import numpy as np import pyarrow as pa import vaex from .datatype import DataTy...
# Copyright 2020 PerfKitBenchmarker 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 appli...
#!/usr/bin/env python import re import sys import time from urllib.parse import urlparse, parse_qs import requests from bs4 import BeautifulSoup PAGE_URL = "http://www.draftscout.com/players.php?GenPos=%s&DraftYear=%d&sortby=PlayerId&order=ASC&startspot=%d" PAGE_SIZE = 15 UA = "Mozilla/5.0 (X11; Linux x86_64; rv:66...
def getMax(arr): mid = (len(arr)-1)//2 # 4 start = 0 end = len(arr) - 1 # 9 while start <= end: if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]: return arr[mid] elif arr[mid] > arr[mid-1] and arr[mid] <= arr[mid+1]: start = mid+1 # 5 mid = (start + end)//2 # 7 elif arr[mid] >= arr[mid-...
from setuptools import setup, find_packages setup( name='sarafan', version='0.1.0', url='https://github.com/sarafanio/sarafan.git', author='Sarafan Community', author_email='flu2020@pm.me', description='Sarafan node and client application. Sarafan is a distributed ' 'publication...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd from mol_tree import Vocab, MolTree from nnutils import create_var, avg_pool, index_select_ND, GRU from jtnn_enc import JTNNEncoder class ScaffoldGAN(nn.Module): def __init__(self, jtnn, hidden_size, beta, gumbel=...
""" MSX SDK MSX SDK client. # noqa: E501 The version of the OpenAPI document: 1.0.9 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from python_msx_sdk.api_client import ApiClient, Endpoint as _Endpoint from python_msx_sdk.model_utils import ( # n...
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Exercise the wallet. Ported from wallet.sh. # Does the following: # a) creates 3 nodes, with an empty c...
import numpy as np from pathlib import Path from pvinspect.data import ( Image, ModuleImage, ImageSequence, ModuleImageSequence, EL_IMAGE, ) from typing import List, Dict, Any, Optional def assert_equal(value, target, precision=1e-3): assert np.all(value > target - precision) and np.all( ...
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is govered by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Main program for Bugdroid.""" import endpoints import logging import os import cloudstorage...
import pytz import re from datetime import timedelta from . import util class RunAt: MINUTE_PATTERN = "(\d\d?):(\d\d?)" HOUR_PATTERN = "(\d\d?):(\d\d?):(\d\d?)" WEEKDAY_PATTERN = "(...) %s" % HOUR_PATTERN PATTERNS = [MINUTE_PATTERN, HOUR_PATTERN, WEEKDAY_PATTERN] WEEKDAY_MAP = { "mon": 0...
from dateutil.tz import tzlocal import stream import time from stream.exceptions import ApiKeyException, InputException import random import jwt try: from unittest.case import TestCase except ImportError: from unittest import TestCase import json import os import sys import datetime import datetime as dt impo...
import numpy as np class ExperienceReplay: def __init__(self, num_frame_stack=4, capacity=int(1e5), pic_size=(96, 96) ): self.num_frame_stack = num_frame_stack self.capacity = capacity self.pic_size = pic_size self.counter = 0 self.fr...
import velocity_obstacle.velocity_obstacle as velocity_obstacle import nmpc.nmpc as nmpc import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mode", help="mode of obstacle avoidance; options: velocity_obstacle, or nmpc") parser.add_argument( ...
import torch import torch.nn as nn from mmcv.runner import load_checkpoint from torchvision import models from mmedit.models import ImgNormalize from mmedit.models.registry import COMPONENTS from mmedit.utils import get_root_logger @COMPONENTS.register_module() class LTE(nn.Module): """Learnable Texture Extracto...
import asyncio import json from galaxy.api.types import FriendInfo from galaxy.api.errors import UnknownError def test_get_friends_success(plugin, read, write): request = { "jsonrpc": "2.0", "id": "3", "method": "import_friends" } read.side_effect = [json.dumps(request).encode() ...
#todo: add list files option. list different file types #list file extensions for specific type of files #add exit as an option in more places import shutil import os from pathlib import Path #works on windows 10 version = "0.0.2" options = ("move files", "file extensions", "clean desktop", "about", "exit") fo...
""" Connected Components """ import numpy as np from scipy import ndimage import cc3d from ... import seg_utils def connected_components(d, thresh=0, overlap_seg=None, dtype=np.uint32): """ Performs basic connected components on network output given a threshold value. Returns the components as a de...
# Copyright 2018 Harold Fellermann # # 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, dis...
"""Support for functionality to interact with Android TV / Fire TV devices.""" import functools import logging import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_P...
from copy import copy import asyncio import aiohttp import importlib import logging import inspect import types from .communicaton import JsonRpcRequest, SyncJsonRpcRequest from .threading import ThreadedWorkerPool from .auth import DummyAuthBackend from .protocol import ( encode_notification, JsonRpcMsgTyp, ...
""" This file offers the methods to automatically retrieve the graph Candidatus Uhrbacteria bacterium RIFOXYB2_FULL_45_11. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title...
""" Created on May 31, 2016 @author: Jafar Taghiyar (jtaghiyar@bccrc.ca) Updated Nov 21, 2017 by Spencer Vatrt-Watts (github.com/Spenca) """ from collections import OrderedDict #============================ # Django imports #---------------------------- from django.db import models from django.shortcuts import rend...
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. """Common paths used in tests""" import os SHARED_MOCK_DATA_DIR = os.path.dirname(os.path.realpath(__file__)) MOCK_APP_CONFIG = os.path.join(SHARED_MOCK_DATA_DIR, "mock_app_config") MOCK_COMMENTED_APP_CONFIG = o...
import _plotly_utils.basevalidators class OperationValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="operation", parent_name="histogram2dcontour.contours", **kwargs ): super(OperationValidator, self).__init__( plot...
# Copyright 2019 Huawei Technologies Co., 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
from django.db import models # class Item(models.Model): # item = models.CharField(max_length=120) # # def __str__(self): # return self.item class Record(models.Model): charity = models.CharField('Charity', max_length=120) # item = models.CharField(max_length=120) # time = models.CharField(max_length...
from rest_framework import serializers from customer.models import Books class BooksSerializer(serializers.ModelSerializer): class Meta: model = Books fields = "__all__" class BooksSerializerGroup(serializers.ModelSerializer): count = serializers.IntegerField() class Meta: mode...
from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ quer...
# # Copyright 2011-2013 Blender Foundation # # 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 -*- # 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 ...
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import collections import copy import glob import importlib import itertools import json import os import time from bisect import bisect from...
import sys V = int(input()) n = int(input()) i = 0 for cur in input().split(): if (V == int(cur)): print(i) i += 1
"""init db Revision ID: 9912396391c9 Revises: Create Date: 2020-08-02 01:10:17.388059 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9912396391c9' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated ...
try: import MySQLdb except: import pymysql as MySQLdb import os import psycopg2 import pymssql import sqlite3 # 不好意思,DB_CONNECTIONS has to be reinitialized, hence defined in user.py TERMINAL_TOKENS = { 'psql': ["'", '$$'], 'mssql': ["'"] }
""" Description: Base classes to quickly derive other objects coming from JSON Contributors: - Patrick Hennessy """ import enum from datetime import datetime import time import dateparser class ModelMissingRequiredKeyError(Exception): pass class ModelValidationError(Exception): pas...
"""Configuration for the package is handled in this wrapper for confuse.""" import argparse from pathlib import Path from typing import Union import confuse from pandas_profiling.utils.paths import get_config_default class Config(object): """This is a wrapper for the python confuse package, which handles settin...
""" Functions to read and write ASCII model (.dat) files used by SPECFEM2D """ import os import numpy as np from glob import glob from shutil import copyfile from seisflows3.tools.tools import iterable def read_slice(path, parameters, iproc): """ Reads SPECFEM model slice(s) based on .dat ASCII files ...
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2020 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free...
# -*- coding=utf-8 -*- import datetime import pathlib import os import re import sys import invoke from parver import Version from towncrier._builder import ( find_fragments, render_fragments, split_fragments ) from towncrier._settings import load_config from pipenv.__version__ import __version__ from pipenv.ven...
import sys from queue import Queue import random import tensorflow as tf import numpy as np import pandas as pd import scipy.signal import gym #FIXME: move these to the net #some quick wrapper methods for the state def process_state(state): #pad state if 1d with odd number of observations dims = len(state.s...
from office365.sharepoint.client_context import ClientContext from office365.sharepoint.publishing.site_page import SitePage from tests import test_client_credentials, test_team_site_url ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials) new_page = ctx.site_pages.pages.add() new_page.sav...
# -*- coding: utf-8 -*- """ como.battery - the power connection """ # http://www.macrumors.com/2010/04/16/apple-tweaks-serial-number-format-with-new-macbook-pro/ import sys import platform from datetime import date, datetime from clint.textui import puts from paxo.util import is_osx, is_lin, is_win from como.settin...
# -*- coding: utf-8 -*- """ This is the entry point of the Flask application. """ import subprocess import unittest import coverage from flask_script import Manager from app import LOGGER, create_app # The logger should always be used instead of a print(). You need to import it from # the app package. If you want to...
# Copyright (c) 2014 OpenStack Foundation. # # 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...
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score from ProcessOptimizer.space import Integer, Categorical from ProcessOptimizer import gp_minimize, bokeh_plot # For repro...
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Utilities for doing coverage analysis on the RPC interface. Provides a way to track which RPC commands...
# -*- coding: UTF-8 -*- """ 概率分布函数 """ import numpy as np import scipy.stats as st import matplotlib as mpl import matplotlib.pyplot as plt # 二项分布 def binomial_distribution(): n = 10 p = 0.3 k = np.arange(0, 21) binomial = st.binom.pmf(k=k, n=n, p=p) plt.plot(k, binomial, 'o-') plt.title(...
import os import time from selenium import webdriver BROWSER_HEIGHT = 1024 BROWSER_WIDTH = 800 USERNAME = os.environ.get("APP_USERNAME") PASSWORD = os.environ.get("APP_PASSWORD") BOARD_ID = os.environ.get("APP_BOARD_ID") DRIVER_PATH = os.environ.get("APP_WEBDRIVER_PATH", "geckodriver") HEADLESS = os.environ.get("APP_...
import hashlib import base64 def md5_file(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) hash=hash_md5.digest() return base64.b64encode(hash).decode('utf-8')
# -*- coding: utf-8 -*- """The ZIP directory implementation.""" from dfvfs.path import zip_path_spec from dfvfs.vfs import directory class ZIPDirectory(directory.Directory): """File system directory that uses zipfile.""" def _EntriesGenerator(self): """Retrieves directory entries. Since a directory can...
from boto3 import Session from moto.core import BaseBackend from moto.core.utils import unix_time_millis from .exceptions import ( ResourceNotFoundException, ResourceAlreadyExistsException, InvalidParameterException, LimitExceededException, ) class LogEvent: _event_id = 0 def __init__(self, ...
# -*- coding: utf-8 -*- ''' Tests for salt.utils.data ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.data import salt.utils.stringutils from salt.utils.odict import OrderedDict from tests.support.unit import TestCas...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 16 14:47:33 2019 @author: Matteo Papini """ import torch import gym import potion.envs from potion.actors.discrete_policies import ShallowGibbsPolicy from potion.common.logger import Logger from potion.algorithms.safe import spg import argparse impo...
from django.apps import AppConfig class CoreConfig(AppConfig): name = 'planguru.core' verbose_name = "Core" def ready(self): import planguru.core.signals pass
from tensorflow.keras.layers import Input, Flatten, concatenate, Activation from tensorflow.keras.layers import Dense, Conv2D class Topology: """Base class for creating headless Keras computation graphs with arbitrary architecture. Input layer is pre-defined, and resides in `self.input`, to be used by us...
from datetime import datetime import os import urllib.request import magic import re from flask import current_app from notifications_utils.recipients import ( validate_and_format_phone_number, validate_and_format_email_address ) from notifications_utils.template import HTMLEmailTemplate, PlainTextEmailTemplat...
# # Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates # # 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 ap...
""" .. module: lemur.plugins.lemur_cfssl.plugin :platform: Unix :synopsis: This module is responsible for communicating with the CFSSL private CA. :copyright: (c) 2018 by Thomson Reuters :license: Apache, see LICENSE for more details. .. moduleauthor:: Charles Hendrie <chad.hendrie@tr.com> """ import ...