code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
from types import MethodType
from django.core.checks import Error
from django.db import connection, models
from .base import IsolatedModelsTestCase
class BackendSpecificChecksTests(IsolatedModelsTestCase):
def test_check_field(self):
""" Test if backend specific check... |
import github.GithubObject
class HookResponse(github.GithubObject.NonCompletableGithubObject):
"""
This class represents HookResponses as returned for example by http://developer.github.com/v3/todo
"""
@property
def code(self):
"""
:type: integer
"""
return self._code... |
def f():
if True:
c = 1
a = 1 |
if (A and
B):
print |
<caret>a = 1 # surprise!
b = 2 |
"""
Formtools Preview application.
"""
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.crypto import constant_time_compare
from django.contrib.formtools.utils import form_hmac
AUTO_ID = 'formtools_%s' # Each form here ... |
"""
Form Widget classes specific to the Django admin site.
"""
from __future__ import unicode_literals
import copy
from django import forms
from django.contrib.admin.templatetags.admin_static import static
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.forms... |
import os
ccdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
template = """<!DOCTYPE html>
<meta charset=utf-8>
"""
errors = {
"dl-in-p": "<p><dl><dt>text<dd>text</dl></p>",
"header-in-dt": "<dl><dt><header>text</header><dd>text</dl>",
"footer-in-dt": "<dl><dt><footer>text</footer><dd>text<... |
import os
import urlparse
from StringIO import StringIO
blacklist = ["/", "/tools/", "/resources/", "/common/", "/conformance-checkers/", "_certs"]
def rel_path_to_url(rel_path, url_base="/"):
assert not os.path.isabs(rel_path)
if url_base[0] != "/":
url_base = "/" + url_base
if url_base[-1] != "/":... |
import config
PAYMENT_PROCESSOR=True |
"""Support code for Ansible testing infrastructure.""" |
"""
The sax module contains a collection of classes that provide a
(D)ocument (O)bject (M)odel representation of an XML document.
The goal is to provide an easy, intuative interface for managing XML
documents. Although, the term, DOM, is used above, this model is
B{far} better.
XML namespaces in suds are represented u... |
instance = None # noqa |
import argparse
import json
from lib.parse_usage import parse_usage
def main():
parser = argparse.ArgumentParser(
description="Converts VPR pack.log into usage numbers."
)
parser.add_argument('pack_log')
parser.add_argument(
'--assert_usage',
help='Comma seperate block name list ... |
import os
def CommandExecution(argument):
file_to_delete = argument
try:
os.remove(file_to_delete)
except:
print("ERROR: File isn't exists or access denied") |
from openwifi import attwifi
__author__ = "mutantmonkey <mutantmonkey@mutantmonkey.in>"
__license__ = "ISC"
if __name__ == '__main__':
n = attwifi.AttWifi()
if not n.connected():
n.login()
print("Connected.")
else:
print("You are already connected.") |
__all__ = ['errors', 'views'] |
import copy, utils.log, random
from utils.utils import randGaussBounds
from logic.smbool import SMBool, smboolFalse
from logic.smboolmanager import SMBoolManager
from logic.helpers import Bosses
from graph.graph_utils import getAccessPoint, GraphUtils
from rando.Filler import FrontFiller
from rando.FillerRandom import ... |
from __future__ import absolute_import
from surveymonkey.webhooks.webhooks import Webhook
__all__ = ['Webhook'] |
import os
class ComplexityConfig(object):
def __init__(self, source_paths, ignore_paths=None, complexity_threshold="B", ignore_block_list=None, **kwargs):
"""
:param source_paths: List of source paths to analyze
:param ignore_paths: Path patterns to ignore (such as *tests*)
:param co... |
'''
Created on May 25, 2012
@author: kwalker
'''
'''
notes:
-conversion to shape shortens long field names and that can mess stuff up.
'''
import arcpy, os, math
arcpy.env.overwriteOutput = True
inRoutesFullPath = arcpy.GetParameterAsText(0)
referencePoints = arcpy.GetParameterAsText(1)
lrsSchemaTemplate = arcpy.GetPar... |
from wtforms import SelectField
import pycountry
class CountrySelectField(SelectField):
def __init__(self, *args, **kwargs):
super(CountrySelectField, self).__init__(*args, **kwargs)
self.choices = [(country.alpha2, country.name) for country in pycountry.countries] |
from pytest import raises
from dbfread import DBF
from dbfread import MissingMemoFile
def test_missing_memofile():
with raises(MissingMemoFile):
DBF('tests/cases/no_memofile.dbf')
# This should succeed.
table = DBF('tests/cases/no_memofile.dbf', ignore_missing_memofile=True)
# Memo fields should... |
import numpy as np
import random
import tensorflow as tf
from collections import deque
from setuptools.sandbox import save_path
class DiscreteDeepQ(object):
def __init__(self, observation_size,
num_actions,
observation_to_actions,
optimizer,
... |
"""
Just list clusters and number of members to enable sorting and summarizing!
"""
import os
import sys
import argparse
import re
__author__ = 'Rob Edwards'
__copyright__ = 'Copyright 2020, Rob Edwards'
__credits__ = ['Rob Edwards']
__license__ = 'MIT'
__maintainer__ = 'Rob Edwards'
__email__ = 'raedwards@gmail.com'
d... |
import os
import sys
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'findyour3d'
copyright = """2017, Oleksii Dubniak"""
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
ht... |
from django.contrib import admin
from .models import *
admin.site.register(Employee)
admin.site.register(Table)
admin.site.register(Order)
admin.site.register(Item)
admin.site.register(DynamicOrder)
admin.site.register(OrderList)
admin.site.register(Shift) |
"""
WSGI config for owlfcoffe 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_SETTING... |
import sys
limit = 1000000
primes = [ 2 ]
def is_prime(candi):
for i1 in range(0, len(primes)):
p1 = primes[i1]
if p1 * p1 > candi:
break
if candi % p1 == 0:
return False
return True
lastprime = 3
maxgap = 0
for c1 in range(3, limit, 2):
if is_prime(c1):
... |
import json
import re
import scrapy
from locations.items import GeojsonPointItem
class McDonaldsNLSpider(scrapy.Spider):
name = "mcdonalds_nl"
allowed_domains = ["mcdonalds.nl"]
def start_requests(self):
url = 'https://mcdonalds.nl/restaurant'
headers = {
'Accept-Language': 'en-U... |
from zfscan.ui.MainWindow import MainWindow
MainWindow(800, 400) |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
from random import uniform
from Solid.HarmonySearch import HarmonySearch
class Algorithm(HarmonySearch):
"""
Tries to get a randomly-generated list to match [.1, .2, .3, .2, .1]
"""
def _random_harmony(self):
return list([uniform(0, 1) for _ in range(5)])
def _score(self, member):
re... |
from pyramid.view import view_config
from .assets import (
convert_to_utc_seconds,
convert_to_datetime,
create_recording,
delete_recording,
get_action,
TunerUnavaliable,
TunerDoesNotExist,
InvalidTimeRange,
RecordingDoesNotExist,
)
from .models import (
DBSession,
Recording,
... |
import unittest
from lattice_mc import jump as jump_module
from lattice_mc.lattice_site import Site
from lattice_mc.lookup_table import LookupTable
from unittest.mock import Mock, patch
import numpy as np
Jump = jump_module.Jump
class JumpTestCase( unittest.TestCase ):
"""Test for Jump class"""
def setUp( self ... |
"""
flask_via.examples.mixed
========================
Mixed router example.
"""
from flask import Flask
from flask.views import MethodView
from flask.ext import restful
from flask.ext.via import Via
from flask.ext.via.routers.default import Functional, Pluggable
from flask.ext.via.routers.restful import Resource
class ... |
import sys
from datetime import datetime
class DummyReader:
def __init__(self):
self.timestamp = '161218232000'
self.trigger = False
def readPacket(self):
if self.trigger:
raise Exception('DummyReader')
self.timestamp = str(int(self.timestamp) + 10)
self.trigg... |
from __future__ import print_function
import codecs
import inspect
import json
import logging
import os
import re
import progressbar
from sanskrit_parser.base.sanskrit_base import SanskritObject, ITRANS
from sanskrit_parser.lexical_analyzer.sanskrit_lexical_analyzer import SanskritLexicalAnalyzer
logger = logging.getLo... |
"""A key-value storage database."""
from basestore import BaseStore
class KVStore(BaseStore):
def __init__(self):
super(KVStore, self).__init__() |
from __future__ import print_function
from django.forms.utils import to_current_timezone
from jalali_date import settings
import jdatetime
def date2jalali(g_date):
return jdatetime.date.fromgregorian(date=g_date) if g_date else None
def datetime2jalali(g_date):
if g_date is None:
return None
g_date ... |
"""An attempt to be able to parse 80% of feeds that feedparser would parse
in about 1% of the time feedparser would parse them in.
LIMITATIONS:
* result.feed.namespaces will only contain namespaces declaed on the
root object, not those declared later in the file
* general lack of support for many types of feeds
*... |
from django.core.management.base import BaseCommand, CommandError
from cc.util import HeaderedRow
from cc.models import *
from collections import Counter
import ipdb
import os, stat, csv
import json
class Command(BaseCommand):
"""Takes mturk repsonse CSV from [source], and loads into database."""
def handle(sel... |
import json
class UnableToResolveValue(KeyError):
pass
class Expression:
@property
def value(self):
raise NotImplementedError()
def __repr__(self):
return str(self)
class SimpleExpression(Expression):
def __init__(self, value):
self._value = value
@property
def value(... |
messages_str = ""
services_str = "/home/holy/HOly/holy/src/dynamixel_motor/dynamixel_controllers/srv/RestartController.srv;/home/holy/HOly/holy/src/dynamixel_motor/dynamixel_controllers/srv/SetComplianceMargin.srv;/home/holy/HOly/holy/src/dynamixel_motor/dynamixel_controllers/srv/SetCompliancePunch.srv;/home/holy/HOly/... |
__author__ = 'Lucian'
values = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2']
colors = ['C', 'D', 'H', 'S']
fibonacci_weight = ['3', '5', '8', '13', '21', '34', '55', '89', '144', '233', '377', '610', '987', '1597', '2584']
color_names = ('Clubs', 'Diamonds', 'Hearts', 'Spades')
DECK_SIZE = 52
combo_... |
"""
Landlab's Continuous-Time Stochastic (CTS) cellular automata modeling package.
Overview
--------
A CellLab CTS model implements a particular type of cellular
automaton (CA): a continuous-time stochastic CA. The approach is based on that
of Narteau et al. (2002, 2009) and Rozier and Narteau (2014). Like a normal
CA,... |
import os
import sys
from fnmatch import fnmatchcase
from setuptools import setup, find_packages
from distutils.util import convert_path
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
standard_exclude = ["*.py", "*.pyc", "*~", ".*", "*.bak", "Makefile"]
standard_exclude_directories = [
"... |
"""
resources.base
~~~~~~~~~~~~~~
Base resource object.
This should be sub-classed by other more mature resource
handlers. It's utility is providing common tasks & error handling
for all resources.
"""
import types
class Resource(object):
""" Base resource class """
DESERIALIZERS = []
... |
from datetime import timedelta
from django.conf import settings as django_settings
try:
from django.contrib.auth import get_user_model
except ImportError:
from django.db.models import get_user_model
class MissingOneAllSettings(KeyError):
def __init__(self, msg=None):
msg = 'Missing or invalid settin... |
from base64 import urlsafe_b64decode, urlsafe_b64encode
import config
from datetime import datetime
import flask
import GeoIP
import geoip2.errors
import geoip2.database
import glob
import hashlib
import json
import logging
from netaddr import IPNetwork
import os
import random
import re
import requests
import string
fr... |
import os
from direct.task.Task import Task
import cPickle
from otp.ai.AIBaseGlobal import *
import DistributedBuildingAI
import HQBuildingAI
import GagshopBuildingAI
import PetshopBuildingAI
from toontown.building.KartShopBuildingAI import KartShopBuildingAI
from toontown.building import DistributedAnimBuildingAI
from... |
'''
EC2 external inventory script
=================================
Generates inventory that Ansible can understand by making API request to
AWS EC2 using the Boto library.
NOTE: This script assumes Ansible is being executed where the environment
variables needed for Boto have already been set:
export AWS_ACCESS_KE... |
from __future__ import unicode_literals
from unittest import SkipTest, TestCase
import sys
import ivoire
class _ShouldStop(Exception):
pass
_MAKE_UNITTEST_SHUT_UP = "__init__"
class Example(TestCase):
"""
An ``Example`` is the smallest unit in a specification.
"""
def __init__(self, name, group, bef... |
from ansible.module_utils.basic import *
DOCUMENTATION = '''
---
module: cassandra_user
short_description: user management for Cassandra databases
description:
- Adds or removes users from Cassandra databases
- Sets or changes passwords for Cassandra users
- Modifies the superuser status for Cassandra users
- Be aware ... |
import unittest
import pysony
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_loadpysony(self):
api = pysony.SonyAPI()
self.assertEqual(api.QX_ADDR, 'http://10.0.0.1:10000')
if __name__ == '__main__':
unittest.main() |
"""
PyAudio provides Python bindings for PortAudio, the cross-platform
audio I/O library. With PyAudio, you can easily use Python to play and
record audio on a variety of platforms. PyAudio is inspired by:
* pyPortAudio/fastaudio: Python bindings for PortAudio v18 API.
* tkSnack: cross-platform sound toolkit for Tcl/T... |
from comment.forms import CommentForm
from comment.models import Comment
class CommentShowMixin(object):
def get_comments(self):
target = self.request.path
return Comment.objects.filter(target=target)
def get_context_data(self, **kwargs):
kwargs.update({
'comment_form': Comme... |
"""mysite 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')
Class-based... |
""" This is algos.euler.views module.
This module provides the view of the REST API from the Euler algo.
"""
from algos.euler.models import training_samples as ts
from algos.euler.models import predictions
from algos.euler.serializers import PredictionSerializer, PriceChangeSerializer
from rest_framework.response i... |
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def get_title(url):
try:
html = urlopen(url)
except HTTPError:
return None
try:
bsObj = BeautifulSoup(html.read())
title = bsObj.body.h1
except AttributeError:
retu... |
import datetime
from app.extensions import db
class User(db.Document):
username = db.StringField(required=True, unique=True)
email = db.EmailField(required=True, unique=True)
firstname = db.StringField(required=True)
lastname = db.StringField(required=True)
password = db.StringField(required=True)
... |
import re
from setuptools import setup, find_packages
INSTALL_REQUIRES = ("marshmallow>=2.15.2",)
EXTRAS_REQUIRE = {
"lint": [
"flake8==3.8.4",
'flake8-bugbear==20.11.1; python_version >= "3.5"',
"pre-commit~=2.4",
],
"tests": ["pytest", "mock", "webargs>=0.11.0", "WTForms>=2.0.1", "... |
from docutils import core
from docutils.writers.html4css1 import Writer,HTMLTranslator
class NoHeaderHTMLTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self,document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
... |
class LRUCache(object):
'''
Implements an LRU cache based on a linked list.
Performance is about 1.1 microseconds per set/get on a core i7
'''
def __init__(self, maxlen=10000):
self.map = {}
self.root = root = []
root[:] = [root, root]
self.maxlen = maxlen
def __g... |
from djangoappengine.settings_base import *
import os
PROJECT_PATH = os.path.realpath(os.path.dirname('__file__'))
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '111.222.333.444', 'appspot.com', 'ayushgargspoj.appspot.com','spojstalker.appspot.com']
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your... |
import pytest
import hypothesis
import hypothesis.strategies as st
from verta._protos.public.monitoring import Alert_pb2 as _AlertService
from verta.monitoring.alert.status import (
Alerting,
Ok,
)
class TestAlerting:
@hypothesis.given(
sample_ids=st.lists(
st.integers(min_value=1, max_v... |
from abc import ABCMeta
import docker
MOUNTABLE_TEMP_DIRECTORY = "/tmp"
docker_client = docker.from_env()
class UseInTestError(Exception):
"""
Base class for all custom exceptions defined in this package.
"""
class MissingDependencyError(UseInTestError):
"""
Raised when an optional package is not in... |
from .experiment import *
from .misc import *
from glimpse.models.ml import Layer, Model, Params, State
from glimpse.models.base import BuildLayer |
""" This program implements a parser and data structure for Petri net files.
This program implements an XML parser and a python data structure for
Petri nets/PNML created with VipTool or MoPeBs.
"""
import sys # argv for test file path
import xml.etree.ElementTree as ET # XML parser
import time # timestamp for id gener... |
"""Raspberry Pi Face Recognition Treasure Box
Face Detection Helper Functions
Copyright 2013 Tony DiCola
Functions to help with the detection and cropping of faces.
"""
import cv2
import config
haar_faces = cv2.CascadeClassifier(config.HAAR_FACES)
haar_eyes = cv2.CascadeClassifier(config.HAAR_EYES)
def detect_single(im... |
import os
import libcnml
from ..exceptions import ParserError
from .base import BaseParser
try:
import urlparse
except ImportError:
from urllib import parse as urlparse
class CnmlParser(BaseParser):
""" CNML 0.1 parser """
protocol = 'static'
version = None
metric = None
def to_python(self, ... |
import unittest
import os
import tempfile
import numpy as np
from numpy import ma
from numpy.testing import assert_array_almost_equal
from netCDF4 import Dataset, default_fillvals
class SetAutoScaleTestBase(unittest.TestCase):
"""Base object for tests checking the functionality of set_auto_scale()"""
def setUp(... |
gunzip='/usr/sbin/gunzip'
def main():
#
# Run pKa calculations in all subdirs given as argument
#
import sys
print
print 'Run pKa calculations in all subdirs. '
print
print 'Looking for pdb files with the name: %s' %sys.argv[1]
print 'Running pKa calculations for: '
import os, sy... |
"""
Django settings for actofgoods 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 psycop... |
import os
PDBdir=os.path.join(os.getcwd(),'PDBs')
if not os.path.isdir(PDBdir):
os.mkdir(PDBdir)
class pKa_contact_order:
"""Class for calculating the pKa contact order of proteins"""
def __init__(self,pdbfiles):
for pdbfile in pdbfiles:
PI=self.get_PDB(pdbfile)
RCOs=[PI.calc... |
'''
Author : Zachary Harvey
'''
from PyQt5 import QtGui
class CardItem(QtGui.QStandardItem):
def __init__(self, card, *args):
self.card = card
self.iconpath = DEFAULT_CARD_ICON
if len(args):
super().__init__(*args)
else:
if self.iconpath is None:
... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('book', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='book',
name='name',
field=models.CharFiel... |
def _merge(nums, left_index, middle_index, right_index):
inversions = 0
left_size = middle_index - left_index + 1
right_size = right_index - middle_index
left_elements = nums[left_index:left_index + left_size]
right_elements = nums[middle_index + 1:middle_index + right_size + 1]
left, right, ind... |
import os, re, json
from cgi import parse_qs
from time import time
try:
from hashlib import md5
except ImportError:
import md5 as _md5
md5 = _md5.new
def uniq_id():
return md5(str(time())).hexdigest()
def valid_token():
query = parse_qs(os.environ['QUERY_STRING'])
if not query.has_key('token'):
... |
""" fetch_all_subreddits.py - Gathers metadata of all subreddits currently on Reddit """
__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__license__ = "MIT"
import json
import csv
import time
import requests
def write_to_csv(subreddit_writer, parsed_json)... |
from gurobipy import *
import numpy as np
import pandas as pd
points = "Points"
salary = "Salary"
position = "Position"
def optimize(player_names, player_data):
varbs = {} # key: player name, value : var
m = Model()
for p in player_names:
varbs[p] = m.addVar(vtype=GRB.BINARY, name = p)
m.update... |
"""config.py: TODO"""
import os
import bottle as app
ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC = '{base}/static'.format(base=ROOT)
DATABASE = os.path.join(ROOT, 'db.sqlite3')
SESSION = os.path.join(ROOT, 'cache')
BASE_URI = 'http://mydomain.tld'
SESSION_TYPE = 'file'
SESSION_AUTO = True
SERVER = 'wsgiref... |
import urllib2
url = "http://www2.census.gov/govs/school/elsec12f.txt"
def download_file(url):
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, f... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='oop_etl_csv',
version='0.0.1',
packages=[''],
url='https://gith... |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class FenxiaoProductGradepriceGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.product_id = None
self.sku_id = None
self.trade_type = None
def getapiname(self... |
from lxml import etree
from healthvaultlib.methods.method import Method
from healthvaultlib.methods.methodbase import RequestBase, ResponseBase
class AuthorizeApplicationRequest(RequestBase):
def __init__(self, appid):
super(AuthorizeApplicationRequest, self).__init__()
self.name = 'AuthorizeApplica... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('snisi_core', '0009_auto_20150415_0902'),
]
operations = [
migrations.AlterModelOptions(
name='snisireport',
options={'ordering': ... |
from lib import primes_up_to
import itertools
from fractions import Fraction
from math import factorial
def compute():
maximum = 100 # inclusive
factorials = [factorial(n) for n in range(0, maximum + 1)]
pairs = [(i, j) for i, j in itertools.product(range(1, maximum + 1), repeat=2) if i > j]
return len(filter(lamb... |
from specter.spec import Spec, DataDescribe
from specter.expect import expect, require, skip_if, incomplete, metadata
class TestObj(object):
def __str__(self):
return '<object>\nbam\ntest'
class ExampleSpec(Spec):
"""Basic File to test scanner and runner"""
def this_is_a_test(self):
"""My ex... |
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
import profiles.urls
import accounts.urls
from . import views
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^about/$', views.AboutPage... |
from datetime import datetime
import operator as op
def frange(start, end=None, inc=None):
"""A range function, that does accept float increments..."""
if end is None:
end = start + 0.0
start = 0.0
if inc is None:
inc = 1.0
L = []
while 1:
next_ = start + len(L) * inc... |
import sys, re, operator, string, inspect
def extract_words(path_to_file):
"""
Takes a path to a file and returns the non-stop
words, after properly removing nonalphanumeric chars
and normalizing for lower case
"""
assert(type(path_to_file) is str), "I need a string! I quit!"
assert(path_to_... |
import os
import sys
import radical.pilot as rp
def pilot_state_cb (pilot, state) :
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED :
sys.exit (1)
def unit_state_change_cb (unit, state) :
"""... |
from graph import *
from utils import *
def royWarshall(g):
closure = g.U
for i in g.X:
for x in g.X:
if (x, i) in closure:
for y in g.X:
if (i, y) in closure:
if (x, y) not in closure:
closure.append((x,... |
import sys
import os
import hashlib
import json
import Geohash
import shapely
from shapely.geometry import shape
from shapely.geometry.point import Point
from rtree import index
from reader import FileReader
from .proj import project, rproject
AWS_BUCKET = "https://s3-us-west-2.amazonaws.com/jeffrey.alan.meyers.bucket"... |
from rest_framework.authentication import (SessionAuthentication,
TokenAuthentication)
from rest_framework.generics import (ListAPIView,
ListCreateAPIView,
RetrieveUpdateDestroyAPIView)
from profiles.mod... |
"""empty message
Revision ID: 230e86b70e59
Revises: 032d311ba5f9
Create Date: 2018-05-17 15:29:57.980559
"""
from alembic import op
import sqlalchemy as sa
revision = '230e86b70e59'
down_revision = '032d311ba5f9'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please... |
"""
Printing writer. Used for testing.
"""
from baseWriter import AbstractFeatureWriter
class PrintFeatureWriter(AbstractFeatureWriter):
def feature(self, name):
print ("feature", name)
return self
def lookup(self, name):
print ("lookup", name)
return self
def featureReferenc... |
"""
from https://codelab.interviewbit.com/problems/diffk2/
"""
class Solution:
# @param A : tuple of integers
# @param B : integer
# @return an integer
def diffPossible(self, A, B):
# all combinations is O(N ^ 2)
s = {A[i]: i for i in range(len(A))}
for i in range(len(A)):
... |
""" Spectroscopy-related functionality """
from __future__ import division, print_function
__author__ = "Andy Casey <arc@ast.cam.ac.uk>"
__all__ = ["Spectrum1D"]
import logging
import os
import numpy as np
import pyfits
class Spectrum1D(object):
"""This is a temporary class holder for a Spectrum1D object until the
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.