code
stringlengths
1
199k
"""Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an o...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id...
from msrest.pipeline import ClientRawResponse from .. import models class Paths(object): """Paths operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. ...
from pseudoregion import * class Edge(PseudoRegion): """EDGE Fringe field and other kicks for hard-edged field models 1) edge type (A4) {SOL, DIP, HDIP, DIP3, QUAD, SQUA, SEX, BSOL, FACE} 2.1) model # (I) {1} 2.2-5) p1, p2, p3,p4 (R) model-dependent parameters Edge type = SOL p1: BS [T] If t...
"""code_for_good URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
"""config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
from OpenGLCffi.GL import params @params(api='gl', prms=['pname', 'index', 'val']) def glGetMultisamplefvNV(pname, index, val): pass @params(api='gl', prms=['index', 'mask']) def glSampleMaskIndexedNV(index, mask): pass @params(api='gl', prms=['target', 'renderbuffer']) def glTexRenderbufferNV(target, renderbuffer): ...
import os, pickle, re, sys, rsa from common.safeprint import safeprint from common.call import parse from multiprocessing import Lock from hashlib import sha256 global bountyList global bountyLock global bountyPath global masterKey bountyList = [] bountyLock = Lock() bounty_path = "data" + os.sep + "bounties.pickle" ma...
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return w...
import numpy as np import numpy.linalg as la import collections import IPython import tensorflow as tf from utils import * import time from collections import defaultdict class PolicyGradient(Utils): """ Calculates policy gradient for given input state/actions. Users should primarily be calling main PolicyGradient...
""" The ``queue` utils ================== Some operation will require a queue. This utils file """ __author__ = 'Salas' __copyright__ = 'Copyright 2014 LTL' __credits__ = ['Salas'] __license__ = 'MIT' __version__ = '0.2.0' __maintainer__ = 'Salas' __email__ = 'Salas.106.212@gmail.com' __status__ = 'Pre-Alph...
''' evaluate result ''' from keras.models import load_model from keras.utils import np_utils import numpy as np import os import sys sys.path.append('../') sys.path.append('../tools') from tools import conf from tools import load_data from tools import prepare step_length = conf.ner_step_length pos_length = conf.ner_po...
import numpy as np import cvxopt as co def load_mnist_dataset(): import torchvision.datasets as datasets mnist_train = datasets.MNIST(root='../data/mnist', train=True, download=True, transform=None) mnist_test = datasets.MNIST(root='../data/mnist', train=False, download=True, transform=None) test_labels...
""" Created on Sun Mar 10 10:43:53 2019 @author: Heathro Description: Reduces a vcf file to meta section and one line for each chromosome number for testing and debugging purposes. """ vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU") testvcf = open("REDUCED_ali.vcf", "w") temp_chrom = 0 counter = 0 for line_index, line ...
import random rand = random.SystemRandom() def rabinMiller(num): if num % 2 == 0: return False s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for trials in range(64): a = rand.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0...
"""Tests exceptions and DB-API exception wrapping.""" from sqlalchemy import exc as sa_exceptions from sqlalchemy.test import TestBase from exceptions import StandardError, KeyboardInterrupt, SystemExit class Error(StandardError): """This class will be old-style on <= 2.4 and new-style on >= 2.5.""" class DatabaseE...
import re from collections import OrderedDict import compiler.lang as lang doc_next = None doc_prev_component = None doc_root_component = None class CustomParser(object): def match(self, next): raise Exception("Expression should implement match method") escape_re = re.compile(r"[\0\n\r\v\t\b\f]") escape_map = { '\0...
from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('app', '0008_playlistitem_network'), ] operations = [ migrations.AddField( model_name='playlistitem', name='create...
from math import pi, sin, log, exp, atan DEG_TO_RAD = pi / 180 RAD_TO_DEG = 180 / pi def minmax (a,b,c): a = max(a,b) a = min(a,c) return a class GoogleProjection: """ Google projection transformations. Sourced from the OSM. Have not taken the time to figure out how this works. """ def _...
import pytest import pandas as pd from lcdblib.pandas import utils @pytest.fixture(scope='session') def sample_table(): metadata = { 'sample': ['one', 'two'], 'tissue': ['ovary', 'testis'] } return pd.DataFrame(metadata) def test_cartesian_df(sample_table): df2 = pd.DataFrame({'num':...
import io import tempfile import unittest from zipencrypt import ZipFile, ZipInfo, ZIP_DEFLATED from zipencrypt.zipencrypt2 import _ZipEncrypter, _ZipDecrypter class TestEncryption(unittest.TestCase): def setUp(self): self.plain = "plaintext" * 3 self.pwd = b"password" def test_roundtrip(self): ...
""" Abstract base for a specific IP transports (TCP or UDP). * It starts and stops a socket * It handles callbacks for incoming frame service types """ from __future__ import annotations from abc import ABC, abstractmethod import asyncio import logging from typing import Callable, cast from xknx.exceptions import Commu...
class Base: def meth(self): print("in Base meth") class Sub(Base): def meth(self): print("in Sub meth") return super().meth() a = Sub() a.meth()
from neo.Core.UIntBase import UIntBase class UInt256(UIntBase): def __init__(self, data=None): super(UInt256, self).__init__(num_bytes=32, data=data) @staticmethod def ParseString(value): """ Parse the input str `value` into UInt256 Raises: ValueError: if the inpu...
''' Build a tweet sentiment analyzer ''' from __future__ import print_function import cPickle as pickle import sys import time from collections import OrderedDict import numpy import theano import theano.tensor as tensor from theano import config from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams imp...
import rinocloud import requests from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor from clint.textui.progress import Bar as ProgressBar from clint.textui import progress import json def upload(filepath=None, meta=None): encoder = MultipartEncoder( fields={ 'file': ('file', ...
import os import json import pytest from .. import bot, PACKAGEDIR EXAMPLE_TWEET = json.load(open(os.path.join(PACKAGEDIR, 'tests', 'examples', 'example-tweet.json'), 'r')) EXAMPLE_RETWEET = json.load(open(os.path.join(PACKAGEDIR, 'tests', 'examples', 'retweeted-status.json'), 'r')) EXAMPLE_NARCISSISTIC = json.load(ope...
"""Defines the SMEFT class that provides the main API to smeftrunner.""" from . import rge from . import io from . import definitions from . import beta from . import smpar import pylha from collections import OrderedDict from math import sqrt import numpy as np import ckmutil.phases, ckmutil.diag class SMEFT(object): ...
from collections import namedtuple import sublime from sublime_plugin import WindowCommand from ..git_command import GitCommand MenuOption = namedtuple("MenuOption", ["requires_action", "menu_text", "filename", "is_untracked"]) CLEAN_WORKING_DIR = "Nothing to commit, working directory clean." ADD_ALL_UNSTAGED_FILES = "...
import os import logging import traceback from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit from dltb.util.debug import edit from ..utils import protect LOG = logging.getLogger(__name__) class QLogHandler(QPlainTextEdit, logging.Handler): """A log handler that displays log mes...
from __future__ import unicode_literals import django from django.core.exceptions import FieldError from django.test import SimpleTestCase, TestCase from .models import ( AdvancedUserStat, Child1, Child2, Child3, Child4, Image, LinkedList, Parent1, Parent2, Product, StatDetails, User, UserProfile, UserStat, ...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
import sys, os sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定 import numpy as np import matplotlib.pyplot as plt from dataset.mnist import load_mnist from simple_convnet import SimpleConvNet from common.trainer import Trainer (x_train, t_train), (x_test, t_test) = load_mnist(flatten=False) max_epochs = 20 netw...
from copy import deepcopy import settings from twitch.player_manager import PlayerManager class QuestPlayerManager(PlayerManager): """ Functions like add_gold perform a raw store action and then save. __add_gold is the raw store action in this case. Properties of raw store actions: - Call username.l...
import pyactiveresource.connection from pyactiveresource.activeresource import ActiveResource, ResourceMeta, formats import shopify.yamlobjects import shopify.mixins as mixins import shopify import threading import sys from six.moves import urllib import six from shopify.collection import PaginatedCollection from pyact...
from django.conf import settings from images.models import S3Connection from shutil import copyfileobj import tinys3 import os import urllib class LocalStorage(object): def __init__(self, filename): self.filename = filename def get_file_data(self): """ Returns the raw data for the specif...
from __future__ import unicode_literals import os import sys extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'powerschool_apps' copyright = """2017, Iron County School District""" version = '0.1' release = '0.1' exclude_patterns = ['_build'] pygments_style = 'sphinx...
import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Pyt...
__author__ = 'Akshay' """ File contains code to Mine reviews and stars from a state reviews. This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map. For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for eac...
""" Program to build lipids from a template, similarly to MARTINI INSANE Is VERY experimental! """ import argparse import os import xml.etree.ElementTree as ET import numpy as np from sgenlib import pdb class BeadDefinition(object): def __init__(self): self.name = None self.xyz = None def parse(...
import os import ycm_core flags = [ '-Wall', '-Wextra', '-Werror', '-std=gnu11', '-x', 'c', '-isystem', '/usr/include', ] compilation_database_folder = '' if os.path.exists( compilation_database_folder ): database = ycm_core.CompilationDatabase( compilation_database_folder ) else: database = None SOURCE_EXTENSIONS ...
class RepeatError(ValueError): pass class NoneError(ValueError): pass
from storytext.javaswttoolkit import describer as swtdescriber from org.eclipse.core.internal.runtime import InternalPlatform from org.eclipse.ui.forms.widgets import ExpandableComposite import os from pprint import pprint class Describer(swtdescriber.Describer): swtdescriber.Describer.stateWidgets = [ ExpandableCo...
import os from setuptools import find_packages from setuptools import setup version = '1.0' project = 'kotti_mb' install_requires=[ 'Kotti', ], here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() se...
brown_mapping1 = { 'j': 'ADJ', 'p': 'PRO', 'm': 'MOD', 'q': 'DET', 'w': 'WH', 'r': 'ADV', 'i': 'P', 'u': 'UH', 'e': 'EX', 'o': 'NUM', 'b': 'V', 'h': 'V', 'f': 'FW', 'a': 'DET', 't': 'TO', 'cc': 'CNJ', 'cs': 'CNJ', 'cd': 'NUM', 'do': 'V', 'dt': 'DET', 'nn': 'N', 'nr': 'N', 'np': 'NP', 'nc': '...
import codecs f = codecs.open("/Users/hjp/Downloads/task/data/dev.txt", 'r', 'utf-8') for line in f.readlines(): print(line) sents = line.split('\t') print(sents[1] + "\t" + sents[3]) for i in range(len(sents)): print(sents[i]) f.close()
"""nubrain URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
from django.contrib import admin from .models import SimpleModel, Type, FKModel admin.site.register(SimpleModel) admin.site.register(Type) admin.site.register(FKModel)
from .logic import LogicAdapter from chatterbot.conversation import Statement from chatterbot.utils.pos_tagger import POSTagger import re import forecastio class WeatherLogicAdapter(LogicAdapter): """ A logic adapter that returns information regarding the weather and the forecast for a specific location. Cu...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Alarm.last_checked' db.alter_column(u'ddsc_core_alarm', 'last_checked', self.gf('django.db.models.fields.DateTimeFiel...
print " Formated number:", "{:,}".format(102403)
import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import time mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = Axes3D(fig) theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * ...
import sched import time scheduler = sched.scheduler(time.time, time.sleep) def print_time(): print(time.time()) return True scheduler.enter(3, 1, print_time) scheduler.enter(5, 1, print_time) print(scheduler.queue) scheduler.run() # blocking until all scheduled things finish print("done")
""" The core module contains the SoCo class that implements the main entry to the SoCo functionality """ from __future__ import unicode_literals import socket import logging import re import requests from .services import DeviceProperties, ContentDirectory from .services import RenderingControl, AVTransport, ZoneGroupT...
''' Created on 24.09.2017 @author: sysoev ''' from google.appengine.ext import db from google.appengine.api import users import datetime import time import logging from myusers import MyUser def force_unicode(string): if type(string) == unicode: return string return string.decode('utf-8') class Project(...
from fooster.web import web import pytest test_key = 'Magical' test_value = 'header' test_header = test_key + ': ' + test_value + '\r\n' poor_key = 'not' poor_value = 'good' poor_header = poor_key + ':' + poor_value + '\r\n' good_header = poor_key + ': ' + poor_value + '\r\n' case_key = 'wEIrd' case_key_title = case_ke...
from {{appname}}.handlers.powhandler import PowHandler from {{appname}}.conf.config import myapp from {{appname}}.lib.application import app import simplejson as json import tornado.web from tornado import gen from {{appname}}.pow_dash import dispatcher @app.add_route("/dash.*", dispatch={"get" :"dash"}) @app.add_route...
from __future__ import unicode_literals, absolute_import from django.conf.urls import url, include from unach_photo_server.urls import urlpatterns as unach_photo_server_urls urlpatterns = [ url(r'^', include(unach_photo_server_urls, namespace='unach_photo_server')), ]
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0013_auto_20160903_0212'), ] operations = [ migrations.RenameField( model_name='section', old_name='approachable_rating', ...
from tornado.web import RequestHandler class BaseHandler(RequestHandler): def initialize(self): _settings = self.application.settings self.db = self.application.db #self.redis = _settings["redis"] self.log = _settings["log"]
from django.contrib import admin from django.db import models from pagedown.widgets import AdminPagedownWidget from .models import Faq, Category class FaqAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': AdminPagedownWidget}, } fieldsets = [ ('Faq', {'fields': ['q...
from utils import Base, engine Base.metadata.create_all(engine)
from __future__ import unicode_literals from django.apps import AppConfig class BlogConfig(AppConfig): name = 'blog'
import os import arcpy import sys import traceback from modules import create_chainages source_align_location = arcpy.GetParameterAsText(0) database_location = arcpy.GetParameterAsText(1) chainage_distance = arcpy.GetParameterAsText(2) new_fc_name = os.path.basename(source_align_location[:-4]) database_name = "{}.gdb"....
import cPickle import numpy as np import cv2 def unpickle(file): fo = open(file, 'rb') dict = cPickle.load(fo) fo.close() return dict files = ['../../datasets/svhn/cifar-10-batches-py/data_batch_1'] dict = unpickle(files[0]) images = dict['data'].reshape(-1, 3, 32, 32) labels = np.array(dict['labels']) ...
from supriya.tools.ugentools.UGen import UGen class TDelay(UGen): r'''A trigger delay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.ar( ... duration=0.1, ... source=source, ... ) >>> tdelay TDelay.ar() ''' ### CLASS...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TootList.settings.local") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import numpy as np from astropy.io import fits import scipy.ndimage import scipy.fftpack import scipy.optimize def getcentroid(coordinates, values): """ Image centroid from image points im that match with a 2-d array pos, which contains the locations of each point in an all-positive coordinate system. "...
import pytest from locuspocus import Chromosome @pytest.fixture def chr1(): return Chromosome("chr1", "A" * 500000) @pytest.fixture def chr2(): return Chromosome("chr1", "C" * 500000) def test_init(chr1): assert chr1 def test_init_from_seq(): x = Chromosome("chr1", ["a", "c", "g", "t"]) assert True ...
from __future__ import unicode_literals import api.utils 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), ] ...
import numpy as np def index2onehot(n_labels, index): return np.eye(n_labels)[index] def scale_to_unit_interval(ndar, eps=1e-8): """ Scales all values in the ndarray ndar to be between 0 and 1 """ ndar = ndar.copy() ndar -= ndar.min() ndar *= 1.0 / (ndar.max() + eps) return ndar def tile_raster_...
from yaml import load_all try: from yaml import CLoader as Loader except ImportError: print("Using pure python YAML loader, it may be slow.") from yaml import Loader from iengine import IDocumentFormatter __author__ = 'reyoung' class YAMLFormatter(IDocumentFormatter): def __init__(self, fn=None, content...
import datetime from flask import jsonify, request from app import token_auth from app.models.user_token_model import UserTokenModel @token_auth.verify_token def verify_token(hashed): token = UserTokenModel.query\ .filter(UserTokenModel.hashed == hashed, UserTokenModel.ip_address == request.remote_addr) ...
import unittest import instruction_set class TestInstructionSet(unittest.TestCase): def test_generate(self): self.assertIsInstance(instruction_set.generate(), list) self.assertEqual(len(instruction_set.generate()), 64) self.assertEqual(len(instruction_set.generate(32)), 32) inset = i...
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.OUT) MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 USERNAME = '' PASSWORD = "" def on_connect(client, userdata, rc): print("\nConnected with result code " + str(rc) + "\n") ...
from django.test import TestCase from django.contrib.auth.models import User from django.urls import reverse from .models import UserProfile from imagersite.tests import AuthenticatedTestCase class ProfileTestCase(TestCase): """TestCase for Profile""" def setUp(self): """Set up User Profile""" s...
""" Define a simple framework for time-evolving a set of arbitrary agents and monitoring their evolution. """ import numpy as np def int_r(f): """ Convert to nearest integer. """ return int(np.round(f)) class Simulation(object): """ A class that manages the evolution of a set of agents. This is a simple objects...
from __future__ import division try: import tracemalloc except ImportError: tracemalloc = None from libqtile.dgroups import DGroups from xcffib.xproto import EventMask, WindowError, AccessError, DrawableError import logging import os import pickle import shlex import signal import sys import traceback import xc...
import sys, os, arcgisscripting, subprocess def check_output(command,console): if console == True: process = subprocess.Popen(command) else: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output,error = process.commu...
""" Simple utils to save and load from disk. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import joblib from sklearn.externals import joblib as old_joblib import gzip import pickle import pandas as pd import numpy as np import os from rdkit import Che...
import numpy as np def data_concat(result_a): return np.concatenate(result_a, axis=0) def data_mean(result_a): return np.mean(result_a) def data_identity(result_a): return result_a def data_stack(result_a): return np.stack(result_a) def data_single(result_a): return result_a[0] def data_stack_mean(r...
import os try: from cStringIO import StringIO # python 2 except ImportError: from io import StringIO # python 3 from collections import OrderedDict import unittest from tornado.escape import to_unicode from tortik.util import make_qs, update_url, real_ip from tortik.util.xml_etree import parse, tostring class...
import numpy as np from sklearn.grid_search import GridSearchCV import sklearn.metrics as metrics from sklearn import preprocessing as prep from tr_utils import merge_two_dicts, isEmpty class SKSupervisedLearning (object): """ Thin wrapper around some learning methods """ def __init__(self, classifier, ...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys class Module: """ This class provides a generic interface for the preprocessor to pass data to the module and retrieve a list of Transforms to the data. """ priority = 5 ...
import pygame class Face(pygame.sprite.Sprite): def __init__(self, imagePaths, rect, player): pygame.sprite.Sprite.__init__(self) self.imagePath = imagePaths self.images = {} self.rect = pygame.Rect(rect) self.player = player self.stateCallback = player.stateOfMind ...
from markupsafe import escape import re from pymongo.objectid import ObjectId from pymongo.errors import InvalidId from app.people.people_model import People from app.board.board_model import BoardTopic, BoardNode from beaker.cache import CacheManager from beaker.util import parse_cache_config_options from lib.filter i...
import subprocess import sys import time import argparse DIFF = False FIRST = [] def get_floating_ips(): sql = """SELECT fip.floating_ip_address FROM neutron.floatingips AS fip JOIN neutron.ports AS p JOIN neutron.securitygroupportbindings AS sgb JOIN neutron.securitygroupr...
from gitbarry.reasons import start, finish, switch # , switch, publish REASONS = { 'start': start, 'finish': finish, 'switch': switch, # 'publish': publish, }
""" The :mod:`sklearn.metrics` module includes score functions, performance metrics and pairwise metrics and distance computations. """ from . import cluster from .classification import accuracy_score from .classification import brier_score_loss from .classification import classification_report from .classification imp...
#Sequences of actual rotors used in WWII, format is name, sequences, turnover notch(es) rotor_sequences = { 'I': ('EKMFLGDQVZNTOWYHXUSPAIBRCJ', ('Q')), 'II': ('AJDKSIRUXBLHWTMCQGZNPYFVOE', ('E')), 'III': ('BDFHJLCPRTXVZNYEIWGAKMUSQO', ('V')), 'IV': ('ESOVPZJAYQUIRHXLNFTGKDCMWB', ('J')), 'V': ('VZBR...
try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET try: import simplejson as json except ImportError: import json ADDRESS_FIELDS = ( 'first', 'middle', 'last', 'salutation', 'email', 'phone', 'fax', 'mobile', 'addr1', 'addr2', 'addr3', 'addr4', 'c...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cityhallmonitor', '0002_matter_attachments_obtained_at'), ] operations = [ migrations.AddField( model_name='matterattachment', na...
from __future__ import absolute_import, division, print_function import hashlib import linecache import sys import warnings from operator import itemgetter from . import _config from ._compat import PY2, isclass, iteritems, metadata_proxy, set_closure_cell from .exceptions import ( DefaultAlreadySetError, FrozenIns...
import unittest class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ ret = nums[0] pre = nums[0] for i in nums[1:]: if ret < i and ret < 0: ret = pre = i continue ...
""" Transactional workflow control for Django models. """
library_file = open('/srv/http/.config/cmus/lib.pl'); tracks = library_file.readlines() for x in tracks: print('<li>' + x + '</li>')
problem = """ The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ def is_palindromic(s): return s[:...
from flask import make_response from flask.views import MethodView class IndexView(MethodView): def get(self): return make_response('Congratulations!')
import logging import sqlite3 from pyfcm import FCMNotification def insert_token(token): try: con = sqlite3.connect('fcm.db') cur = con.cursor() cur.execute('CREATE TABLE IF NOT EXISTS tokens(token TEXT)') cur.execute('INSERT INTO tokens VALUES (?)', (token, )) con.commit() ...
from unittest import TestCase from aq.sqlite_util import connect, create_table, insert_all class TestSqliteUtil(TestCase): def test_dict_adapter(self): with connect(':memory:') as conn: conn.execute('CREATE TABLE foo (foo)') conn.execute('INSERT INTO foo (foo) VALUES (?)', ({'bar': '...