text
stringlengths
2
999k
# Copyright (C) 2010-2011 Richard Lincoln # # 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...
#!/usr/bin/env python """ Copyright (c) 2014-2016 Miroslav Stampar (@stamparm) See the file 'LICENSE' for copying permission """ import re from core.common import retrieve_content __url__ = "http://rules.emergingthreats.net/open/suricata/rules/botcc.rules" __check__ = "CnC Server" __info__ = "potential malware site...
"""Contains show related classes.""" import re from collections import namedtuple from typing import List, Dict, Any, Optional from mpf.core.assets import AssetPool from mpf.core.config_validator import RuntimeToken from mpf.core.utility_functions import Util from mpf.exceptions.config_file_error import ConfigFileErr...
#!/usr/bin/python ################################################################################ # 20cb92a6-5cc5-11e4-af55-00155d01fe08 # # Justin Dierking # justindierking@hardbitsolutions.com # phnomcobra@gmail.com # # 10/24/2014 Original Construction ################################################################...
import click import concurrent.futures import sqlite_utils from sqlite_utils.db import OperationalError try: import osxphotos except ImportError: osxphotos = None import sqlite3 import boto3 import json import pathlib from .utils import ( calculate_hash, image_paths, CONTENT_TYPES, get_all_keys...
import argparse import json import logging import os import random from io import open import math import sys import pandas as pd import requests from time import gmtime, strftime from timeit import default_timer as timer import numpy as np from tqdm import tqdm, trange import torch from torch.utils.data import Data...
import taxcalc
# # Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import argparse import os import pathlib import re import sys import subprocess import time import logging ...
# -*- coding: utf-8 -*- import logging logger = logging.getLogger('main_logger') import pandas as pd import numpy as np from sklearn.model_selection import StratifiedKFold import os def get_update_df(conf): """ From the direction of the dataset it clean it and return train and validation dataset for the tra...
#!/bin/env python """Command-line interface (CLI) SCL <scott@rerobots.net> Copyright (c) 2019 rerobots, Inc. """ from __future__ import absolute_import from __future__ import print_function import argparse import glob import json import os.path import subprocess import sys import tempfile import uuid import zipfile ...
import pandas as pd from scipy import ndimage from sklearn.cluster import DBSCAN import numpy as np from scipy import stats as st import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.ticker as mticker #import spacepy.plot as splot #import seaborn as sns import matplotlib.colors as ...
import numpy as np import math def splitdata_train_test(data, fraction_training): #randomize data set order np.random.seed(0) np.random.shuffle(data) #find split point training_rows = math.floor(len(data) * fraction_training) #int(...) would be enough training_set = data[0:training_rows] #or data[:tra...
#!/usr/bin/env python3 """Download images provided in wedding-list.csv""" import csv import subprocess WEDDING_LIST_IMG_DIR = "static/img/wedding-list/" WEDDING_LIST_CSV = "backend/db/wedding-list.csv" with open(WEDDING_LIST_CSV) as csvfile: reader = csv.reader(csvfile, quotechar='"') next(reader) images...
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
import cv2 as cv import const import matplotlib.pyplot as plt import numpy as np from PIL import Image from collections import deque def get_neighbors(height, width, pixel): return np.mgrid[ max(0, pixel[0] - 1):min(height, pixel[0] + 2), max(0, pixel[1] - 1):min(width, pixel[1] + 2) ...
from django import forms from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active or not user.is_validated: raise forms.ValidationError('There was a problem with your login.', code='...
#!/usr/bin/env python import roslib; roslib.load_manifest('flexbe_input') import rospy import pickle import actionlib import threading from flexbe_msgs.msg import BehaviorInputAction, BehaviorInputFeedback, BehaviorInputResult, BehaviorInputGoal from .complex_action_server import ComplexActionServer ''' Created on 02...
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from scipy.optimize import fmin import emcee __all__ = ['mcmc_fit', 'initial_odr_fit'] def v_vector(theta): """ Hogg+ 2010, Eqn 29. """ return [[-np.sin(theta)], [np.cos(th...
#!/usr/bin/env python3 import math import sys from typing import Any, Dict import numpy as np from selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY from selfdrive.locationd.models.constants import ObservationKind from selfdrive.swaglog import cloudlog from rednose.helpers.kalmanfilter import K...
#!/usr/bin/env python __author__ = 'Sergei F. Kliver' import argparse from MACE.Parsers.VCF import CollectionVCF parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", action="store", dest="input", required=True, help="Input vcf file with variants") parser.add_argument("-o", "--o...
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE from __future__ import absolute_import import sys import pytest import numpy import awkward1 numba = pytest.importorskip("numba") awkward1_numba = pytest.importorskip("awkward1._connect._numba") awkward1_numba_arrayview = py...
import pygame import random class Apple: def __init__(self): self.apple_skin = pygame.Surface((10, 10)) self.apple_skin.fill((255, 0, 0)) self.pos = (random.randint(0, 400) // 10 * 10, random.randint(0, 400) // 10 * 10) def new_pos(self): self.pos = (random.randint(0, 400) //...
import numpy as np from skimage.measure import points_in_poly import pandas as pd from ._base import GeneAssignmentAlgorithm class PointInPoly(GeneAssignmentAlgorithm): def __init__(self, verbose=False, **kwargs): self.verbose = verbose @classmethod def add_arguments(cls, parser): pass ...
from __future__ import annotations import asyncio import bisect import builtins import concurrent.futures import errno import heapq import logging import os import random import sys import threading import warnings import weakref from collections import defaultdict, deque, namedtuple from collections.abc import Callab...
from pony.orm import * from datetime import datetime from model.group import Group from model.contact import Contact from pymysql.converters import decoders import random class ORMFixture: db = Database() class ORMGroup(db.Entity): _table_ = 'group_list' id = PrimaryKey(int, column='group_id...
# Copyright 2004-present, Facebook. All Rights Reserved. import os from core.models import BaseModel from django.conf import settings from django.db import models from shop.models import Store from shop.models.choices import Currency from .choices import BusinessVertical, FBEChannel class FacebookMetadata(BaseModel...
__all__ = ['CovidDashboard'] import dash_html_components as html import dash_core_components as dcc import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate from dash_oop_components import DashFigureFactory, DashComponent, DashComponentTabs, ...
""" This is a command line application that allows you to scrape twitter! """ import csv import json import argparse import collections import datetime as dt from os.path import isfile from twitterscraper.query import query_tweets, query_tweets_from_user from twitterscraper.ts_logger import logger class JSONEncoder(j...
from math import log import numpy as np import functools from ray.rllib.models.action_dist import ActionDistribution from ray.rllib.utils import MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT, \ SMALL_NUMBER, try_import_tree from ray.rllib.utils.annotations import override, DeveloperAPI from ray.rllib.utils.framework import...
# 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.16.14 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re #...
import random import numpy as np import numpy.random from PIL import Image from faker import Faker from CNNScan.Ballot import BallotDefinitions, MarkedBallots, Positions import CNNScan.Mark.Marks # Create a single, fixed fake race with 4 candidates. def create_fake_contest(pagenum, contest_index=0, min_candidate=1, m...
""" Agglomerative clustering with different metrics =============================================== Demonstrates the effect of different metrics on the hierarchical clustering. The example is engineered to show the effect of the choice of different metrics. It is applied to waveforms, which can be seen as high-dimens...
from enum import Enum import tensorflow as tf import cv2 regularizer_conv = 0.004 regularizer_dsconv = 0.0004 batchnorm_fused = True activation_fn = tf.nn.relu class CocoPart(Enum): Nose = 0 Neck = 1 RShoulder = 2 RElbow = 3 RWrist = 4 LShoulder = 5 LElbow = 6 LWrist = 7 RHip = ...
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Eleccoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test Wallet encryption""" import time from test_framework.test_framework import EleccoinTestFramewor...
""" Shelly platform for the cover component. For more details about this platform, please refer to the documentation https://home-assistant.io/components/shelly/ """ #pylint: disable=import-error from homeassistant.components.cover import (ATTR_POSITION, SUPPORT_CL...
import os import sys import numpy as np import matplotlib.pyplot as pp import warnings from datetime import datetime #try: # from PIL import Iamge #except ImportError: # print ("Python module 'PIL' not available." # pass class EOS1_Img: """Python class for analyzing spectra images t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess import sys def initial_setup(): # Necessary for install programs and edit protected files. if os.geteuid() != 0: print("Script must need root access") subprocess.call(['sudo', 'python3', *sys.argv]) # Install pip f...
# 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 ...
""" The main file used to train student and teacher models. Mainly based on [GitHub repository](https://github.com/intersun/PKD-for-BERT-Model-Compression) for [Patient Knowledge Distillation for BERT Model Compression](https://arxiv.org/abs/1908.09355). """ import logging import os import random import pickle ...
############################################################################## from pandas import DataFrame import numpy as np class Analyzer: """This class create reports from the datasets""" @classmethod def _analyze_header(cls, header_frame, header, data_type): """Create an analysis report ...
from ._paths import * from ._pscmanipulate import *
# -*- coding: utf-8 -*- """ Django settings for MAD Web project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_lit...
import re import jsonschema import jwt from config import db, vuln_app from api_views.json_schemas import * from flask import jsonify, Response, request, json from models.user_model import User # from app import vuln def error_message_helper(msg): return '{ "status": "fail", "message": "' + msg + '"}' def get_...
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRcurl(RPackage): """A wrapper for 'libcurl' <http://curl.haxx.se/libcurl/> Provides ...
from flask import Flask, render_template, request, url_for, redirect from flask_mysqldb import MySQL from twilio.twiml.messaging_response import MessagingResponse from datetime import datetime import functions.getter as getter import json app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_...
#!/usr/bin/env python3 import argparse import csv from sklearn.model_selection import train_test_split from nltk import pos_tag from nltk.tokenize import word_tokenize def load_csv(csv_filename): """Load csv file generated py ```generate_training_testing_csv.py``` and parse contents into ingredients and labels l...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=3 # total number=4 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess import logging logger = logging.getLogger() def reverse(filename, output=None, *, engine='pdftk'): """ reverse a PDF :param filenames: PDF filepath :param output: PDF output """ if output is None: output = 'REVERSED-' +...
from skimage.filters import threshold_otsu from skimage.filters import sobel from skimage.morphology import disk, remove_small_objects, binary_closing from scipy.ndimage import binary_fill_holes __all__ = [ 'segment_all_channels', 'bright_field_segmentation', 'fluorescent_segmentation'] def s...
#Samuel Low-Chappell import difflib import pickle import sys import os #error checking: #ensures that arguments were entered properly #and that the file exists if len(sys.argv)!=2: print "Error: Improper number of arguments. Should be 2." else: pickle_name=sys.argv[1] if not os.path.exists(pickle_name): print "...
from .message_pb2 import ( StartTimeFilter, StatusFilter, WorkflowExecutionFilter, WorkflowTypeFilter, ) __all__ = [ "StartTimeFilter", "StatusFilter", "WorkflowExecutionFilter", "WorkflowTypeFilter", ]
from random import randint import datetime lvl = 10 base_rounds = 10 rounds = lvl * base_rounds print("You have", rounds, "rounds to try to get through.") for i in range(rounds): r = randint(1, 100) print(r) if r >= 96: break print("Number of rounds:", i) if i == rounds - 1: print("Nothing ...
#!/usr/bin/env python3 import os import sys import subprocess import argparse def main(): parser = argparse.ArgumentParser(description='GATK MergeMutectStats') parser.add_argument('-j', '--jvm-mem', dest='jvm_mem', type=int, help='JVM max memory in MB', default=1000) parser.add_a...
import unittest, json from etk.etk import ETK from etk.extractors.glossary_extractor import GlossaryExtractor from etk.knowledge_graph_schema import KGSchema sample_input = { "projects": [ { "name": "etk", "description": "version 2 of etk, implemented by Runqi, Dongy...
# # PySNMP MIB module PANDATEL-BMZ-MODEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANDATEL-BMZ-MODEM-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:37:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
# Copyright 2021 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 agreed to in writing, ...
#!/usr/bin/env python import setuptools with open("README.md", "r") as fh: long_description = fh.read() # See https://packaging.python.org/tutorials/packaging-projects/ for details setuptools.setup( name="fuzzingbook", version="0.0.1", author="Andreas Zeller et al.", author_email="zeller@cs.uni-s...
from ._version import get_versions from .contexts import cd from .prompting import error, prompt, status, success from .unix import cp, ln_s __all__ = ["prompt", "status", "success", "error", "cp", "cd", "ln_s"] __version__ = get_versions()["version"] del get_versions
# Copyright 2018 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...
from __future__ import absolute_import from __future__ import print_function import sys import os # the next line can be removed after installation sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))) from veriloggen import * import ve...
#!/usr/bin/env python # File: get_outliers.py # Created on: Wed Feb 20 14:12:45 2013 # Last Change: Thu Feb 21 16:02:23 2013 # Purpose of script: <+INSERT+> # Author: Steven Boada from mk_galaxy_struc import mk_galaxy_struc from random import choice galaxies = mk_galaxy_struc() galaxies = filter(lambda galaxy: galax...
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup ------------------------------------------------------------...
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from .registry import register from .layers import create as create_layer from .layers.activations import create as create_act from .layers import SpectralConv2d __all__ = ['ResNeXtER', 'resnexter18', 'resnexter34', 'res...
import warnings import numpy as np import pandas as pd import xarray as xr import geopandas from rasterio import features from affine import Affine from python.aux.utils import calc_area np.seterr(divide='ignore', invalid='ignore') """Contains methods for the flowmodel (transport model & local model)""" def get_mask...
# Copyright 2018 Calculation Consulting [calculationconsulting.com] # # 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 python3 from concurrent.futures import ThreadPoolExecutor as PoolExecutor import re import mwbot def convert_redirect(r): before = r['revisions'][0]['*'] redir = mwbot.parse_redirect(before) if redir and redir[0].startswith('http'): text = '{{#exturl:%s}}' % redir[0].strip() if redir[1] and redi...
""" A server that responds with two pages, one showing the most recent 100 tweets for given user and the other showing the people that follow that given user (sorted by the number of followers those users have). For authentication purposes, the server takes a commandline argument that indicates the file containing Twi...
import os import pathlib from typing import Optional, Tuple import requests import tensorflow as tf from chitra.constants import IMAGENET_LABEL_URL from chitra.logging import logger IMAGENET_LABELS: Optional[Tuple[str]] = None def remove_dsstore(path) -> None: """Deletes .DS_Store files from path and sub-folde...
# 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 # distributed under the...
#!/usr/bin/env python # # Volconv - geometry-aware DICOM-to-NIfTI converter # Raw writer (primarily for NIfTI data, hence using NIfTI type system) # # Copyright 2006-2016 Mark J White <mark@celos.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance w...
def factorial(num) : if num <= 1 : print('1 반환') return 1 print("%d * %d! 호출" % (num, num-1)) retVal = factorial(num-1) print("%d * %d!(=%d) 반환" % (num, num-1, retVal)) return num * retVal print('\n5! = ', factorial(5))
import keras from keras.datasets import fashion_mnist import numpy as np from PIL import Image, ImageOps import os import random def convert(size, box): dw = 1./size[0] dh = 1./size[1] x = (box[0] + box[1])/2.0 y = (box[2] + box[3])/2.0 w = box[1] - box[0] h = box[3] - box[2] x = x*dw ...
import asyncio from typing import List, Optional, Union import aioredis from ..utils.scripts import generate_key USER_KEY = "user_urls" class RedisDB: def __init__(self, host: str, port: int, password: str, db: int): self._host = host self._port = port self._password = password ...
from django.forms import widgets class Autocomplete(widgets.Select): template_name = "forms/autocomplete_field.html"
from setuptools import setup, find_packages __version__ = "1.0.2" with open("readme.md", "r") as f: readme = f.read() requirements = ["requests-HTML>=0.10.0", "MangaDex.py>=2.0.6", "pillow>=8.0.1", "imgurpython>=1.1.7"] setup( name = "mangas-dl", version = __version__, author = "Boubou0909", aut...
# -*- coding: utf-8 -*- # # FoundationDB documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are co...
import argparse import logging import os import time import numpy as np import pybullet as p import igibson from igibson.external.pybullet_tools.utils import ( get_max_limits, get_min_limits, get_sample_fn, joints_from_names, set_joint_positions, ) from igibson.objects.visual_marker import VisualM...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import json import boto3 import datetime s3 = boto3.resource('s3') sm = boto3.client('sagemaker') time_created = datetime.datetime.now() def lambda_handler(event, context): print...
# -*- coding: utf-8 -*- # # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu> # # 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 # # Unl...
# Set random seed np.random.seed(0) # Set parameters T = 50 # Time duration tau = 25 # dynamics time constant process_noise = 2 # process noise in Astrocat's propulsion unit (standard deviation) measurement_noise = 9 # measurement noise in Astrocat's collar (standard deviation)...
import winrm import base64 import subprocess # noqa: B404 def fix_run_ps(self, script): # Fixes string bug in python 3 for NTLM connection encoded_ps = base64.b64encode(script.encode("utf_16_le")).decode("ascii") rs = self.run_cmd("powershell -encodedcommand {0}".format(encoded_ps)) if len(rs.std_err): ...
# Copyright Verizon. # Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms. #!/bin/env python3 import argparse import csv import fileinput import getpass import os import re import shlex import shutil import sys import textwrap from datetime import datetime, timezone import...
'''Test idlelib.help_about. Coverage: ''' from idlelib import help_about from idlelib import textview from idlelib.idle_test.mock_idle import Func from idlelib.idle_test.mock_tk import Mbox_func from test.support import requires, findfile requires('gui') from tkinter import Tk import unittest About = help_about.Abou...
from datetime import date from django.views.generic import ListView from django.views.generic import TemplateView from django.views.generic import DetailView from django.http import HttpResponseRedirect from django.utils.encoding import iri_to_uri from django.core.urlresolvers import reverse from django.contrib.auth.m...
from django.conf.urls import patterns, url, include ajax_urls = [ url(r'^get-kml/$', 'tethys_gizmos.views.gizmo_showcase.get_kml', name='get_kml'), url(r'^swap-kml/$', 'tethys_gizmos.views.gizmo_showcase.swap_kml', name='swap_kml'), url(r'^swap-overlays/$', 'tethys_gizmos.views.gizmo_showcase.swap_overlays...
#!/usr/bin/python # # Copyright 2013 Google 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 b...
from django.db import models from django.urls import reverse # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True) price = models.DecimalField(decimal_places=2, max_digits=100) summary = models.TextFiel...
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as AddressProvider class Provider(AddressProvider): building_number_formats = ('###', '##', '#',) city_formats = ('{{city_name}}',) postcode_formats = ('#####',) street_name_formats = ( '{{street_prefix_short}}...
from datetime import date import json import petl as etl import fhir_petl.fhir as fhir def test_to_ratio(): numerator_tuple = (100, '<', 'mL', 'http://unitsofmeasure.org', 'mL') denominator_tuple = (2, '>', 'h', 'http://unitsofmeasure.org', 'h') ratio_tuple = (numerator_tuple, denominator_tuple) ratio_...
"""Script defined to test the Customer class.""" import httpretty from paystackapi.transaction import Transaction from paystackapi.tests.base_test_case import BaseTestCase class TestTransaction(BaseTestCase): """Method defined to test transaction initialize.""" @httpretty.activate def test_initialize(s...
# Copyright (C) 2018 Google 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import time def get_primes_till(limit): l = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53] for i in range(54,limit+1): prime = True sq_root = int(i**0.5) for j in l: if(j>sq_root): break if(i%j==0): prime...
from sqlalchemy import Table, MetaData, create_engine, Integer, \ Column, String, Date, UniqueConstraint class DataAccessLayer: connection = None engine = None conn_string = None metadata = MetaData() def db_init(self, conn_string): self.engine = create_engine(conn_string or self.conn...
class DeploymentError(Exception): pass
#!/usr/bin/env python """The EE Python library.""" __version__ = '0.1.135' # Using lowercase function naming to match the JavaScript names. # pylint: disable=g-bad-name # pylint: disable=g-bad-import-order import collections import datetime import inspect import numbers import os import six from . import batch fro...
import copy import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from argparse import ArgumentParser def generate_random_state(dim): return [np.random.randint(2, size = dim) for _ in range(dim)] def generate_initial_state_from_file(file): f = open(file, "r") grid = [] for row in...
# Copyright (C) 2021-2022, Mindee. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. import math import random from typing import Any, Callable, Dict, List, Tuple import numpy as np from doctr.utils.repr ...
# Copyright 2015 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...
# 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 # distributed under th...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest, time from rapidsms.backends.backend import Backend from rapidsms.message import Message from harness import MockRouter class TestBackend(unittest.TestCase): def setUp (self): self.router = MockRouter() self.backend = Backend(self....