code
stringlengths
1
199k
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: purefa_volume version_added: '2.4' short_description: Manage ...
import os import mock from oslo_config import cfg from oslo_utils import uuidutils from neutron.agent.l3 import keepalived_state_change from neutron.tests.functional import base class TestKeepalivedStateChange(base.BaseSudoTestCase): def setUp(self): super(TestKeepalivedStateChange, self).setUp() cf...
""" Test Cython optimize zeros API functions: ``bisect``, ``ridder``, ``brenth``, and ``brentq`` in `scipy.optimize.cython_optimize`, by finding the roots of a 3rd order polynomial given a sequence of constant terms, ``a0``, and fixed 1st, 2nd, and 3rd order terms in ``args``. .. math:: f(x, a0, args) = ((args[2]*...
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'core', 'version': '1.0'} DOCUMENTATION = r''' --- module: win_file version_added: "1.9.2" short_description: Creates, touches or removes files or directories. description: - Creates (empty) files, updates fi...
import multiprocessing import os _is_travis = os.environ.get('TRAVIS') == 'true' workers = multiprocessing.cpu_count() if _is_travis: workers = 2 bind = ['0.0.0.0:8080', '0.0.0.0:8081', '0.0.0.0:8082'] keepalive = 120 errorlog = '-' pidfile = '/tmp/api_hour.pid' pythonpath = 'hello' backlog = 10240000
from collections import defaultdict from openerp.tools import mute_logger from openerp.tests import common UID = common.ADMIN_USER_ID class TestORM(common.TransactionCase): """ test special behaviors of ORM CRUD functions TODO: use real Exceptions types instead of Exception """ def setUp(self): ...
from __future__ import unicode_literals from django.utils.functional import cached_property from django.contrib.contenttypes.models import ContentType from wagtail.wagtailcore.blocks import ChooserBlock class SnippetChooserBlock(ChooserBlock): def __init__(self, target_model, **kwargs): super(SnippetChooser...
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python Docs and examples: http://code.google.com/p/fantasm/ Copyright 2010 VendAsta Technologies 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 obtai...
"""Views fo the node settings page.""" from flask import request import logging from addons.dropbox.serializer import DropboxSerializer from addons.base import generic_views from website.project.decorators import must_have_addon, must_be_addon_authorizer logger = logging.getLogger(__name__) debug = logger.debug SHORT_N...
import unittest import inspect import logging from struct import pack, unpack_from, pack_into from nose.tools import ok_, eq_, raises from ryu.ofproto import ether from ryu.ofproto import inet from ryu.lib.packet.ethernet import ethernet from ryu.lib.packet.ipv4 import ipv4 from ryu.lib.packet.packet import Packet from...
from nupic.frameworks.opf.exp_description_helpers import importBaseDescription config ={ 'modelParams' : {'sensorParams': {'encoders': {u'c0_timeOfDay': None, u'c0_dayOfWeek': None, u'c1': {'name': 'c1', 'clipInput': True, 'n': 275, 'fieldname': 'c1', 'w': 21, 'type': 'AdaptiveScalarEncoder'}, u'c0_weekend': None}}, ...
import re from itertools import islice import util, units, format class Point(object): """ A geodetic point with latitude, longitude, and altitude. Latitude and longitude are floating point values in degrees. Altitude is a floating point value in kilometers. The reference level is never considered a...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: elasticache_subnet_group version_added: "2.0" short_description: manage Elasticache subnet groups description: - Creates, modifies, and deletes ...
"""i18n_subsites plugin creates i18n-ized subsites of the default site This plugin is designed for Pelican 3.4 and later """ import os import six import logging import posixpath from copy import copy from itertools import chain from operator import attrgetter from collections import OrderedDict from contextlib import c...
__author__ = 'rolandh' RESEARCH_AND_SCHOLARSHIP = "http://refeds.org/category/research-and-scholarship" RELEASE = { "": ["eduPersonTargetedID"], RESEARCH_AND_SCHOLARSHIP: ["eduPersonPrincipalName", "eduPersonScopedAffiliation", "mail", "givenName", "...
import cherrypy import os _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # 表示程式在雲端執行 download_root_dir = os.environ['OPENSHIFT_DATA_DIR'] data_dir = os.environ['OPENSHIFT_DATA_DIR'] else: # 表示程式在近端執行 download_root_dir = _curdir + "/local_...
import sys import argparse import json import base64 import zlib import time import subprocess def mkdesc(): proto = {} proto['magic'] = "PX4FWv1" proto['board_id'] = 0 proto['board_revision'] = 0 proto['version'] = "" proto['summary'] = "" proto['description'] = "" proto['git_identity'] = "" proto['build_tim...
import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() bmpReader = vtk.vtkBMPReader() bmpReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp") atext = vtk.vtkTexture() atext.SetInputConnection(bmpReader.GetOutputPort()) atext.InterpolateOn() plane = vtk.vtkPlaneSource() planeMapper = vtk...
"""California housing dataset. The original database is available from StatLib http://lib.stat.cmu.edu/ The data contains 20,640 observations on 9 variables. This dataset contains the average house value as target variable and the following input variables (features): average income, housing average age, average ro...
"""QGIS Unit tests for QgsDefaultValue. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Matthias Kuh...
"""Tests for the HomematicIP Cloud component."""
import os import eventlet def monkey_patch(): if os.name == 'nt': # eventlet monkey patching the os and thread modules causes # subprocess.Popen to fail on Windows when using pipes due # to missing non-blocking IO support. # # bug report on eventlet: # https://bitbuck...
import inc_sip as sip import inc_sdp as sdp sdp = \ """ v=0 o=- 0 0 IN IP4 127.0.0.1 s=pjmedia c=IN IP4 127.0.0.1 t=0 0 m=audio 4000 RTP/AVP 0 101 a=ice-ufrag:1234 a=ice-pwd:5678 a=rtpmap:0 PCMU/8000 a=sendrecv a=rtpmap:101 telephone-event/8000 a=fmtp:101 0-15 a=candidate:XX 1 UDP 1 1.1.1.1 2222 typ host """ args = "--...
""" Tests for L{twisted.conch.recvline} and fixtures for testing related functionality. """ import sys, os from twisted.conch.insults import insults from twisted.conch import recvline from twisted.python import reflect, components from twisted.internet import defer, error from twisted.trial import unittest from twisted...
'''Unittests for idlelib/SearchDialogBase.py Coverage: 99%. The only thing not covered is inconsequential -- testing skipping of suite when self.needwrapbutton is false. ''' import unittest from test.support import requires from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar from idlelib import Search...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core' } DOCUMENTATION = ''' --- author: Ansible Core Team (@ansible) module: import_tasks short_description: Import a task list descri...
from django.forms import HiddenInput from .base import WidgetTest class HiddenInputTest(WidgetTest): widget = HiddenInput() def test_render(self): self.check_html(self.widget, 'email', '', html='<input type="hidden" name="email" />') def test_use_required_attribute(self): # Always False to a...
from copy import deepcopy import unittest from host_file_system_provider import HostFileSystemProvider from host_file_system_iterator import HostFileSystemIterator from object_store_creator import ObjectStoreCreator from test_branch_utility import TestBranchUtility from test_data.canned_data import CANNED_API_FILE_SYST...
import codecs from collections import deque import contextlib import csv from glob import iglob as std_iglob import io import json import logging import os import py_compile import re import shutil import socket import ssl import sys import tarfile import tempfile import time import zipfile from . import DistlibExcepti...
from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIE...
""" Verifies actions which are not depended on by other targets get executed. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('bare.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('bare.gyp', chdir='relocate/src') file_content = 'Hello from bare.py\n' test.built_file_must_match('out.txt', fi...
""" requires tlslite - http://trevp.net/tlslite/ """ import binascii try: from gdata.tlslite.utils import keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory try: from gdata.tlslite.utils import cryptomath except ImportError: from tlslite.tlslite.utils import cryptomath import gdata.oaut...
from __future__ import absolute_import, unicode_literals from django.utils.encoding import force_str from django.utils import six from django.utils.six.moves import http_cookies _cookie_encodes_correctly = http_cookies.SimpleCookie().value_encode(';') == (';', '"\\073"') _tc = http_cookies.SimpleCookie() try: _tc.l...
from __future__ import division, absolute_import, print_function from distutils.util import get_platform import os import sys import unittest import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError libDir = "l...
{ 'name': 'Password Encryption', 'version': '1.1', 'author': ['OpenERP SA', 'FS3'], 'maintainer': 'OpenERP SA', 'website': 'http://www.openerp.com', 'category': 'Tools', 'description': """ Ecrypted passwords ================== Interaction with LDAP authentication: ---------------------------...
import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' for t in r: if DEBUG: ...
import os import sys import random import unittest sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../.."))) import base_test repo_root = os.path.abspath(os.path.join(__file__, "../../..")) sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver")) from webdriver import exceptions class SendKeysTest(b...
"""Core models.""" import re from email.header import Header from django.conf import settings from django.db import models from django.urls import reverse from django.utils.encoding import force_str, smart_bytes, smart_text from django.utils.functional import cached_property from django.utils.translation import ugettex...
"""Admin API urls.""" from rest_framework import routers from . import viewsets router = routers.SimpleRouter() router.register(r"domains", viewsets.DomainViewSet, basename="domain") router.register( r"domainaliases", viewsets.DomainAliasViewSet, basename="domain_alias") router.register(r"accounts", viewsets.Accoun...
""" sipptam.conf.Schema ~~~~~~~~~~~~~~~~~~~ Contains a basic XML schema to parse the input configuration file. :copyright: (c) 2013 by luismartingil. :license: See LICENSE_FILE. """ import StringIO schema = StringIO.StringIO('''\ <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www...
import wx import os.path class MainWindow( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents() ...
import sys, os extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'sanpera' copyright = u'2012, Eevee' version = '0.1.0' release = '0.1.0' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_st...
from django.urls import reverse_lazy from modoboa.lib.tests import ModoTestCase class OpenAPITestCase(ModoTestCase): openapi_schema_url = reverse_lazy('schema-v1-legacy') def test_unauthorized(self): self.client.logout() response = self.client.get(self.openapi_schema_url) self.assertEqua...
"""Single slice vgg with normalised scale. """ import functools import lasagne as nn import numpy as np import theano import theano.tensor as T import data_loader import deep_learning_layers import image_transform import layers import preprocess import postprocess import objectives import theano_printer import updates ...
class Solution(): def firstMissingPositive(self, A): i = 0 while i < len(A): # 变换和变换条件是关键 if A[i] > 0 and A[i] - 1 < len(A) and A[i] != A[A[i] - 1]: A[A[i] - 1], A[i] = A[i], A[A[i] - 1] else: i += 1 for i, integer in enumer...
"""Main decoy module.""" __version__ = "0.2.0" SETTINGS_PREFIX = "decoy" def includeme(configurator): """ Configure decoy plugin on pyramid application. :param pyramid.configurator.Configurator configurator: pyramid's configurator object """ configurator.registry["decoy"] = get_decoy_setting...
""" Assumptions: * Revisions appear ordered by page ASC, timestamp ASC, rev_id ASC * The max(rev_id) and max(timestamp) of revisions represents the last revision chronologically captured by the dump """ import logging import traceback from mw.xml_dump import Iterator, map, open_file from ..errors import RevisionOrder...
""" Zappa CLI Deploy arbitrary Python programs as serverless Zappa applications. """ from __future__ import unicode_literals from __future__ import division import argcomplete import argparse import base64 import pkgutil import botocore import click import collections import hjson as json import inspect import importli...
""" Bridges calls made inside of a Python environment to the Cmd2 host app while maintaining a reasonable degree of isolation between the two. """ import sys from contextlib import ( redirect_stderr, redirect_stdout, ) from typing import ( IO, TYPE_CHECKING, Any, List, NamedTuple, Option...
"""Graphical user interface.""" import collections import ctypes import sdl2 import hienoi.renderer from hienoi._common import GLProfile, GraphicsAPI, ParticleDisplay, UserData from hienoi._vectors import Vector2i, Vector2f, Vector4f class NavigationAction(object): """Enumerator for the current nagivation action. ...
from leancloud import Object from leancloud import Query from leancloud import LeanCloudError from flask import Blueprint from flask import request from flask import redirect from flask import url_for from flask import render_template import sys sys.path.insert(0,'../') from utils import JsonDict import logging import ...
from selenium.webdriver.support.select import Select def get_selected_option(browser, css_selector): # Takes a css selector for a <select> element and returns the value of # the selected option select = Select(browser.find_element_by_css_selector(css_selector)) return select.first_selected_option.get_at...
import ctypes import time from serial import win32 import serial from serial.serialutil import SerialBase, SerialException, to_bytes, portNotOpenError, writeTimeoutError class Serial(SerialBase): """Serial port implementation for Win32 based on ctypes.""" BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200,...
from IPython.core.display import Javascript, HTML, display_javascript, display_html def setup_notebook(): # assign text/x-c++src MIME type to pybind11 cells code = """ require(['notebook/js/codecell'], function(cc) { cc.CodeCell.options_default.highlight_modes['magic_text/x-c++src'] = {r...
import os import shutil import tempfile import numpy as np import pytest import torch from spotlight.cross_validation import random_train_test_split from spotlight.datasets import movielens from spotlight.evaluation import mrr_score, sequence_mrr_score from spotlight.evaluation import rmse_score from spotlight.factoriz...
import theano, theano.tensor as T import numpy as np import pandas as pd import lasagne """ note: we are following the sklearn api for metrics/loss functions, where the first arg for a function is y true, and second value is y predicted. this is the opposite of the theano functions, so just keep in mind. """ multiclass...
import os import unittest import numpy as np from tfsnippet.examples.utils import MLResults from tfsnippet.utils import TemporaryDirectory def head_of_file(path, n): with open(path, 'rb') as f: return f.read(n) class MLResultTestCase(unittest.TestCase): def test_imwrite(self): with TemporaryDire...
import logging import requests HUE_IP = '192.168.86.32' HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6' logger = logging.getLogger('hue') def getLights(): url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME) try: r = requests.get(url) except: logger.error('Failed getting status for...
import re import braintree from braintree.address import Address from braintree.error_result import ErrorResult from braintree.exceptions.not_found_error import NotFoundError from braintree.resource import Resource from braintree.successful_result import SuccessfulResult class AddressGateway(object): def __init__(s...
project = 'msgiver' copyright = '2018, Tatsunori Nishikori' author = 'Tatsunori Nishikori' version = '0.1' release = '0.1.7.1' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.githubpages', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' langu...
from anima.render.arnold import base85 import unittest import struct class Base85TestCase(unittest.TestCase): """tests the base85 module """ def setup(self): """setup the test """ pass def test_arnold_b85_encode_is_working_properly(self): """testing if arnold_b85_encode i...
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
import os import sys import zlib import time import datetime import base64 from socket import * from impacket import ImpactPacket """ Constants """ READ_BINARY = "rb" WRITE_BINARY = "wb" READ_FROM_SOCK = 7000 ICMP_HEADER_SIZE = 27 DATA_SEPARATOR = "::" DATA_TERMINATOR = "\x12\x13\x14\x15" INIT_PACKET ...
from django.http import StreamingHttpResponse, HttpResponseServerError from download_service.zipbuilder import DDSZipBuilder, NotFoundException, NotSupportedException from django.contrib.auth.decorators import login_required from download_service.utils import make_client from django.http import Http404 @login_required ...
from celery.schedules import crontab import djcelery from django.conf.global_settings import EMAIL_BACKEND import os, sys, logging import subprocess ROOT_PATH = os.path.dirname(__file__) def to_absolute_path(path): return os.path.realpath(os.path.join(ROOT_PATH, path)) DEBUG = True TEMPLATE_DEBUG = DEBUG DONATION_D...
import re import tensorflow as tf class TArtGraphKeys: PLACEHOLDERS = 'placeholders' TART_VARIABLES = 'tart_variables' INFERENCE_SUMMARIES = 'inference_summaries' SCALAR_VARIABLES = 'scalar_variables' OPTIMIZER_VARIABLES = 'optimizer_variables' # DEPRECATED: (2017-12-02) TART_OPERATORS = 'ta...
import sys import py, pytest import _pytest.assertion as plugin from _pytest.assertion import reinterpret, util needsnewassert = pytest.mark.skipif("sys.version_info < (2,6)") @pytest.fixture def mock_config(): class Config(object): verbose = False def getoption(self, name): if name == '...
from tests import base from app import pivocram class PivocramConnetcTest(base.TestCase): def setUp(self): self.connect = pivocram.Connect('PIVOTAL_TEST_TOKEN') def test_should_have_the_pivotal_api_url(self): self.connect.PIVOTAL_URL.should.be.equal('https://www.pivotaltracker.com/services/v5') ...
""" Django settings for TaskTracker project. Generated by 'django-admin startproject' using Django 1.9.6. 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 BA...
from typing import Dict, Any from depccg.tree import Tree from depccg.cat import Category def _json_of_category(category: Category) -> Dict[str, Any]: def rec(node): if node.is_functor: return { 'slash': node.slash, 'left': rec(node.left), 'right':...
""" WSGI config for genoome project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` s...
"""Remove CSV header Removes the header from all CSV files in the current working directory. Note: Outputs to ``./headerRemoved`` directory. """ def main(): import csv, os os.makedirs('headerRemoved', exist_ok=True) # Loop through every file in the current working directory. for csvFilename in os.li...
from redmine import Redmine from feedbacks import settings from base import IBackend class RedmineBackend(IBackend): def __init__(self): self.redmine = Redmine(settings.DJFEEDBACK_REDMINE_URL, key=settings.DJFEEDBACK_REDMINE_KEY) self.project_id = settings.DJFEEDBACK_R...
from django.core.management.base import BaseCommand from optparse import make_option import daemon import daemon.pidfile from signal import SIGTSTP, SIGTERM, SIGABRT import sys, os, subprocess import time from jukebox.jukebox_core import api class Command(BaseCommand): daemon = None proc = None mpg123 = Non...
import random from action import Action class Agent: # nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku def __init__(self, p, pj, pn, height, width, areaMap): self.times_moved = 0 self.direction = Action.LEFT # w ten sposob mozna zapamietac zmienn...
import json import gspread from oauth2client.client import SignedJwtAssertionCredentials import datetime from participantCollection import ParticipantCollection participantFileNames = ['../stayclean-2014-november/participants.txt', '../stayclean-2014-december/participants.txt', ...
import pretend import pytest from botocore.exceptions import ClientError from configstore.backends.awsssm import AwsSsmBackend def test_awsssm_init_bad_install(monkeypatch): monkeypatch.setattr('configstore.backends.awsssm.boto3', None) with pytest.raises(ImportError): AwsSsmBackend() def test_awsssm_su...
import sys import traceback import unittest import unittest.mock import rail class TestIdentity(unittest.TestCase): def test_returns_input_value(self): value = unittest.mock.Mock() self.assertEqual(value, rail.identity(value)) class TestNot(unittest.TestCase): def test_returns_inverse_for_bool(s...
""" thisplace: Human-readable addresses for every 3x3m square on the earth's surface. The simplest way to use this module are the `four_words` and `decode` functions. For more see `WordHasher`. """ import random import geohash def get_words(fname): lines = open(fname) words = [] for word in lines: w...
import kxg import random import pyglet LOWER_BOUND, UPPER_BOUND = 0, 5000 class World(kxg.World): """ Keep track of the secret number, the range of numbers that haven't been eliminated yet, and the winner (if there is one). """ def __init__(self): super().__init__() self.number = 0 ...
"Tests for the `btclib.hashes` module." from btclib.hashes import hash160, hash256 from tests.test_to_key import ( net_unaware_compressed_pub_keys, net_unaware_uncompressed_pub_keys, plain_prv_keys, ) def test_hash160_hash256() -> None: test_vectors = ( plain_prv_keys + net_unaware_compr...
from django.conf.urls import include, url from django.contrib import admin from Poller import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='result...
import os import marshal import cPickle import array class HuffmanNode(object): recurPrint = False def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None): self.L = lnode self.R = rnode self.p = parent self.c = ch self.fq = fq def __repr__(self): ...
NSEEDS=600 import re import sys from subprocess import check_output def main(): lines = sys.stdin.readlines() ips = [] pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):11000") for line in lines: m = pattern.match(line) if m is None: continue ip = 0 ...
from __future__ import division import math import random from colour import Color from PIL import Image, ImageChops, ImageDraw, ImageFont from components import App def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) class Pa...
from django.db import models from django.contrib.auth.models import User class StockStatus(models.Model): date = models.DateTimeField(auto_now_add=True) price = models.FloatField() change = models.FloatField() volume = models.IntegerField() average_daily_volume = models.IntegerField() market_cap...
import boto3 import re cloudformation = boto3.client("cloudformation") stacks = cloudformation.describe_stacks() cfn_topic = ( "arn:aws:sns:us-east-1:561178107736:infrastructure-" "notifications-CloudFormationNotificationSnsTopic-2OCAWQM7S7BP" ) print("===========================================================...
import numpy as np from . import finiteelements as fe from . import matrices from math import cos class Result: def __init__(self): pass def __init__(self, freq, u1, u2, u3, mesh, geometry): self.freq = freq self.u1 = u1 self.u2 = u2 self.u3 = u3 self.mesh = mesh ...
""" Define a Check monad and corresponding functions. """ from functools import (reduce, partial) class Check: """ This super class is not really necessary but helps make the structure clear. data Check a = Pass a | Fail Message """ pass class Pass(Check): def __init__(self, value): ...
""" Revision ID: 0146_add_service_callback_api Revises: 0145_add_notification_reply_to Create Date: 2017-11-28 15:13:48.730554 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = '0146_add_service_callback_api' down_revision = '0145_add_notification_reply_to' def upg...
""" Author: Maneesh Divana <mdaneeshd77@gmail.com> Interpreter: Python 3.6.8 Quick Sort Worst Case: O(n^2) Average Case: O(nlog n) Best Case: O(nlog n) """ from random import shuffle def partition(arr: list, left: int, right: int) -> int: """Partitions the given array based on a pivot element, then sorts the su...
from runner.koan import * import re class AboutRegex(Koan): """ These koans are based on the Ben's book: Regular Expressions in 10 minutes. I found this books very useful so I decided to write a koans in order to practice everything I had learned from it. http://www.forta.com/books/067232566...
from django.db.models import CharField DEFALT_PROTOCOLS = ('http', 'https', 'mailto', 'tel') class HrefField(CharField): def __init__( self, protocols=DEFALT_PROTOCOLS, allow_paths=True, allow_fragments=True, allow_query_strings=True, max_lengt...
import json from collections import OrderedDict import numpy as np import matplotlib.pyplot as plt with open('data/EURUSD3600.json') as f: data = json.loads(f.read()) data = OrderedDict(sorted(data.items())) for i, v in data.iteritems(): print 'timestamp', i print v['rate'] points = OrderedDict(sorted(v...
''' Created on Mar 28, 2016 @author: Ziv ''' class MyClass(object): ''' classdocs ''' def __init__(self, params): ''' Constructor ''' import sys import os from getArgs import getParams from parse import parse __all__ = [] __version__ = 0.1 __date__ = '2015-05-24' __updated__ = '2...
from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time from test_framework.blocktools import create_block, create_coinbase ''' Test version bits' warning system. Generate chains with block versions that appear to be signalling u...
from rest_framework import serializers from rest_framework import pagination from .models import Airport class AirportSerializer(serializers.ModelSerializer): read_only_fields = ('id','name','city','country','country_code','iata','icao') class Meta: model = Airport class PaginationAirportSerializer(pagi...
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisNicSnStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.nic.sn/status_registered.txt" host = "whois.nic.sn" part = yawhois.record.Part(...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
from database import init_db from flask import Flask from flask_graphql import GraphQLView from schema import schema app = Flask(__name__) app.debug = True default_query = ''' { allEmployees { edges { node { id, name, department { id, name }, role ...