code stringlengths 1 199k |
|---|
"""Search query parser
version 2006-03-09
This search query parser uses the excellent Pyparsing module
(http://pyparsing.sourceforge.net/) to parse search queries by users.
It handles:
* 'and', 'or' and implicit 'and' operators;
* parentheses;
* quoted strings;
* wildcards at the end of a search term (help*);
Requireme... |
import cipher
class Latinlike(cipher.Cipher):
_tests = [{"offset": o} for o in [0, 1, 1023, 1024, 2048]]
def variant_name(self):
return "{0}{1[rounds]}_{1[lengths][key]}".format(self.name(), self.variant)
def encrypt(self, plaintext, offset=0, **d):
result = []
while plaintext:
... |
"""Skills module."""
import math
import logging
from .locals import * # noqa
from .entities import EntityEvent, EntityInput, EntityInputChangeEvent, EntityCollisionEvent, EntityManager, \
Component, System, EntityState, EntityStateChangeEvent, EntityHealthChangeEvent
from .modules import Module
from .utils import ... |
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),
('quran', '0008_aut... |
from bearlibterminal import terminal as term
from .screen_functions import center
class Option:
def __init__(self, title, opt=None, subopts=None):
self.title = title
# options list
self.opts = [opt] if opt else []
# options index
self.optindex = 0
# suboptions list
... |
class Scene(object):
"""Abstract Scene"""
def __init__(self, scene_manager):
self.manager = scene_manager
def render(self, screen):
raise NotImplementedError
def update(self):
raise NotImplementedError
def handle_events(self, e):
raise NotImplementedError |
import os
import pytest
from pocs.dome.bisque import Dome
from pocs.utils.theskyx import TheSkyX
pytestmark = pytest.mark.skipif(TheSkyX().is_connected is False,
reason="TheSkyX is not connected")
@pytest.fixture(scope="function")
def dome(config):
try:
del os.environ['POCSTI... |
from django.conf.urls.defaults import patterns, url
from arcade.games import views
urlpatterns = patterns('',
url(r'^games/new/$', views.CreateNewGameView.as_view(), name='games.CreateNewGameView'),
url(r'^games/(?P<pk>\d+)/$', views.GameDetailView.as_view(), name='games.GameDetailView'),
) |
import csv
minx, maxx = 0, 0
miny, maxy = 0, 0
minz, maxz = 0, 0
with open('thc.csv') as input_file:
reader = csv.DictReader(input_file)
for row in reader:
x, y, z = float(row['x']), float(row['y']), float(row['z'])
minx = min(x, minx)
maxx = max(x, maxx)
miny = min(y, miny)
... |
import datetime
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@core.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or... |
"""
single-number-ii.py
Created by Shuailong on 2016-03-23.
https://leetcode.com/problems/single-number-ii/.
"""
class Solution(object):
def singleNumber(self, nums):
"""
O(n) time and O(1) space, but slower than Solution1 and Solution2.
:type nums: List[int]
:rtype: int
"""
... |
"""Method for sharing global sensor and port configuration values between
modules.
"""
import serial
portdefaults = {
"port_baud": 9600,
"port_stopbits": serial.STOPBITS_ONE,
"port_parity": serial.PARITY_NONE,
"port_timeout": 0.01,
"virtual": False,
"delimiter": r"\s",
"encoding": "UTF-8"
... |
"""
WSGI config for rotations 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.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWh... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user', '0002_auto_20170818_1829'),
('user', '0030_auto_20170818_0748'),
('user', '0021_auto_20170818_0251'),
]
operations = [
] |
import numpy as np
from ivf.np.norm import normalizeVector
def LdotN(L, N_32F):
L = normalizeVector(L)
h, w = N_32F.shape[:2]
N_flat = N_32F.reshape((-1, 3))
LdN_flat = np.dot(N_flat, L)
LdN = LdN_flat.reshape(h, w)
return LdN
class Shader(object):
def __init__(self):
super(Shader, s... |
import io
import json
import os
import socket
import ssl
import tempfile
import unittest
import warnings
import six
from six.moves import urllib
import notrequests as nr
def _url(path):
# See README on how to use a local httpbin instance for testing.
base_url = os.environ.get('NOTREQUESTS_TEST_URL', 'http://htt... |
import dataset
def connect():
"""
Connect to the database.
"""
db = dataset.connect('sqlite:///photostreamer.db')
return db
def set(key, value):
"""
Set a setting in the database settings table.
"""
db = connect()
settings = db['settings']
if settings.find_one(key = key):
settings.update(dict(key=key, valu... |
from __future__ import unicode_literals
from flask import views, render_template
from express.blueprints import blueprint_www
class IndexView(views.MethodView):
'''
首页
'''
def get(self):
return render_template('www/index.html')
blueprint_www.add_url_rule('/', view_func=IndexView.as_view(b'in... |
'''Take a comma-delimited, double quote-quoted csv and update ENCODE objects appropriately'''
import requests
import json
import os
import csv
import subprocess
import time
import logging
import common
from encodedcc import ENC_Key, ENC_Connection, ENC_Item
logger = logging.getLogger(__name__)
EPILOG = '''Notes:
Re... |
'''
The MIT License (MIT)
Copyright (c) 2014 Jaime Ortiz
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, modif... |
from . import error
from . import function_type
from . import string_utilities
from . import utilities
from . import lexer
from . import preparser
from . import ast_node
class Parser:
def __init__(self):
self._errors = []
def parse(self, preast, functions={}):
self._transform_entity_list(preast,... |
'''Classes which support the Queryable interface.'''
import heapq
import itertools
import operator
from asq.selectors import make_selector
from .selectors import identity
from .extension import extend
from asq.namedelements import IndexedElement, KeyedElement
from ._types import (is_iterable, is_type)
from ._portabilit... |
import math
import os
import sys
import unittest
sys.path.insert(0, os.path.abspath('..'))
import ec.common
class BearingTests(unittest.TestCase):
def test_exception_wrong_type(self):
with self.assertRaisesRegex(ValueError, 'bearing needs to'):
ec.common.Bearing("AA")
def test_above_range_de... |
import sys
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxsize
# Mark all nodes unvisited
self.visited = False
# Predecessor
self.previous = None
def add_nei... |
mass = 240.79500 / 7 / 1000.0 / 6.0221415e23 # average atomic mass in ?kg/atom?
N = 1.0 # number of atoms per unit cell (related to density…)
V = 9.51215e-30 # volume in ?m^3?
density = mass / V # mass density in ?kg/m^3?
kb = 1.3806504e-23 # Boltzmann's constant, J/atom-K
hbar = 1.05457148e-34 # Planck's constan... |
'''
1044. Lucky Tickets. Easy!
Time limit: 2.0 second
Memory limit: 64 MB
[Description]
The public transport administration of Ekaterinburg is anxious about the fact
that passengers don’t like to pay for passage doing their best to avoid the
fee. All the measures that had been taken (hard currency premiums for all of
t... |
from urllib import urlretrieve
import re
import argparse
from time import sleep
import os
import sys
import codecs
import htmlentitydefs
import signal
import random
import json
first_cache_miss = True
def sleep_if_necessary():
global first_cache_miss
if not(first_cache_miss):
sleep(args.sleep_time)
first_cache_mis... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0003_job_run_time'),
]
operations = [
migrations.AlterField(
model_name='job',
name='pid',
field=models.CharF... |
import ast
import inspect
import formater
def scope(func):
func.scope = True
return func
class JSError(Exception):
pass
class JS(object):
name_map = {
'self' : 'this',
'True' : 'true',
'False' : 'false',
'None' : 'null',
'int' : '_int',
'float' : '_f... |
"""
Container location mapper.
"""
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from thelma.entities.container import Tube
from thelma.entities.container import TubeLocation
from thelma.entities.rack import RackPosition
from thelma.entities.rack import TubeRack
__docformat__ = 'reStructured... |
from bottle import route, request, run
def run_webserver(worker, host, port):
# Set up the bottle endpoint
@route('/do/<command>', method='POST')
def do_command(command):
kwargs = dict(request.json)
worker.do(command, **kwargs)
return {}
run(host=host, port=port) |
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='Author',
fields=[
('id',... |
import csv
import sys
if len(sys.argv) != 3:
print ("Usage: python heirarchical-cluster.py [in file] [out file]")
exit(-1)
in_file = sys.argv[1]
out_file = sys.argv[2]
sortedDistances = [] #Tuples to be sorted by distances.
clusterDistances = {}
clusters = {} # Clusters is a list of tracts in a cluster - number... |
"""Convenience wrapper for running bootstrap directly from source tree."""
from paci.cli import main
if __name__ == "__main__":
main() |
from __future__ import print_function, division
from sklearn import datasets
import math
import matplotlib.pyplot as plt
import numpy as np
import progressbar
from sklearn.datasets import fetch_mldata
from mlfromscratch.deep_learning.optimizers import Adam
from mlfromscratch.deep_learning.loss_functions import CrossEnt... |
"""This module contains the detection code for potentially insecure low-level
calls."""
from mythril.analysis import solver
from mythril.analysis.potential_issues import (
PotentialIssue,
get_potential_issues_annotation,
)
from mythril.analysis.swc_data import REENTRANCY
from mythril.laser.ethereum.state.constr... |
import context
import conf
import api
conf.load()
response = api.api_version()
print("HTTP Status: " + str(response.http_code))
print("Error: " + str(response.error))
print("Errortext: " + response.error_text)
print("Body: " + str(response.response))
if response.is_rersponse_status_ok():
if api.is_minimum_version(r... |
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data) |
"""
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['NotesMaker.py']
DATA_FILES = [('LICENSE'),
('ext', ['ext/__init__.py']),
('ext', ['ext/datetime.py']),
('ext', ['ext/find.py']),
('ext', ['ext/table.py']),
('ext', ['ext/w... |
import random
import logging
import sys
import util
logging.basicConfig(filename="logs/frederic.log", level=logging.DEBUG)
comm = util.Communication()
blah_file = open("blah", "w")
rows = 10
cols = 10
NUM_ITERATIONS = 1000
codes = {'A': 1, 'B' : 2, 'S': 3, 'D': 4, 'P': 5, 'H' : 6, 'M': 7}
sunk = 8
def is_sunken(code):
... |
import hashlib
import logging
import urllib
from tornado import gen
from tornado import httpclient
from tornado.escape import json_decode
from tornado.httputil import url_concat
class RenrenGraphMixin(object):
_OAUTH_AUTHORIZE_URL = "https://graph.renren.com/oauth/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://g... |
"""
Created on Jan 25, 2017
@author: Jafar Taghiyar (jtaghiyar@bccrc.ca)
"""
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from core.helpers import *
from simple_history.models import HistoricalRecords
class Sample(models.Model, FieldValue):
"""
... |
import os
import json
import re
import hermes.factory
from hermes.grammar import NonTerminal
from hermes.hermes_parser import parse, lex
base_dir = os.path.join(os.path.dirname(__file__), 'cases/grammar/')
grammars_dir = os.path.join(os.path.dirname(__file__), 'grammars/')
def get_grammar(directory, name='grammar.hgr')... |
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... |
from gloria.service.decorator import job, task, Property
@job()
class Svc6Job3_1:
'''Svc6Job3_1 description'''
def __init__(self):
print(self.__class__.__name__ + ' __init__')
def run(self):
print 'Hello from {0}'.format(self.__class__.__name__)
@job()
class Svc6Job3_2:
'''Svc6Job3_2 description'''
def __init_... |
from django.db import models
from users.models import Employee, Donor, Secretary, Administrator
from django.contrib.auth.models import AbstractUser, User
from equipments.models import Equipment
class DonationStrategy(models.Model):
def build_donation():
pass
def get_value():
pass
class Donation(... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('petitions', '0009_signature_counter'),
]
operations = [
migrations.AddField(
model_name='petition',
name='disabled_message',
... |
import unittest
from TorrentPython.PeerProvider import *
from TorrentPython.RoutingTable import *
from TorrentPython.TorrentUtils import *
SAMPLE_TORRENT_PATH = '../Resources/sample.torrent'
ROUTING_TABLE_PATH = '../Resources/routing_table.py'
class PeerProviderTest(unittest.TestCase):
def setUp(self):
self... |
daemon = True
bind = '127.0.0.1:8000' |
from cyinterval.cyinterval import Interval, IntervalSet, FloatIntervalSet, DateIntervalSet,\
unbounded, ObjectIntervalSet
from nose.tools import assert_equal, assert_is, assert_not_equal, assert_less,\
assert_less_equal, assert_greater_equal, assert_in, assert_not_in,\
assert_raises, assert_list_equal
from ... |
from __future__ import division, print_function, unicode_literals
import SegmentsPen
from GlyphsApp import *
from Foundation import NSBundle, NSOffsetRect, NSIntersectsRect, NSPointInRect, NSMinX, NSMinY, NSMaxX, NSMaxY
import objc
_path = NSBundle.mainBundle().bundlePath()
_path = _path+"/Contents/Frameworks/GlyphsCor... |
from .Configuration import Configuration
from .PointSource import PointSource
from .Sersic import Sersic
from .Sky import Sky |
import json
import urllib2
import commands
import pickle
import os
import weasyprint
import jinja2
import argparse
import ConfigParser
import qrcode
import qrcode.image.svg
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argumen... |
import time
__author__ = 'sking32'
class PreR(object):
"""Implement transformation of the packet-analyzer output.
The PreR object knows how to
process one packet at a time,
give the current result and
reset its own state.
"""
def __init__(self, f):
self.__f = f
self.__start_t... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'palette.views.index', name='palette-index'),
url(r'^(?P<slug>[\w\d_-]+)/$', 'palette.views.palette_detail', name='palette-detail'),
) |
DNASeq = raw_input("Enter a DNA sequence:")
print 'Sequence:', DNASeq
Seqlength=float(len(DNASeq))
print 'Sequence Length:', Seqlength
NumberA=DNASeq.count('A')
NumberC=DNASeq.count('C')
NumberG=DNASeq.count('G')
NumberT=DNASeq.count('T')
print 'A:', NumberA/Seqlength
print 'C:', NumberC/Seqlength |
x = 0
for i in range(0,4):
x = 2 *i |
from django.conf.urls import patterns, url
urlpatterns = [
url(r'^link/$', 'squeezemail.views.link_click', name='link'),
#url(r'^link/(?P<link_hash>[a-z0-9]+)/$', 'squeezemail.views.link_hash', name='link_hash'),
#url(r'^(?P<tracking_pixel>.*?).png', tracking_pixel, name="tracking_pixel"),
url(r'^pixel.png'... |
"""empty message
Revision ID: a73e9ebc3f55
Revises: 71a988ebf4ca
Create Date: 2017-05-30 18:32:03.253502
"""
revision = "a73e9ebc3f55"
down_revision = "71a988ebf4ca"
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
... |
import time
def search_01 (stdout=[]):
package = {}
if not ('package \'dnsmasq\' not found.') in stdout:
for line in stdout:
if line.startswith('Repository:'):
package['repository'] = line.split(': ')[1].strip()
if line.startswith('Version:'):
pack... |
import re
import enum
import binascii
import datetime
class TimestampFormat(enum.Enum):
"""Describes a type of timestamp. ABSOLUTE is referring to UNIX time
(seconds since epoch). RELATIVE is seconds since start of log, or time
since last frame depending of the contents of the log file. MISSING means
th... |
from __future__ import absolute_import, division, print_function, unicode_literals
from echomesh.util import Log
from echomesh.element import Element
LOGGER = Log.logger(__name__)
class Handler(Element.Element):
def __init__(self, parent, description):
super(Handler, self).__init__(parent, description)
... |
class Constantes:
mOperacionSelect="SEL"
mOperacionInsert="INS"
mOperacionUpdate="UPD"
mOperacionDelete="DEL"
#Modulos
mModuleMesa = "GT"
mModuleOrden = "GO"
#ModuloMesa
mGTOperacionReservarMesa = "RME"
mGTOperacionDesocuparMesa = "DME"
mEstadoLibre = "L"
mEstadoOcupada = "O"
#ModuloOrden
mGOEstadoSer... |
from directory.models import StaticPage
def static_pages(request):
all_static_pages = StaticPage.objects.all()
return {
'static_pages': all_static_pages,
} |
"""
Database utility functions.
"""
from typing import Optional
from asyncpg import Record
from asyncpg.pool import Pool
def parse_record(record: Record) -> Optional[tuple]:
"""
Parse a asyncpg Record object to a tuple of values
:param record: the asyncpg Record object
:return: the tuple of values if it... |
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, render
from django import forms
from .models import Images, Events
from .forms import PhotoForm, EventsForm, RegisterForm
from django.contrib.auth.decorators import lo... |
import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.p... |
from fastapi.testclient import TestClient
from docs_src.security.tutorial003 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/token": {
"post": {
"responses": {
"2... |
import uuid
import supriya.commands
import supriya.realtime
from supriya.patterns.Event import Event
class SynthEvent(Event):
### CLASS VARIABLES ###
__slots__ = ()
### INITIALIZER ###
def __init__(
self,
add_action=None,
delta=0.0,
is_stop=False,
synthdef=None,
... |
from django.conf.urls import include, url, patterns
from django.conf import settings
from apps.reader import views as reader_views
from apps.social import views as social_views
from apps.static import views as static_views
from apps.profile import views as profile_views
from django.contrib import admin
admin.autodiscov... |
"""Bridge control utilities.
"""
import os
import os.path
import re
import sys
CMD_IFCONFIG = 'ifconfig'
CMD_ROUTE = 'route'
CMD_BRCTL = 'ovs-vsctl'
CMD_IPTABLES = "iptables"
opts = None
class Opts:
def __init__(self, defaults):
for (k, v) in defaults.items():
setattr(self, k, v)
p... |
import datetime
from django.core.management.base import BaseCommand
from django.utils import timezone
from email_confirm_la.conf import configs
from email_confirm_la.models import EmailConfirmation
class Command(BaseCommand):
def handle(self, **options):
expiration_time = timezone.now() - datetime.timedelta... |
from msrest.service_client import ServiceClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .operations.parameter_grouping_operations import ParameterGroupingOperations
from . import models
class AutoRestParameterGroupingTestServiceConfiguration(AzureConfiguration):
d... |
class DbItem:
"""
Represents a generic item which can be added/updated/deleted/retrieved to a
database.
Each dbItem consists of a unique identifier and a set of tags(which are simple key-value pairs).
"""
def __init__(self, id, tags=None):
"""
Instantiates a new dbItem object.
Requires a 'id' pa... |
from future import standard_library
standard_library.install_aliases()
from urllib.parse import urlparse
from html.parser import HTMLParser
import requests
def authenticate(url, username, password):
''' Queries an asset behind CMU's WebISO wall.
It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/t... |
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
"""
EOF analysis
"""
from pycmbs.examples import download
import matplotlib.pyplot as plt
from pycmbs.diagnostic import EOF
plt.close('all')
air = download.get_sample_file(name='air')
air.labe... |
"""
lassie.helpers
~~~~~~~~~~~~~~
This module contains the set of helper functions executed by Lassie methods.
"""
from .compat import str
import locale
import re
CLEANER = re.compile(r'[\r\n\t]')
RE_INT = re.compile(r'\d+')
def clean_text(value):
"""Removes all line breaks, new lines and tabs from the specified co... |
import ImageManipulator
import glob
from PIL import Image
processor = ImageManipulator.ImageManipulator()
stopP = ImageManipulator.IMStop()
roadP = ImageManipulator.IMRoad()
images = glob.glob('images/**/*.*')
for item in images:
try:
pil_im = Image.open(item)
except IOError:
print("\n error ope... |
import shutil
import os
from subprocess import Popen, PIPE
from tempfile import mkdtemp
from unittest import TestCase
from tipi import (execute_from_command_line, CommandDispatch, get_commands,
call_command,)
from tipi.commands.base import BaseCommand, CommandError
class CommandRunner(object):
"""... |
from setuptools import setup, find_packages
__version__ = '1.0.1'
setup(
name='maildocker',
version=str(__version__),
packages=find_packages(),
description='Maildocker library for Python',
long_description=open('./README.rst').read(),
install_requires=['urllib2'],
) |
from ..lazy import lazify
from .kernel import Kernel
class ProductStructureKernel(Kernel):
r"""
A Kernel decorator for kernels with product structure. If a kernel decomposes
multiplicatively, then this module will be much more computationally efficient.
A kernel function `k` has product structure if it ... |
"""
A wrapper around a 32-bit C++ library, :ref:`example_cpp_lib32
<example-cpp-lib32-header>`, using :class:`ctypes.CDLL`.
Example of a server that loads a 32-bit shared library, :ref:`example_cpp_lib32
<example-cpp-lib32-header>`, in a 32-bit Python interpreter to host the library.
The corresponding :mod:`~.cpp64` mo... |
"""Old parser tests."""
import os
import re
import pytest
from pydocstyle.violations import Error, ErrorRegistry
from pydocstyle.checker import check
from pydocstyle.config import ConfigurationParser
DEFAULT_PROPERTY_DECORATORS = ConfigurationParser.DEFAULT_PROPERTY_DECORATORS
@pytest.mark.parametrize('test_case', [
... |
from tg import expose, TGController, AppConfig
from wsgiref.simple_server import make_server
import urllib.request
import threading
import time
class RootController(TGController):
@expose()
def index(self):
return 'Hello World'
def testWebServer():
print("Hosting server")
config = AppConfig(mini... |
from sd2wiki.techs import buildings
result = '{|class = "wikitable sortable"\n'
result += '! Icon !! Building !! Description !! Requires technology !! Cost !! Maintenance \n'
for buildingUID in sorted(buildings):
building = buildings[buildingUID]
result += '|-\n'
result += '| [[File:%s.png]] || %s || %s ' %... |
import unittest
import mock
import archivey
class TestArchivey(unittest.TestCase):
def setUp(self):
self.blips = {}
for i in range(20):
blip = mock.Mock(spec=['is_root'])
blip.name = "blip "+str(i)
blip.is_root.return_value = False
blip.last_modified_time = i
self.blips[blip.name] = blip
self.wave... |
from hashlib import sha1
from werkzeug.http import is_resource_modified
from flask import Response, request
from grano.core import app
class NotModified(Exception):
pass
@app.errorhandler(NotModified)
def handle_not_modified(exc):
return Response(status=304)
def generate_etag(keys):
args = sorted(set(reques... |
import MapReduce
import sys, copy
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
def mapper(record):
# record: a list of strings representing a tuple in the database
# key: order id
# value: record
key = record[1]
value = record
mr.emit_intermediat... |
"""Utilities."""
from uuid import uuid4
PACKABLE_TYPES = {}
class PackableType:
"""Packable type description."""
_pack_identifier = None
_pack_header_fmt = None
def __init_subclass__(cls, **kwargs):
"""Create subclass."""
super().__init_subclass__(**kwargs)
if hasattr(cls, "_pack... |
"""
Hamper
Usage:
hamper.py auth login --email=<email> --password=<password>
hamper.py cert create (development | development_push | distribution | distribution_push) --csr_path=<csr_path> --cert_path=<cert_path> [--bundle_id=<bundle_id>]
hamper.py identifier create --app_name=<app_name> --bundle_id=<bundle_id> [... |
import sys, os, six
from zope.interface import Interface, implementer
from twisted.trial import unittest
from twisted.trial.unittest import TestCase, SynchronousTestCase
from twisted.internet import error, protocol, defer, reactor
from twisted.protocols import policies
from twisted.python import log, filepath
from axio... |
from xmra.repositories.local.db import engine
from xmra.repositories.local.db import Base
def main():
# con = engine.connect()
# trans = con.begin()
#
# con.execute(table.delete())
# trans.commit()
for table in Base.metadata.sorted_tables:
if table in engine.table_names():
ta... |
"""
WSGI config for django_automata 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.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def route(root):
root_height = root[2]
coordinates = [\
[0.42*root_height+root[0],0.42*root_height+root[1],root_height/2],\
[-0.42*root_height+root[0],0.42*root_height+root[1],root_height/2],\
[-0.42*root_height+root[0],-0.15*root_height+root[1],roo... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('challenges', '0005_auto_20160213_1503'),
]
operations = [
migrations.AlterField(
model_name='challenge',
name='end_date',
... |
revision = '488b68c48fe'
down_revision = '4939e91a8b3'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.drop_column('person', 'cdep_id')
op.drop_column('person', 'minority')
op.drop_column('person', 'county_id')
op.drop_column('question', 'perso... |
from common import Modules, data_strings, load_yara_rules, PEParseModule, ModuleMetadata, is_ip_or_domain
import struct
class abaddon(PEParseModule):
def __init__(self):
md = ModuleMetadata(
module_name="abaddon",
bot_name="Abaddon",
description="Point of sale malware des... |
'''
Processed BCSD-orig 20-year average country-level data by model
Aggregated to impact regions using area weights. Produced from BCSD-originals
using the GCP climate toolbox at https://github.com/ClimateImpactLab/pipelines
'''
from __future__ import absolute_import
import os
import pipelines
import pipelines.climate.... |
from django.db import models
from django.test import TestCase
from asynchrormous.models import AsyncManager
from asynchrormous.query import AsyncQuerySet
class AsyncModel(models.Model):
objects = AsyncManager()
field1 = models.IntegerField(default=0)
field2 = models.CharField(max_length=100)
class BasicBeha... |
"""
clearance dataset loader.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import deepchem
def load_clearance(featurizer='ECFP', split='random'):
"""Load clearance datasets."""
# Featurize clearance dataset
print("About to featurize cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.