code
stringlengths
1
199k
"""Tests for the init module.""" import asyncio from unittest.mock import Mock, patch from pyheos import CommandFailedError, HeosError, const import pytest from homeassistant.components.heos import ( ControllerManager, async_setup_entry, async_unload_entry, ) from homeassistant.components.heos.const import ...
""" Unittets for S3 objectstore clone. """ import os import shutil import tempfile import boto from boto import exception as boto_exception from boto.s3 import connection as s3 from oslo.config import cfg from nova.objectstore import s3server from nova import test from nova import wsgi CONF = cfg.CONF CONF.import_opt('...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('osf', '0094_update_preprintprovider_group_auth'), ] operations = [ migrations.RunSQL( """ SELECT setval(pg_get_serial_sequence('"osf_abst...
import sqlalchemy as sql def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; bind # migrate_engine to your metadata meta = sql.MetaData() meta.bind = migrate_engine endpoint_filtering_table = sql.Table( 'project_endpoint', meta, sql.Column...
""" Test the lms/staticbook views. """ import textwrap import mock import requests from django.test.utils import override_settings from django.core.urlresolvers import reverse, NoReverseMatch from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from student.tests.factories import UserFactory, Cou...
""" Serial Port Protocol """ import os, errno import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial import STOPBITS_ONE, STOPBITS_TWO from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS from serialport import BaseSerialPort from twisted.internet import abstract, fdesc, main class Seri...
from __future__ import division, print_function, absolute_import __all__ = ['expm','cosm','sinm','tanm','coshm','sinhm', 'tanhm','logm','funm','signm','sqrtm', 'expm_frechet', 'expm_cond', 'fractional_matrix_power'] from numpy import (Inf, dot, diag, product, logical_not, ravel, transpose,...
from Components.Element import Element from os import path class FrontpanelLed(Element): def __init__(self, which=0, patterns=None, boolean=True): if not patterns: patterns = [(20, 0, 0xffffffff), (20, 0x55555555, 0x84fc8c04)] self.which = which self.boolean = boolean self.patterns = patterns Element.__init_...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ce_evpn_bd_vni version_added: "2.4" short_description: Manages EVPN VXLAN Network Identifier (VNI) on HUAWEI CloudEngine switches. description: -...
""" requests.structures ~~~~~~~~~~~~~~~~~~~ Data structures that power Requests. """ import os import collections from itertools import islice class IteratorProxy(object): """docstring for IteratorProxy""" def __init__(self, i): self.i = i # self.i = chain.from_iterable(i) def __iter__(self)...
import sys import time import os import string import libxml2 libxml2.debugMemory(1) import libxslt debug = 0 repeat = 0 timing = 0 novalid = 0 noout = 0 docbook = 0 html = 0 xinclude = 0 profile = 0 params = {} output = None errorno = 0 begin = 0 endtime = 0 def startTimer(): global begin begin = time.time() d...
'''A library that provides a Python interface to the Twitter API''' __author__ = 'python-twitter@googlegroups.com' __version__ = '1.0.1' import base64 import calendar import datetime import httplib import os import rfc822 import sys import tempfile import textwrap import time import urllib import urllib2 import urlpars...
import sys import os import io import shutil from hashlib import md5 import unittest import tarfile from test import support try: import gzip except ImportError: gzip = None try: import bz2 except ImportError: bz2 = None try: import lzma except ImportError: lzma = None def md5sum(data): retu...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: postgresql_ext short_description: Add or remove PostgreSQL extensions from a database. description: - Add or remove PostgreSQL extensions from a database. ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: digital_ocean_account_info short_description: Gather information about DigitalOcean User ...
from django.conf.urls import patterns, include from . import admin urlpatterns = patterns('', (r'^generic_inline_admin/admin/', include(admin.site.urls)), )
traindat = '../data/fm_train_real.dat' testdat = '../data/fm_test_real.dat' parameter_list = [[traindat,testdat],[traindat,testdat]] def distance_geodesic_modular (train_fname=traindat,test_fname=testdat): from modshogun import RealFeatures, GeodesicMetric, CSVFile feats_train=RealFeatures(CSVFile(train_fname)) feat...
from __future__ import unicode_literals import frappe from frappe import _ from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_date_format, get_fullname, strip_html_tags from frappe.website.utils import find_first_image...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_nova_host_aggregate short_description: Manage OpenStack host...
from __future__ import unicode_literals import webnotes def execute(): webnotes.reload_doc("setup", "doctype", "email_digest") from webnotes.profile import get_system_managers system_managers = get_system_managers(only_name=True) if not system_managers: return # no default company company = webnotes.conn.sql_li...
"""Tools for setting up printing in interactive sessions. """ from __future__ import print_function, division import sys from distutils.version import LooseVersion as V from io import BytesIO from sympy import latex as default_latex from sympy import preview from sympy.core.compatibility import integer_types from sympy...
''' Runnable ======== ''' from jnius import PythonJavaClass, java_method, autoclass _PythonActivity = autoclass('org.renpy.android.PythonActivity') class Runnable(PythonJavaClass): '''Wrapper around Java Runnable class. This class can be used to schedule a call of a Python function into the PythonActivity threa...
"""Test utilities for tf.contrib.signal.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import rewriter_config_pb2 from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver def grappler_...
from __future__ import unicode_literals import webnotes from webnotes.webutils import WebsiteGenerator from webnotes import _ from webnotes.model.controller import DocListController class DocType(DocListController, WebsiteGenerator): def autoname(self): from webnotes.webutils import cleanup_page_name self.doc.name...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from teams.models import CourseTeamMembership class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'CourseTeam.team_size' db.add_column('t...
import Framework import github.NamedUser class RawData(Framework.TestCase): jacquev6RawData = { 'disk_usage': 13812, 'private_gists': 5, 'public_repos': 21, 'subscriptions_url': 'https://api.github.com/users/jacquev6/subscriptions', 'gravatar_id': 'b68de5ae38616c296fa345d2b9d...
import sys import warnings from abc import ABCMeta, abstractmethod import numpy as np from scipy import sparse from .base import LinearModel, _pre_fit from ..base import RegressorMixin from .base import center_data, sparse_center_data from ..utils import check_array, check_X_y, deprecated from ..utils.validation import...
r"""Removes parts of a graph that are only needed for training. There are several common transformations that can be applied to GraphDefs created to train a model, that help reduce the amount of computation needed when the network is used only for inference. These include: - Removing training-only operations like chec...
"""Compiler for keymap.c files This scrip will generate a keymap.c file from a simple markdown file with a specific layout. Usage: python compile_keymap.py INPUT_PATH [OUTPUT_PATH] """ from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import...
from __future__ import absolute_import from django.test import TestCase from .models import Guitarist class PermalinkTests(TestCase): urls = 'regressiontests.model_permalink.urls' def test_permalink(self): g = Guitarist(name='Adrien Moignard', slug='adrienmoignard') self.assertEqual(g.url(), '/g...
from whoosh.automata.fsa import ANY, EPSILON, NFA _LIT = 0 _STAR = 1 _PLUS = 2 _QUEST = 3 _RANGE = 4 def parse_glob(pattern, _glob_multi="*", _glob_single="?", _glob_range1="[", _glob_range2="]"): pos = 0 last = None while pos < len(pattern): char = pattern[pos] pos += 1 ...
""" Least Angle Regression algorithm. See the documentation on the Generalized Linear Model for a complete discussion. """ from __future__ import print_function from math import log import sys import warnings from distutils.version import LooseVersion import numpy as np from scipy import linalg, interpolate from scipy....
class ModuleDocFragment(object): # Postgres documentation fragment DOCUMENTATION = """ options: login_user: description: - The username used to authenticate with default: postgres login_password: description: - The password used to authenticate with login_host: description: ...
"""Bagging meta-estimator.""" from __future__ import division import itertools import numbers import numpy as np from warnings import warn from abc import ABCMeta, abstractmethod from ..base import ClassifierMixin, RegressorMixin from ..externals.joblib import Parallel, delayed from ..externals.six import with_metaclas...
""" Script for exporting courseware from Mongo to a tar.gz file """ import os from django.core.management.base import BaseCommand, CommandError from xmodule.modulestore.xml_exporter import export_course_to_xml from xmodule.modulestore.django import modulestore from opaque_keys.edx.keys import CourseKey from xmodule.con...
""" Ported using Python-Future from the Python 3.3 standard library. Parse (absolute and relative) URLs. urlparse module is based upon the following RFC specifications. RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding and L. Masinter, January 2005. RFC 2732 : "Format for Literal IPv6 Add...
""" Settings for the LMS that runs alongside the CMS on AWS """ from ..aws import * with open(ENV_ROOT / "cms.auth.json") as auth_file: CMS_AUTH_TOKENS = json.load(auth_file) MODULESTORE = CMS_AUTH_TOKENS['MODULESTORE']
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: infini_vol version_added: 2.3 short_description: Create, Delete or Modify volumes on Infinibox description: - This module creates, deletes or mo...
import sys import a print(sys, third_party, a)
from __future__ import print_function from sys import argv, exit import codecs import re import os if len(argv) != 2: exit(1) try: with open(argv[1]) as fle: text = fle.readlines() if text: match = re.match(r"#\s*coding\s*:\s*(?P<coding>\w+)", text[0]) if match: text = co...
""" ========================================================================== Illustration of prior and posterior Gaussian process for different kernels ========================================================================== This example illustrates the prior and posterior of a GPR with different kernels. Mean, sta...
""" This module allows importing AbstractBaseSession even when django.contrib.sessions is not in INSTALLED_APPS. """ from django.db import models from django.utils.translation import gettext_lazy as _ class BaseSessionManager(models.Manager): def encode(self, session_dict): """ Return the given sess...
""" Modified version of build_ext that handles fortran source files. """ from __future__ import division, absolute_import, print_function import os import sys from glob import glob from distutils.dep_util import newer_group from distutils.command.build_ext import build_ext as old_build_ext from distutils.errors import ...
"""Tests for python.util.protobuf.compare.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import re import textwrap import six from google.protobuf import text_format from tensorflow.python.platform import googletest from tensorflow.python.uti...
import logging from ctf_gameserver.lib.database import transaction_cursor from ctf_gameserver.lib.exceptions import DBDataError def get_control_info(db_conn, prohibit_changes=False): """ Returns a dictionary containing relevant information about the competion, as stored in the game database. """ with tr...
""" Form buttons """ import re import sys import binascii from collections import OrderedDict from .field import InputField AC_DEFAULT = 0 AC_PRIMARY = 1 AC_DANGER = 2 AC_SUCCESS = 3 AC_INFO = 4 AC_WARNING = 4 css = { AC_PRIMARY: 'btn-primary', AC_DANGER: 'btn-danger', AC_SUCCESS: 'btn-success', AC_INFO...
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): # First generate a hash table # Format: number:([index array], appearing_frequency_int) d = {} for ii in range(len(num)): if d.has_key(num[ii]): d[num[ii]] = (d[num[ii]...
from django.db import models from stdimage.models import StdImageField from stdimage.utils import UploadToUUID, pre_delete_delete_callback, pre_save_delete_callback from experiences.models import ORMExperience class ORMScene(models.Model): title = models.CharField(max_length=30, blank=False) description = model...
from autobahn.twisted.websocket import WebSocketClientProtocol import logging import json class BitfinexWsClientProtocol(WebSocketClientProtocol): RESPONSE_CODE = { # Generic Error Codes "10000": "Unknown event", "10001": "Unknown pair", "10011": "Unknown Book precision", "10...
import pygame BLACK = (0, 0, 0) WHITE = (255, 255, 255) class TextPrint(object): """ This is a simple class that will help us print to the screen It has nothing to do with the joysticks, just outputting the information. """ def __init__(self): """ Constructor """ self.reset() ...
import unittest from popo_fsm import transition, can_proceed, TransitionNotAllowed class BlogPost(object): def __init__(self, **kwargs): self.state = 'new' super(BlogPost, self).__init__(**kwargs) @transition('state', source='new', target='published') def publish(self): pass @tra...
from pprint import pprint import pickle f = open('query_list.txt','r') o = pickle.load(f) for x in o: pprint(x) raw_input()
import unittest import os import shutil from pybagit.bagit import BagIt class CreateTest(unittest.TestCase): def setUp(self): pass def tearDown(self): if os.path.exists(os.path.join(os.getcwd(), 'test', 'newtestbag')): shutil.rmtree(os.path.join(os.getcwd(), 'test', 'newtestbag')) ...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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,...
import random from ..exceptions.RTMLError import SizeMismatchException, OutOfRangeException def test_train_split(features, labels, test_perc=0.5, rand=True): """ used to randomly(or not) split up data into test and train sample sets. Attrbs: features - The Feature set. labels - The Labels for the Features. test_p...
from django.core.exceptions import ValidationError from django.template import Template from django.utils.translation import ugettext_lazy as _ def TemplateValidator(value): """Try to compile a string into a Django template""" try: Template(value) except Exception as e: raise ValidationError...
try: import hashlib md5er = hashlib.md5 except ImportError, e: import md5 md5er = md5.new import optparse import os from os.path import abspath, join, dirname, basename, exists import pickle import re import sys import subprocess from subprocess import PIPE ENABLED_LINT_RULES = """ build/class build/deprecated ...
import neo4j import time def main(): conn = neo4j.connect("http://localhost:7474") conn.authorization('neo4j', 'testing') start = time.time() iterations = 10000 for it in xrange(iterations): cursor = conn.cursor() for i in xrange(50): cursor.execute("CREATE (n:User)") ...
from Node import Node class DisjointSet(object): # constructor # provides the basic structure of the union find data structure def __init__(self, vertexList): self.vertexList = vertexList self.rootNodes = [] self.nodeCount = 0 self.setCount = 0 self.makeSets(vertexLis...
from pyramid.view import view_config from pyramid.security import remember, forget from pyramid.httpexceptions import HTTPFound, HTTPNotFound, HTTPForbidden import logging, json from traceback import print_exc from ihm.utilities.jwtHttpSecurity import tokenJwt, checking_security_request, checking_security_request_decor...
import math import os import random import re import sys import copy class Node: def __init__(self, data): self.data = data self.right = None self.left = None def printTree(self): if self.left != None: self.left.printTree() if self.data != -1: prin...
import re REGEX_TYPE = type(re.compile('')) __all__ = [ 'ValidationError', 'ValueRequiredError', 'InvalidValueError', 'RequiredValidator', 'BoundsValidator', 'RegexValidator', 'ChoiceValidator', 'ConditionalValidator', 'required', 'bounds', 'regex', 'cond', 'choice' ]...
rm -r /var/log/manabi/profiles/ mkdir -p /var/log/manabi/profiles/ python manage.py runprofileserver --prof-path /var/log/manabi/profiles/ --nomedia --use-cprofile
"Tools for optimal fits to GP sweeps" from time import time import numpy as np from ..small_classes import Count from ..small_scripts import mag from ..solution_array import SolutionArray from ..exceptions import InvalidGPConstraint class BinarySweepTree(object): """Spans a line segment. May contain two subtrees th...
from ..util import Line, ensure_buffer def flush_template(context, declaration=None, reconstruct=True): """Emit the code needed to flush the buffer. Will only emit the yield and clear if the buffer is known to be dirty. """ if declaration is None: declaration = Line(0, '') if {'text', 'dirty'}.issubset(context.f...
from csvkit import CSVKitReader, CSVKitWriter, join from csvkit.cli import CSVKitUtility, match_column_identifier class CSVJoin(CSVKitUtility): description = 'Execute a SQL-like join to merge CSV files on a specified column or columns.' epilog = 'Note that the join operation requires reading all files into memo...
import pytest import netmiko import time from DEVICE_CREDS import * def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'root@pynet-jnpr-srx1', 'router_prompt' : 'root@pynet-jnpr-srx1>', 'router_conf_mode' : 'root@pynet-jnpr-srx1#', 'interface_ip' : '1...
""" Django settings for vkusotiiki project. Generated by 'django-admin startproject' using Django 1.9.8. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os BAS...
""" Create sentinel and singleton objects. Copyright 2014 © Eddie Antonio Santos. MIT licensed. """ import inspect __all__ = ['create'] __version__ = '0.1.1' def get_caller_module(): """ Returns the name of the caller's module as a string. >>> get_caller_module() '__main__' """ stack = inspect.s...
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) visited = [[False] * n for _ in range(m)] def dfs(r, c, pr, pc): visited[r][c] = True for nr, nc in (r-1, c), (r+1, c), (r, c-1), (r, c+1): if 0 <= n...
""" Run the pyrif lib testing locally """ import sys sys.path.insert(0,"/Users/ivan/Library/Python") import sys, getopt from pyMicrodata import pyMicrodata, __version__ test_path = "/Users/ivan/W3C/github/microdata-rdf/tests/" test_file_base = test_path + ("%04d" % int(sys.argv[1])) test_html = test_file_base + "....
""" Api Tests are skipped unless VODAFONE_DESTRUCTIVE is set. This is because these tests WILL make requests to a working device that are potentially: * destructive * expensive * annoying to others It is STRONGLY suggested you remove the simcard to run these tests. By setting the environment variable VODAFO...
from bs4 import BeautifulSoup import requests import json import codecs def page2md(url,md_file_name): page = requests.get( url ).content soup = BeautifulSoup(page) md_file = codecs.open(md_file_name,'w','utf-8') # 文章标题 article_title = soup.title.string md_file.write(u"## %s \n\n" % article_title) # 文章发表时间 arti...
import logging import uuid from sft.common.commands.factory import CommandFactory from sft.common.config import Config from sft.common.commands.base import CommandFinished, CommandIds, ErrorIds, ProgramFinished from .base import ClientCommandBase from sft.common.utils.packets import generate_packet, get_error_code, get...
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, ) bp = Blueprint('routes', __name__, url_prefix='/') from app.forms import CardlabelsForm from app.config import Config from app.cards import cards imgnames, status = cards idx = 0 # init card index max...
from datetime import * from time import strftime import calendar, operator from galaxy.webapps.reports.base.controller import * import galaxy.model from galaxy.model.orm import * import pkg_resources pkg_resources.require( "SQLAlchemy >= 0.4" ) import sqlalchemy as sa import logging log = logging.getLogger( __name__ ) ...
""" converter.py Convert those silly plain text readmes to markdown easily! """ import sys import subprocess import requests import json import argparse import getpass from shutil import copyfile from requests.auth import HTTPBasicAuth __author__ = "Stephen Greene, and Matt Dzwonczyk" __credits__ = ["Stephen Greene", "...
from pymongo import MongoClient from datetime import datetime class MongoFns: def __init__(self): self.client = MongoClient() self.db = self.client.three_sixty_one def saveCrawl(self, url, feedUrl, data, links): crawls = self.db.crawls crawl = {"url": url, "feed_...
"""Tests for plugin system.""" import unittest2 as unittest class TestPlugins(unittest.TestCase): """Unit test for plugin code.""" def test_plugin_locator_with_manager(self): """Test cases for plugin locator. Uses custom PluginLocator inside PluginManager. """ from drop.plugins i...
print(12139)
"""Get jobs offer from json stream""" import re import argparse import json import urllib3 urllib3.disable_warnings() def get_jobs_json(url): """Get jobs json payload""" http = urllib3.PoolManager() req = http.request("GET", url) return req.data def display_jobs(jobs_json, joburl_prefix, filter_rx): ...
""" Logger ------ This module contains pywincffi's logger and functions to retrieve new child loggers. """ import logging try: # pylint: disable=invalid-name,no-member NullHandler = logging.NullHandler except AttributeError: # pragma: no cover # Python 2.6 does not have a NullHandler class NullHandler(...
from __future__ import unicode_literals from django.db import models, migrations import datetime from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
from tkinter import * root = Tk() w = Label(root, text="Hello, world!") w.pack() root.mainloop()
"""Helper classes to monitor and capture output as it runs.""" import sys import threading def monitor(stream, modifier=None, live=False, output=sys.stdout): """Monitor and print lines from stream until end of file is reached. Each line is piped through :modifier:. """ ...
from django.views.generic import ListView from .models import Section class SectionListView(ListView): model = Section
"""v3/mail/send response body builder""" from .personalization import Personalization from .header import Header class Mail(object): """Creates the response body for v3/mail/send""" def __init__( self, from_email=None, subject=None, to_email=None, content=None): self.from_email = None ...
""" WSGI config for tsace project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.development") from django....
from setuptools import setup, find_packages from os import walk from os.path import join, dirname, sep import os import glob packages = find_packages() package_data = {'': ['*.tmpl', '*.patch', ], } data_files = [] def recursively_include(results, directory, patterns): for root, subfolders, fil...
""".. module:: exception Contain all the error handling stuff. """ class SendError(Exception): def __init__(self, error, ret, config): self.message = error self.value = ret self.config = config def __str__(self): return "Error (" + repr(self.value) + ") while sending request:...
import pytest from raiden.exceptions import InvalidAddress from raiden.network.discovery import Discovery from raiden.tests.utils.factories import make_address def test_mock_registry_api_compliance(): address = make_address() contract_discovery_instance = Discovery() # `get` for unknown address raises w...
from django.contrib import admin from django.contrib.admin import autodiscover from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group from .sites import AdminSite site = AdminSite() admin.site = site admin.site.register(Group, GroupAdmin) admin.site.register(User,...
from .rule_action import RuleAction class RuleEmailAction(RuleAction): """Specifies the action to send email when the rule condition is evaluated. The discriminator is always RuleEmailAction in this case. :param odatatype: Constant filled by server. :type odatatype: str :param send_to_service_owners...
from pyslave.data import xy fig, ax = subplots() values_to_scan = np.linspace(0,1,100) values_measured = ones_like(values_to_scan)*nan for i, x in enumerate(values_to_scan) : # Fake measurement values_measured[i] = sin(x) #disp('Step #{0}'.format(i)) # Plot the data ax.clear() ax.plot(values_to_...
from util import * from codes import * import operator def dostats(households): meter = spinner("Writing stats.txt",1) with open('stats.txt', 'w') as stats: meter.spin() males,females = male_to_female(households) stats.write("Percentage Male: %.1f\n" % males) stats.write("Percentage Female: %.1f\n...
from django.db import models from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from...
from typing import TYPE_CHECKING from azure.core import PipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin from msrest import Deserializer, Serializer from ._configuration import KeyVaultClientConfiguration from ._operations_mixin imp...
import sys import os from eclipse2buck import decorator from eclipse2buck import config def get_current_dep_name(file): if os.path.isdir(file): return os.path.realpath(file) else: return os.path.dirname(os.path.realpath(file)) def get_reference_lists(file): filename = get_current_dep_name(fi...
import os import multiprocessing bind = "127.0.0.1:{}".format(os.getenv('PORT', 8000)) workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'aiohttp.worker.GunicornWebWorker' reload = True accesslog = '-' errorlog = '-' proc_name = 'emergency'
"""Chapter 16 Practice Questions Answers Chapter 16 Practice Questions via Python code. """ def main(): # 1. Why can't a brute-force attack be used against a simple substitution # cipher, even with a powerful supercomputer? # Hint: Check page 208 from math import factorial numKeys = factorial(26) ...