code
stringlengths
1
199k
"""Decorators for cross-domain CSRF. """ from django.views.decorators.csrf import ensure_csrf_cookie def ensure_csrf_cookie_cross_domain(func): """View decorator for sending a cross-domain CSRF cookie. This works like Django's `@ensure_csrf_cookie`, but will also set an additional CSRF cookie for use cr...
def main(request, response): return [("Content-Type", "text/html"), ("X-Test", "PASS")], "PASS"
"""Xcode-ninja wrapper project file generator. This updates the data structures passed to the Xcode gyp generator to build with ninja instead. The Xcode project itself is transformed into a list of executable targets, each with a build step to build with ninja, and a target with every source and resource file. This ap...
import numpy as np import scipy import scipy.signal import librosa def structure(X): d, n = X.shape X = scipy.stats.zscore(X, axis=1) D = scipy.spatial.distance.squareform( scipy.spatial.distance.pdist(X.T, metric="cosine")) return D[:-1, :-1] def analyze_file(infile, debug=False): y, sr = l...
"""Pipeline runner""" from __future__ import print_function from __future__ import division from __future__ import absolute_import from .job_processor import Pipeline
from django.apps import AppConfig class MockConfig(AppConfig): name = 'mock' verbose_name = 'Django-Knowledgebase Mock'
from django.db import models class Team(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=20) current_team = models.ForeignKey( "Team", related_name="current_players", on_delete...
from api.libcloudapi import LibcloudApi # noqa __author__ = 'Anthony Shaw' __email__ = 'anthonyshaw@apache.org' __version__ = '0.3.0'
import numpy as np import random def sigmoid(z): return 1.0/(1.0 + np.exp(-z)) def sigmoid_prime(z): return sigmoid(z)*(1-sigmoid(z)) class FullyConnectedNN: def __init__(self, sizes): """Initialize fully connected NN using the list size""" self.sizes = sizes self.W = [np.random.rand...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^issue/(\d+)$', views.issue, name='issue'), url(r'^render/(\d+)$', views.render_invoice, name='render_invoice'), url(r'^render/(\d+)/pdf$', views.render_invoice_pdf, name='render_invoice_pdf'), ]
import collections import warnings import numpy import chainer from chainer.backends import cuda from chainer.backends import intel64 from chainer import configuration from chainer import function from chainer import function_node from chainer.utils import argument from chainer.utils import type_check if cuda.cudnn_ena...
from .sub_resource import SubResource class VirtualNetworkPeering(SubResource): """Peerings in a virtual network resource. :param id: Resource ID. :type id: str :param allow_virtual_network_access: Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virt...
""" Simple caching. """ import os from .os_helpers import write_text_file, read_file, create_dir, remove_file from .. import SNIPS_CACHE_DIR class Cache: STORE_FILE = os.path.join(SNIPS_CACHE_DIR, "token_store") @staticmethod def get_login_token(): return read_file(Cache.STORE_FILE) @staticmetho...
""" Full code for running a game of tic-tac-toe on a board of any size with a specified number in a row for the win. This is similar to tic_tac_toe.py but all relevent moves are paramiterized by board_size arg that sets how big the board is and winning_length which determines how many in a row are needed to win. Defaul...
from setuptools import setup import sys import re version = '' with open('Lib/booleanOperations/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information')...
""" __graph_MT_post__Package.py___________________________________________________________ Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION _____________________________________________________________________________ """ import tkFont from graphEntity import * from GraphicalForm imp...
from os import path from logging import getLogger, Formatter, INFO from logging.handlers import RotatingFileHandler LOG_FORMAT = '[%(asctime)s] %(module)12s:%(funcName)12s:%(lineno)-4s %(levelname)-9s %(message)s' LOG_FILE_NAME = 'pi_bmp183.log' def create_logger(name): """ Creates a logger for the given applic...
from django.contrib import admin from .models import Dependent, Client, Visit from pantry.admin import admin_site class DependentInlineAdmin(admin.TabularInline): model = Dependent fk_name = 'dependent_on' extra = 1 class VisitInlineAdmin(admin.TabularInline): model = Visit fk_name = 'client' re...
""" (c) 2012-2021 Martin Wendt; see https://github.com/mar10/pyftpsync Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php """ import codecs import contextlib import io import os import shutil import sys import threading from posixpath import join as join_url from posixpath import normpa...
""" This module contains definitions and a factory function for XSD builtin datatypes. Only atomic builtins are created, the list builtins types ('NMTOKENS', 'ENTITIES', 'IDREFS') are created using the XSD 1.0 meta-schema or with and additional base schema for XSD 1.1. """ from decimal import Decimal from elementpath i...
# -*- coding: utf-8 -*- import projecteuler as pe def main(): pass if __name__ == "__main__": main()
from __future__ import unicode_literals codec_names = { 'a3d1': 'Multiview Video Coding', 'a3d2': 'Multiview Video Coding', 'a3d3': 'Multiview Video Coding', 'a3d4': 'Multiview Video Coding', 'a3ds': 'Auro-Cx 3D Audio', 'ac-3': 'AC-3 Audio', 'ac-4': 'AC-4 Audio', 'alac': 'Apple Lossless ...
from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OutboxRequestLog', ...
"""A seq2seq model""" import theano from theano import tensor from blocks.bricks import (Initializable, Linear, NDimensionalSoftmax, MLP, Tanh, Rectifier) from blocks.bricks.base import application from blocks.bricks.recurrent import LSTM from blocks.bricks.lookup import LookupTable from bloc...
import re import difflib _hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$") _no_eol = "\ No newline at end of file" def apply_patch(s, patch, revert=False): """ Apply unified diff patch to string s to recover newer string. If revert is True, treat s as the newer string, recover older string. ...
__author__ = 'Tina'
import os import shutil from django.conf import settings from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): args = "" help = "Collect Javascript templates in a place where they're available to Jasmine tests" destination_dir = os.path.join(settings.PROJECT_PATH, 'st...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0006_auto_20160828_0709'), ] operations = [ migrations.RemoveField( model_name='heroesstatistics', name='matches_played', ...
import os USE_CALIENDO = True if os.environ.get('USE_CALIENDO') == 'True' else False class UNDEFINED(object): pass class Ignore(object): def __init__(self, args=UNDEFINED, kwargs=UNDEFINED): self.args = () self.kwargs = {} if args != UNDEFINED: self.args = args if kwa...
from mininet.link import OVSLink from mininet.log import info from mininet.net import Mininet from mininet.node import Host, OVSSwitch, RemoteController from .crossdomain import (CrossDomainCLI, CrossDomainLink, CrossDomainMininet, CrossDomainSwitch) from .data import Data from .utils import c...
r""" Backrefs re. Add the ability to use the following backrefs with re: * \l - Lowercase character class (search) * \c - Uppercase character class (search) * \L - Inverse of lowercase character class (search) * \C - Inverse of uppercase character class (s...
class Weapon(object): def __init__(self, damage, rangeX, rangeY): self.damage = damage self.rangeX = rangeX self.rangeY = rangeY self.selected = False # Gets the class name def getName(self): return self.__class__.__name__ def getDamage(self): return self.damage def getRangeX(self): return self.range...
import pytest from iced_x86 import * @pytest.mark.parametrize("bitness", [16, 32, 64, 0, 15, 128]) def test_invalid_bitness(bitness): if bitness == 16 or bitness == 32 or bitness == 64: BlockEncoder(bitness) else: with pytest.raises(ValueError): BlockEncoder(bitness) @pytest.mark.parametrize("fix_branches", [F...
""" Support for displaying the current CPU speed. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.cpuspeed/ """ import logging from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "CPU speed" ATTR_VEND...
from som_cm.datasets.google_image import createDatasets from som_cm.results.single_image import singleImageResults from som_cm.results.multi_images import multiImagesResults if __name__ == '__main__': data_names = ["apple", "banana", "tulip", "sky", "flower"] num_images = 9 createDatasets(data_names, num_im...
from nose.tools import * from PyKlondike.playingCard import PlayingCard def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_new_card_has_rank_suit_and_is_face_down(): card = PlayingCard('A', 's') assert_equals(card.rank, 'A') assert_equals(card.suit, 's') assert_equals(card.is_face_up(), False...
""" Created on Mon Sep 4 20:25:49 2017 @author: Kirby Urner """ """ primes.py -- Oregon Curriculum Network (OCN) Feb 1, 2001 changed global var primes to _primes, added relative primes test Dec 17, 2000 appended probable prime generating methods, plus invmod Dec 16, 2000 revised to use pow(), removed methods ...
import sys, os, re def remove_comments(s): def replacer(match): s = match.group(0) if s.startswith('/'): return "" else: return s pattern = re.compile( r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE ) r...
L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[0][0]) print(L[1][1]) print(L[2][2])
import sys start=sys.argv[3] end=sys.argv[4] word2id = {} with open(sys.argv[2]) as f: for line in f: if "," in line: w_string, w_id = line.strip().split(",") word2id[w_id] = w_string word2year2embedding={} with open(sys.argv[1]) as f: for line in f: if "," in line: line = line.strip().split(",") w=li...
"""A minimal non-colored version of https://pypi.org/project/halo, to track list progress""" from __future__ import absolute_import, unicode_literals import os import sys import threading from collections import OrderedDict from datetime import datetime import py threads = [] if os.name == "nt": import ctypes c...
from core.himesis import Himesis import uuid class Hlayer5rule2(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule layer5rule2. """ # Flag this instance as compiled now self.is_compiled = True super(Hlayer5rule2, self).__init__(name='Hlayer5rule2', num_nodes=0, edges...
import _plotly_utils.basevalidators class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="namelengthsrc", parent_name="cone.hoverlabel", **kwargs ): super(NamelengthsrcValidator, self).__init__( plotly_name=plotly_name, ...
import argparse from autograd import grad import autograd.numpy as np import autograd.numpy.random as npr import autograd.scipy.special as sp from gamma_def import * from gamma_def_rejection import * from gamma_def_score import * parser = argparse.ArgumentParser(description='Run Sparse gamma DEF example.') parser.add_a...
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url('^$', TemplateView.as_view(template_name='core/index.html'), name="core_index"), ]
""" A directive for including a matplotlib plot in a Sphinx document. By default, in HTML output, `plot` will include a .png file with a link to a high-res .png and .pdf. In LaTeX output, it will include a .pdf. The source code for the plot may be included in one of three ways: 1. **A path to a source file** as the ...
import numpy as np import MDP import RLnetwork import requests import json groups = {'external':['0.0.0.0/0'],'internal':['10.0.0.0/8']} flows = {'keys':'ipsource,ipdestination','value':'frames','filter':'sourcegroup=external&destinationgroup=internal'} threshold = {'metric':'incoming','value':1000} sFlowURL = 'http://...
from IPython.display import HTML, display from utils import argmax, argmin from games import TicTacToe, alphabeta_player, random_player, Fig52Extended, infinity from logic import parse_definite_clause, standardize_variables, unify, subst _canvas = """ <script type="text/javascript" src="./js/canvas.js"></script> <div> ...
from django import forms from .models import Quiz class QuickQuizCreate(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'required':'required'}),max_length=200) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'required':'required'}), min_length=5, label="Password") password2 = forms.C...
import _plotly_utils.basevalidators class TicktextsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="ticktextsrc", parent_name="layout.ternary.aaxis", **kwargs ): super(TicktextsrcValidator, self).__init__( plotly_name=plotly_name, p...
from uio.ti.icss import Icss from uio.device import Uio import ctypes import os EVENT0 = 16 # range 16..31 EVENT1 = 17 # range 16..31 IRQ = 2 # range 2..9 pruss = Icss( "/dev/uio/pruss/module" ) irq = Uio( "/dev/uio/pruss/irq%d" % IRQ ) intc = pruss.intc (core0, core1) = pruss.cores pruss.initialize() for event in ...
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class ColorBar(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "bar.marker" _path_str = "bar.marker.colorbar" _valid_props = { "bgcolor", "bo...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation from DatabaseConnection import DatabaseConnection dbc = DatabaseConnection() Base = declarative_base(bind=dbc.engine) class Journal(Base): __tablename__ = 'journal' __table_args__ = {'autoload': True} class Reference(Bas...
import os import requests from flask import Flask, request, send_from_directory, Response url_to_proxy = "https://lainon.life" server = Flask(__name__) @server.route("/") def handle_root(): return send_from_directory("_site", "index.html") @server.route("/<path:_>") def handle_request(_): path = request.path ...
"""Show the text behind the type""" import os import re import sys import stat import doctest import subprocess from collections import defaultdict from bdb import BdbQuit from pysyte.iteration import first from pysyte.types import paths from whyp import arguments from whyp import shell class BashError(ValueError): ...
""" test_snooper ---------------------------------- Tests for `snooper` module. """ import sys import unittest from contextlib import contextmanager from click.testing import CliRunner from snooper import snooper class TestSnooper(unittest.TestCase): def setUp(self): pass def tearDown(self): pas...
""" Setup """ __author__ = "Manuel Ebert" __copyright__ = "Copyright 2015, summer.ai" __date__ = "2015-11-19" __email__ = "manuel@summer.ai" import boto3 from config import config import argparse def set_up_buckets(): s3 = boto3.resource('s3', region_name=config.region) existing_buckets = [bucket.name for bucke...
class Node: def __init__(self): self.nodes = [] self.index = 0 self.rank = 0 self.parent = None def makeset(self, n): for i in range(0, n): node = Node() node.index = i node.rank = 0 node.parent = node self.nodes...
import sys import json import requests status_url = "https://33yy6hwxnwr3.statuspage.io/api/v2/summary.json" status_data = requests.get(status_url) status_json = json.loads(status_data.text) exit_code = 3 message = "UNKNOWN" for component in status_json['components']: if component['name'] == 'REST API & Web Applica...
from PySide import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(364, 406) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setAutoFillBackground(False) self.centralwidget.se...
import argparse import binascii import random import sys import tempfile import time import os import targets import testlib from testlib import assertEqual, assertNotEqual, assertIn, assertNotIn from testlib import assertGreater, assertRegexpMatches, assertLess from testlib import GdbTest, GdbSingleHartTest, TestFaile...
import argparse import math import numpy as np import os.path import pickle import sys sys.path.append('../lib') import groups import project import match_culling as cull r2d = 180.0 / math.pi parser = argparse.ArgumentParser(description='Keypoint projection.') parser.add_argument('project', help='project directory') a...
from flask import Flask from flask_routelogger import RouteLogger app = Flask(__name__) app.config.update(EXCLUDE_ROUTES = ('/',)) rapp = RouteLogger(app, log_everything=True) @app.route('/') def test(): return "Welcome to flask-routerlogger testing!!" if __name__ == '__main__': app.run()
from datastore import Datastore from traverse import Traverse
""" Test resource module. """
import ast import itertools from StringIO import StringIO from mako.template import Template import mako.ext.babelplugin _args = "message plural n context comment".split() def extract_python(fileobj, keywords, comment_tags, options): return extract_from_string(fileobj.read(), keywords, comment_tags, options) def ex...
import math A = int( input() ) B = int( input() ) C = int( input() ) print( int( (C - A) // B ) )
import pandas as pd import numpy as np from faps.sibshipCluster import sibshipCluster def summarise_sires(sibships, drop_na=False): """ Summarise mating events across maternal families. This is a wrapper function to call `sibshipCluster.sires()` across multiple sibshipCluster objects stored in a diction...
import random import string import os import sys directory = '' def randomstring(): output= '' for i in range(25): # @UnusedVariable output += random.choice(string.letters) return output def fuckem(): for i in range(1000000): # @UnusedVariable directory = randomstring() os.syst...
import calendar import datetime import durationpy import fnmatch import json import os import re import shutil import stat import sys from past.builtins import basestring if sys.version_info[0] < 3: from urlparse import urlparse else: from urllib.parse import urlparse def copytree(src, dst, metadata=True, symli...
""" Simple sequencing file statistics. Gather the following numbers: * Percentages of bases with quality at least Q40, Q30, and Q20 from FASTQ files. * Percentages of reads whose average quality is at least Q40, Q30, and Q20. Requirements: * Python == 2.7.x * Biopython >= 1.60 Copyright (c) 2013 W...
import unittest import os import sys import tensorflow as tf import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from util import run_test, get_data_4d from CNN import CNNModel from DataHolder import ...
''' utils for building wxpy or wxpy extensions ''' from __future__ import with_statement import itertools import os import shutil import sipconfig import sipdistutils import sys import wxpyconfig import wxpyfeatures from distutils.core import Extension from path import path VERBOSE = True def different(file1, file2, st...
import licant from licant.modules import submodule from licant.cxx_modules import application from licant.scripter import scriptq scriptq.execute("../../gxx.g.py") application("target", sources = ["main.cpp"], include_paths = ["../.."], modules = [ submodule("gxx", "posix"), submodule("gxx.dprint", "cout"), su...
print( ord("0") ) print(hex(48))
from userInsert import userInsert from dataRead import dataRead if __name__ == "__main__": filename = u'data.xls' tables = dataRead(filename) data = tables.excel_table_byname() userdata = userInsert() userdata.insertData(data) # userlogin = Login() # url1 = 'http://api.yunlu6.com' # url2...
from os.path import join from fact.path import tree_path from functools import partial import manure input_dir = '/fact/foo' out_dir = '/fact/bar' manure.production_main( path_generators={ 'input_file_path': partial(tree_path, input_dir, '.fits.fz'), 'output_file_path': partial(tree_path, out_dir, ...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('content', '0003_add_collapsible_block'), ] operations = [ migrations.AddField( model_name='linkedcontentpage', name='contact_information_header', field=model...
""" How many circular primes are there below one million? """ from primes import sieve def pe35(limit=1000000): """ >>> pe35() 55 """ ps = set(sieve(limit)) s = 0 # circ = [] for p in ps: pl = len(str(p)) for i in range(1, pl): t = 10**i pp = (p % ...
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.core.urlresolvers import reverse from django.http import Http404 from django.shortcuts import redirect, render from django.views.generic.edit import CreateView from django.db.models import Q from d...
from __future__ import unicode_literals import json import stripe import arrow from django.utils import timezone from django.contrib import messages, auth from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.shortcuts import render, redirect from django.http...
from __future__ import unicode_literals import os import shutil import unittest import tempfile from io import BytesIO from PIL import Image from flask_thumbnails.storage_backends import FilesystemStorageBackend class FilesystemStorageBackendTestCase(unittest.TestCase): def setUp(self): image = Image.new('R...
class Solution: # @param {string} a # @param {string} b # @return {string} def addBinary(self, a, b): return bin(int(a,2) + int(b,2))[2:]
import os,sys,re import getpass import getopt from Tools.eddo import * from pyson import * shortargs=[ 'h', 'u:', 'p:', 'v' ] longargs=[ 'help', 'username=', 'password=', 'verbose' ] def usage(): print 'Usage:',sys.argv[0],':',''.join(shortargs),longargs return try: opts, arg...
from __future__ import absolute_import, division, print_function, unicode_literals import os import pytest from bosonnlp import BosonNLP, ClusterTask, CommentsTask from bosonnlp.exceptions import HTTPError, TimeoutError def test_invalid_token_raises_HTTPError(): nlp = BosonNLP('invalid token') pytest.raises(HTT...
"""PlannerOverride API Tests for Version 1.0. This is a testing template for the generated PlannerOverrideAPI Class. """ import unittest import requests import secrets from py3canvas.apis.planner_override import PlannerOverrideAPI from py3canvas.apis.planner_override import Planneroverride class TestPlannerOverrideAPI(...
import os, sys import pika import json import time import traceback from peewee import * from datetime import datetime MQTT_HOST = os.environ.get('MQTT_HOST') MQTT_USER = os.environ.get('MQTT_USER') MQTT_PASSWORD = os.environ.get('MQTT_PASSWORD') DB_HOST = os.environ.get('DB_HOST') DB_PASSWORD = os.environ.get('DB_PASS...
import simplejson from str_builder import StrBuilder import pihdf def print_design(mfdo, s): s += '{\n' s += s.indent() + '"design":\n' s += '{\n' s += s.indent() + '"name": "' + mfdo.module_name + '",\n' s += '"interfaces":\n' s += '[\n' s.indent() if mfdo.Reset != None: s += si...
from __future__ import print_function, division, absolute_import, unicode_literals from tqdm import tqdm import numpy as np from scipy.ndimage import gaussian_filter from scipy.special import logsumexp import tensorflow as tf from .models import sample_from_logdensity from .tf_utils import gauss_blur def sample_batch_f...
import numpy as np import pdb import matplotlib.pyplot as plt import glob from .. import nptipsyreader class profile(object): def __init__(self, filename): self.filename = filename tipsyfile = glob.glob('*.den')[0] tipsy = nptipsyreader.Tipsy(tipsyfile) tipsy._read_param() se...
TAGS_ALLOWED_CHARACTERS = 'a-z0-9+#-.' MAX_TAGS = 10 MIN_TAGS = 1
import argparse import urlparse import os import requests from bs4 import BeautifulSoup parser = argparse.ArgumentParser() parser.add_argument("-p", "--prefix", help = "Remove this prefix from all files where it is present") parser.add_argument("base", help = "URL at which to start the crawl") parser.add_argument("targ...
''' Manipulate action (wrench) menu example: add_action('/stash/launch_stash.py','monitor') save_defaults() # so it is stored for next launch ''' from objc_util import * NSUserDefaults = ObjCClass('NSUserDefaults') def add_action(scriptName, iconName='python', iconColor='', title=''): '''adds an editor acti...
from okdataset import ChainableList, Context, Logger logger = Logger("collect example") logger.info("Building big list") l = ChainableList([ x for x in xrange(0, 100) ]) logger.info("Creating context") context = Context() logger.info("Building dataset") ds = context.dataSet(l, bufferSize=1) a = 1 logger.info("Calling m...
__all__ = ['models',]
import flag import skiplist class Number: def __init__(x): .x = x N = flag.Int('n', 0, 'Number of trials of abandoned iterator.') def main(args): args = flag.Munch(args) # We want sum of (2, 20..29, 200..299) want = sum([2*2] + [(x+20)*(x+20) for x in range(10)] + [(x+200)*(x+200) for x in range(100)]) mu...
import sys, time, random, math, pygame from pygame.locals import * def print_text(font, x, y, text, color=(255, 255, 255)): imgText = font.render(text, True, color) screen = pygame.display.get_surface() # req'd when function moved into MyLibrary screen.blit(imgText, (x, y)) class MySprite(pygame.sprite.Spr...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('crop', '0001_initial'), ] operations = [ migrations.RenameField( model_name='fertilizer', old_name='dis_id', new_name='ferti_...
previous_results = {} def fibo(number): if previous_results.get(number, 0): return previous_results.get(number) if number <= 2: previous_results[number] = 1 else: previous_results[number] = fibo(number - 1) + fibo(number - 2) return previous_results.get(number) n = 0 i = 0 while ...
"""The python-broadlink library.""" import socket import typing as t from . import exceptions as e from .const import DEFAULT_BCAST_ADDR, DEFAULT_PORT, DEFAULT_TIMEOUT from .alarm import S1C from .climate import hysen from .cover import dooya from .device import Device, ping, scan from .light import lb1, lb2 from .remo...