code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
readme = f.read()
install_requires = [
'mock',
'decor... | bywires/chara | setup.py | Python | mit | 1,559 |
'''test_style - test coding style
=================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This script runs pep8 on all UMI-tools
This script is best run within nosetests::
nosetests tests/test_style.py
This code is borrowed with permission from https://gi... | CGATOxford/UMI-tools | tests/test_style.py | Python | mit | 2,234 |
import logging
import multiprocessing
import os
import sys
import time
import uuid
from pyjob.cexec import cexec
from pyjob.task import Task
CPU_COUNT = multiprocessing.cpu_count()
logger = logging.getLogger(__name__)
class LocalTask(Task):
"""Locally executable :obj:`~pyjob.task.Task`"""
def __init__(sel... | fsimkovic/pyjob | pyjob/local.py | Python | mit | 4,489 |
from django.conf.urls import url, patterns, include
from . import views
urlpatterns = patterns('django.contrib.auth.views',
url(r'^', include('django.contrib.auth.urls')),
url(r'^register/$', views.RegistrationView.as_view(), name='register'),
url(r'^register/verify/$', 'password_reset', {
'templa... | funkybob/django-dequorum | accounts/urls.py | Python | mit | 1,110 |
#-*- coding:utf-8 -*-
from xml.etree import ElementTree
import os
import base64
import struct
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
CSV_PATH = ROOT_PATH + "/../Resources/json/"
def package_csv():
out_path = os.path.join(CSV_PATH, "config.bin")
f = open(out_path, "w")
for name in os.lis... | helloztq/helloztq.github.io | _drafts/package_res.py | Python | mit | 1,014 |
class ContextEngine:
def run(self):
pass
def get_context(self, room_id, client_id):
pass
def update_context(self, room_id, client_id):
pass
| Matvey-Kuk/cspark-python | cspark/ContextEngine.py | Python | mit | 179 |
import numpy as np
import tensorflow as tf
import tfmodel
def train_input_fn():
x = {"image": tf.constant(np.ones([32, 224, 224, 3]), dtype=np.float32, name="image")}
y = tf.constant(np.zeros([32, 1000], dtype=np.float32), name="label")
return x, y
def main():
warm_start_settings = tf.estimator.Warm... | sfujiwara/tfmodel | example_vgg16.py | Python | mit | 768 |
# error codes
PARAM_REQUIRED = 100
PARAM_INVALID = 101
CSRF_INVALID = 102
NOT_IMPLEMENTED_YET = 103
QUERY_PARAM_INVALID = 104
| zh012/djrest | djrest/constants.py | Python | mit | 126 |
""" DO NOT MODIFY. Auto-generated by build_frontend script """
VERSION = "85f0078ea394a12dd95395799e345c83"
| sanmiguel/home-assistant | homeassistant/components/frontend/version.py | Python | mit | 108 |
import sys
def _get_frame_from_record(record):
"""
takes a exception log record and looks at the traceback object.
Traverses the traceback and finds the inner most call
that takes in a request object as an arguement
This allows more accurate logging for wrapped api's
"""
tb = record.exc_in... | RideScout/django-splunk-logging | django_splunk_logging/utils.py | Python | mit | 891 |
# -*- coding: utf-8 -*-
'''Samples storage module tests
'''
from __future__ import with_statement, division, absolute_import, print_function
from aorn.methods.antest import ANTest
class SampleTest(ANTest):
__doc__ = ''
def analyze(self, _):
pass
def test_antest_init():
try:
ANTest()
... | soutys/aorn | tests/test_methods_antest.py | Python | mit | 878 |
import math
import unittest
from forest.treespecies import TreeSpecies
from forest.tree import Tree
from forest.forest import Forest
class TestForest(unittest.TestCase):
def setUp(self):
self.species = TreeSpecies("birch", 0.1, 10, 3, 0.8, 79, 2)
def test_create(self):
f = Forest(1, None, 10... | DaveTCode/ProceduralForest | tests/TestForest.py | Python | mit | 2,501 |
"""
Ryan Kynor tutorial
"""
from ggame import App, RectangleAsset, ImageAsset, SoundAsset
from ggame import LineStyle, Color, Sprite, Sound
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
green = Color(0x00ff00, 1)
black = Color(0, 1)
noline = LineStyle(0, black)
bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, nol... | ryankynor/ggame-tutorials | tutorial3.py | Python | mit | 1,560 |
__author__ = 'Deniz'
| Murkantilism/LoL_API_Research | Summoner_Data_Retrieval/RiotWatcher/__init__.py | Python | mit | 21 |
import pytest
from peach.rest.base_api import ApiFactory
from peach.database.mongo_proxy import MongoDBProxy
from peach.rest.pagination import Pagination
from peach.rest.response import ResponseDocumentFactory
@pytest.fixture
def data():
return {
'APIS': {
'api': {
'prefix': '... | sebastiandev/peach | tests/test_api_factory.py | Python | mit | 3,107 |
"""
Spatial Variant of Spiegelman's Monster Simulation
Allows templates to move between simulations based on their composition
Author: David Wu
Universty of Auckland
"""
import spiegelman as spg
import run_simulation as rsim
from operator import itemgetter
import pylab
# spatial simulation object
# objec... | chickensuitinvader/spiegelman | computational_python/spatial.py | Python | mit | 8,826 |
import xml.etree.ElementTree as ET
import os
import loc
datadir = 'D:/Steam/steamapps/common/Galactic Civilizations III/data'
tree = ET.parse(os.path.join(datadir, 'Game', 'ShipComponentDefs.xml'))
def manufacturingCost(shipComponent):
result = 0.0
for stats in shipComponent.findall('Stats'):
if 'Man... | ajul/galciv3wikiscripts | modules.py | Python | mit | 755 |
# -*-: coding utf-8 -*-
"""The microphone setup command."""
import time
from ..base import Base
from ...utils.os_helpers import file_exists
from ...utils.os_helpers import is_raspi_os
from ...utils.microphone_setup import MicrophoneSetup, RespeakerMicrophoneSetup
from ...utils.snipsfile import Snipsfile
from ... imp... | snipsco/snipsskills | snipsmanager/commands/setup/microphone.py | Python | mit | 5,031 |
# -*- coding: utf-8 -*-
import sklearn.datasets
import numpy as np
from sklearn.decomposition import PCA
def gen_first_two():
np.random.seed(seed=777)
iris = sklearn.datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
id_list = np.array(["Line{}".format(i) for i in range(len(y))])
idx ... | smly/ume | demo/iris_multiclass_logloss/feat.py | Python | mit | 1,195 |
from django.apps import AppConfig
class DjsanaConfig(AppConfig):
name = "djasana"
verbose_name = "Asana"
def ready(self):
pass
| sbywater/django-asana | djasana/apps.py | Python | mit | 150 |
"""
Bitcoin client that connects to DNS bootstrap connections, grabs addr records,
disconnects after enough records are obtained, and that's that.
"""
import asyncio
import logging
from asyncio.queues import PriorityQueue
from pycoinnet.helpers.standards import initial_handshake
from pycoinnet.helpers.standards impo... | richardkiss/pycoinnet | pycoinnet/helpers/dnsbootstrap.py | Python | mit | 4,607 |
# -*- coding: utf8 -*-
import module
from module import use_module
import fields
class MoistureReducing(module.Base):
public_name = 'Humidite automatique'
fan_actuator = use_module('FanActuator')
moisture_sensor = use_module('MoistureSensor')
moisture = fields.proxy.readable('moisture', 'MoistureSen... | k-team/KHome | modules/moisture_reducing/local_module.py | Python | mit | 1,522 |
def build_root_fs( target, source, env ):
"""
I'm very sorry for this eye bleeding function.
It's setting up a stack that mounts all the disks, and the directories
and activates the lvm volumes. And once all that is done then calls
another function to actually start installing files.
"""
from plumb... | py-yyc/context_managers | examples/build_root_fs.py | Python | mit | 2,219 |
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
import transaction
import custom_class_zodb
filestorage = ZODB.FileStorage.FileStorage('zodb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
noah = custom_class_zodb.Account('noah', 1000)
print (noah)
root['noah'] = noah
jeremy ... | lluxury/P_U_S_A | 12_data_persistence/zodb_custom_class.py | Python | mit | 439 |
import _plotly_utils.basevalidators
class HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator):
def __init__(self, plotly_name="hoverinfo", parent_name="funnelarea", **kwargs):
super(HoverinfoValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,... | plotly/plotly.py | packages/python/plotly/plotly/validators/funnelarea/_hoverinfo.py | Python | mit | 610 |
# -*- coding: utf-8 -*-
"""
I/O routines.
io.py
(c) Will Roberts 23 June, 2017
"""
from __future__ import absolute_import
import codecs
import gzip
import pathlib
import sys
import zipfile
from collections import Counter
from .compat import basestring
try:
import lzma
except ImportError:
try:
imp... | wroberts/wkr.py | wkr/io.py | Python | mit | 3,684 |
import os
import cv2
import numpy as np
path = 'C:\\Users\\toby\\Downloads\\self-driving-car\\training_images_3'
os.chdir(path)
img = cv2.imread("training_image_1502733794000_left.png")
img = img[240:480, 0:640]
img = cv2.blur(img, (5, 5))
b,g,r = cv2.split(img)
img = b
retval, img = cv2.threshold... | tobyriddell/self-driving-car | munge_image_windows.py | Python | mit | 384 |
#!/usr/bin/python2.7
#-*- coding: utf-8 -*-
from movingAver import movingAver
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import rc
#import math
plt.rcParams["legend.fontsize"]=25
plt.figure(figsize=(12,9),dpi=200)
# plt.gca().yaxis.set_major_formatter(ticker.... | zharuosi/2017 | tools/plot-f-ema.py | Python | mit | 2,033 |
import httplib
import urlparse
from oauth2client.client import flow_from_clientsecrets
headers = {"Content-Type":"application/json"}
url = "https://picasaweb.google.com/data/feed/api/user/101458158860096958252"
domain = urlparse.urlparse(url).netloc
connection = httplib.HTTPSConnection(domain)
connection.request("GET... | anpieber/img2plus | img2plus.py | Python | mit | 489 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0008_weeklytimeslot'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='n... | malaonline/Server | server/app/migrations/0009_auto_20151127_1826.py | Python | mit | 506 |
import re
import os
import collections
import operator
def extend(d, u):
for k, v in u.items():
if isinstance(v, collections.Mapping):
r = extend(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
def list_dirs(path):
folders = []
while path != ""... | JacobFischer/Creer | creer/utilities.py | Python | mit | 1,685 |
from django.test import TestCase, Client
import json
import re
from freezegun import freeze_time
from twote.models import OutgoingTweet, OutgoingConfig
from twote.tasks import beat_tweet_scheduler, tweeter
from twote.models_calendar import Event
class StrictViewTest(TestCase):
"""simple tests for strict endpoint"... | totalgood/twote | twote/tests.py | Python | mit | 8,329 |
# 329-longest-increasing-path-in-matrix.py
class Solution(object):
def longestIncreasingPath_wa(self, matrix): # Wrong Answer, need 4 directions
"""
:type matrix: List[List[int]]
:rtype: int
"""
if len(matrix) == 0: return 0
d1 = [[1] * len(matrix[0]) for _ in matrix... | daicang/Leetcode-solutions | 329-longest-increasing-path-in-matrix.py | Python | mit | 2,949 |
import urllib2
import os.path
import sys
import re
default_encoding = sys.getfilesystemencoding()
if default_encoding.lower() == 'ascii':
default_encoding = 'utf-8'
def to_native_string(s):
if type(s) == unicode:
return s.encode(default_encoding)
else:
return s
def r1(pattern, text):
m = re.search(pattern, ... | rahimnathwani/youku-lixian | common.py | Python | mit | 7,356 |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from nodetraq.lib.base import BaseController, render, user_level
log = logging.getLogger(__name__)
class HelpController(BaseController):
@user_level(0)
def __before__(sel... | seryl/Nodetraq | nodetraq/controllers/help.py | Python | mit | 707 |
#!/usr/bin/env python2
import unittest
from system.spectrum import Spectrum
from system.parameterset import ParameterSet
from eqc.eqc import CircuitTree
from eqc.parser import Parser
simplecases = [{'specfile':'cases/trilayer.json', 'eqc':'(R|C)+Warb', 'p0':[0.025,1e-4,0.025,10]}]
class TestParser(unittest.TestCase... | robbje/eis | src/test_cases.py | Python | mit | 1,965 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def _defaultFilter(packetNum, packet, glob):
'''Filter for Traffic
Args:
packetNum (int): packet number
packet (obj): packet
glob (dict): global dict
Returns:
bool: if True do not hanlde that packet
'''
return False
| LyleMi/Trafficker | Trafficker/filters/template.py | Python | mit | 318 |
from qtpy.QtWidgets import (QMainWindow, QProgressBar, QTableWidgetItem,
QHBoxLayout, QCheckBox, QWidget, QTableWidgetSelectionRange)
from qtpy import QtGui
import numpy as np
from src.iBeatles.table_dictionary.table_fitting_story_dictionary_handler import TableFittingStoryDictionaryHandler... | ornlneutronimaging/iBeatles | src/iBeatles/fitting/march_dollase/create_fitting_story_launcher.py | Python | mit | 10,811 |
from cornice.resource import resource, view
@resource(collection_path='/notes', path='/notes/{note_id}')
class NotesResource(object):
def __init__(self, request):
self._request = request
self._context = request.context
def collection_get(self):
return self._context.get_notes()
@... | brukhabtu/zingk | zingkd/zingkd/resources.py | Python | mit | 512 |
from django.contrib import admin
from .models import Paragraph, Result
# Register your models here.
class ResultAdmin(admin.ModelAdmin):
list_display = ('user', 'paragraph')
list_filter = ['user', 'paragraph']
class ParagraphAdmin(admin.ModelAdmin):
list_display = ('id', 'paragraph', 'count')
list... | hgt312/SimpleMark | pars/admin.py | Python | mit | 430 |
### The only things you'll have to edit (unless you're porting this script over to a different language)
### are at the bottom of this file.
import urllib
import urllib2
import hashlib
import random
import email
import email.message
import email.encoders
import StringIO
import sys
""""""""""""""""""""
""""""""""""... | vinhqdang/my_mooc | MOOC-work/coursera/FINISHED/Web Application Architecture/MoocSubmitScript 2/submit.py | Python | mit | 5,254 |
import click
import copy
import json
from ethereum import slogging
slogging.PRINT_FORMAT = '%(message)s'
from ethereum import vm
from ethereum.block import Block
from ethereum.transactions import Transaction
from ethereum.config import Env, default_config
from ethereum.db import EphemDB
from ethereum.genesis_helpers ... | karlfloersch/pyethereum | tools/evm.py | Python | mit | 4,265 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/responses/use_item_potion_response.proto
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... | bellowsj/aiopogo | aiopogo/pogoprotos/networking/responses/use_item_potion_response_pb2.py | Python | mit | 4,133 |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
README = read('README.rst')
class PyTest(TestCommand):
def finalize_options(se... | suutari-ai/django-enumfields | setup.py | Python | mit | 1,456 |
import sys,os
sys.path.insert(0,os.path.abspath(__file__+"/../.."))
from d2d.benchmark import run_rui2016
def main():
ans = run_rui2016(n_cc=5, n_pairs=5, n_rb=50, cc_qos=1)
print(ans.champion_x)
print(ans.champion_f)
if __name__ == '__main__':
main() | mathwuyue/py-wireless-sys-sim | test/test_rui2016.py | Python | mit | 271 |
import re
import time
import datetime
import pymongo
import elasticsearch
import redis
import urllib3
import celery
import html
import mongoengine as mongo
from django.conf import settings
from django.contrib.auth.models import User
from apps.search.tasks import IndexSubscriptionsForSearch
from apps.search.tasks import... | samuelclay/NewsBlur | apps/search/models.py | Python | mit | 23,760 |
import logging
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs.
Messages are available from an instance's ``messages`` dict, in order, indexed by
a lowercase log level string (e.g., 'debug', 'info', etc.).
"""
def __init__(self, *args, **kwargs):
... | nlindblad/ocarina | tests/mockings.py | Python | mit | 1,393 |
from fixures import *
from freezegun import freeze_time
from datetime import datetime
from time import sleep
from django.core import mail
from django.conf import settings
from funcy import is_list, all, str_join
from . import tasks as T
import fixures
from .models import JobStatus, job_status, get_questions, get_anon, ... | popara/jonny-api | matching/tests.py | Python | mit | 6,443 |
import socket
from threading import Lock
from __about__ import __version__, __title__, __description__
__all__ = ['__version__', '__title__', '__description__',
'SubdomainDispatcher']
class SubdomainDispatcher(object):
""" A WSGI application that gets or creates other WSGI applications
based on t... | xsleonard/wsgisubdomain | wsgisubdomain.py | Python | mit | 2,974 |
# -*- coding: utf-8 -*-
def get_single_preprocessor(instance_id=None, **kw):
"""Accepts a single argument, `instance_id`, the primary key of the
instance of the model to get.
"""
pass
def get_single_postprocessor(result=None, **kw):
"""Accepts a single argument, `result`, which is the dictionar... | Depado/MarkDownBlog | app/api/example.py | Python | mit | 3,586 |
from peewee import Model, CharField, DateField, ForeignKeyField, BooleanField
from affiliations.db import db
class ModelBase(Model):
class Meta:
database = db
class Article(ModelBase):
title = CharField(
help_text="Title of article.")
doi = CharField(
index=True,
help_text=... | cameronneylon/affiliations | affiliations/models.py | Python | mit | 4,172 |
import pytest
from nordb.database import nordic2sql
from nordb.database import creationInfo
from nordb.database import sql2nordic
from nordb.core import nordic
from nordb.core import usernameUtilities
@pytest.mark.usefixtures("setupdb", "nordicEvents")
class TestNordic2SQL(object):
def testSuccesfulNordic(self, se... | MrCubanfrog/NorDB | tests/database/test_nordic2sql.py | Python | mit | 1,887 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | Stargrazer82301/CAAPR | CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/reporting/reporting.py | Python | mit | 15,439 |
#!/usr/bin/env python3
from setuptools import setup, find_packages
from spotify_dl.constants import VERSION
with open('README.md') as f:
long_description = f.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='spotify_dl',
version=VERSION,
python_requires... | SathyaBhat/spotify-dl | setup.py | Python | mit | 1,643 |
import os
import sys
sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib'))
import birthday
| dcifuen/cloudbday | src/run.py | Python | mit | 100 |
#!/usr/bin/env python2
# Copyright (c) 2014 The Drivercoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test the BIP66 changeover logic
#
from test_framework.test_framework import DrivercoinTestFramework
fr... | drivercoin/drivercoin | qa/rpc-tests/bipdersig.py | Python | mit | 3,160 |
# test_cisco_iosxrv.py - Unit test cases for Cisco IOS XRv platform handling
#
# October 2016, Glenn F. Matthews
# Copyright (c) 2014-2017 the COT project developers.
# See the COPYRIGHT.txt file at the top-level directory of this distribution
# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.
#
#... | glennmatthews/cot | COT/platforms/tests/test_cisco_iosxrv.py | Python | mit | 5,500 |
# Copyright (c) 2002 Joao Prado Maia. See the LICENSE file for more information.
import MySQLdb
import papercut.settings
import md5
settings = papercut.settings.CONF()
class Papercut_Auth:
"""
Authentication backend interface for the phpBB web message board software (http://www.phpbb.com) when used inside Pos... | jgrassler/papercut | papercut/auth/postnuke_phpbb_mysql_users.py | Python | mit | 1,382 |
# -*- encoding: utf-8 -*-
from .configuration_generator import (
ConfigurationGenerator,
DockerConfigurationGenerator,
)
| cbrand/vpnchooser | src/vpnchooser/cli/__init__.py | Python | mit | 130 |
from __future__ import print_function
from setuptools import setup
from setuptools.command.test import test as TestCommand
import os
import sys
import receita
class Tox(TestCommand):
user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
TestCommand.initialize_... | vkruoso/receita-tools | setup.py | Python | mit | 2,683 |
# Christopher Campo
# origin: 12 Feb, 2012
# maxheap.py
'''
maxheap.py
Author: Christopher Campo
Email : ccampo.progs@gmail.com
A set of functions to implement a max-heap priority queue in Python. I wrote
this to study for a computer science class exam and figured that it may come
in handy some day, so I might as we... | quake0day/oj | maxheap.py | Python | mit | 3,392 |
import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
import pandas as pd
import itertools
import numpy as np
import random
import subprocess as sub
def get_least_gaps_seq(seq_dict,length,side='left'):
middle = length/2
min_gaps = length
min_key = ''
# for all sequences check number of gaps in ... | sergpolly/FluUtils | FluDB_coding_aln/subsample_msa_random.py | Python | mit | 2,581 |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
from jnius import autoclass
class OutputArgs(unittest.TestCase):
def test_string_output_args(self):
String = a... | benson-basis/pyjnius | tests/test_output_args.py | Python | mit | 521 |
"""This module contains all tests related to postgres."""
import sys
import psycopg2
import pytest
from ovmm.config.environment import PSQL_CONN, PSQL_TABLE
from ovmm.handlers import postgres
from ovmm.prompts.defaults import DUMMY_USERS
# Variable is used to skip postgres tests if not on Ubuntu
pytestmark = pytest... | tobiasraabe/otree_virtual_machine_manager | tests/test_handlers_postgres.py | Python | mit | 6,436 |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from course.models import Subscription, Author
from course.forms import CourseForm
def home(request):
if request.user.is_authenticated():
return redirect('home:mycourses')
else:
return rende... | starkdee/courseware | home/views.py | Python | mit | 888 |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
common = ''
min_len = 0
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
... | cheng10/leetcode | longest_common_prefix.py | Python | mit | 766 |
from quaidan.status import parse_balancer_manager_page
import unittest
class BalancerManagerParserTest(unittest.TestCase):
def setUp(self):
with open('tests/balancer-manager.2.4.7.html', 'r') as htmlFile:
html = htmlFile.read()
self.status = parse_balancer_manager_page(html)
d... | stefanbirkner/quaidan | tests/status_test.py | Python | mit | 2,619 |
from machine.settings import import_settings
from machine.utils import Singleton
from machine.utils.module_loading import import_string
class Storage(metaclass=Singleton):
def __init__(self):
_settings, _ = import_settings()
_, cls = import_string(_settings['STORAGE_BACKEND'])[0]
self._sto... | DandyDev/slack-machine | machine/clients/singletons/storage.py | Python | mit | 488 |
# -*- coding: utf-8 -*-
__all__ = ["Sampler"]
from .base import Sampler
| jellis18/emcee3 | emcee3/samplers/__init__.py | Python | mit | 74 |
# coding=utf-8
"""Test for countbyalexa."""
| ravishan16/CountByAlexa | tests/__init__.py | Python | mit | 44 |
"""A module using export, for validation."""
__all__ = ["first"]
from pydecor.decorators import export
def first():
"""Allow testing of __all__ appending."""
@export
def exported():
"""Allow testing of @export."""
| mplanchard/pydecor | tests/decorators/exports/list_all.py | Python | mit | 228 |
#!/usr/bin/env python
import kapteyn.wcs as wcs
import astropy, astropy.io.fits as pyfits, sys, re
from optparse import OptionParser
from numpy import *
class Image:
def __init__(self, imagename):
self.name = imagename
header = pyfits.getheader(self.name)
self.shape = array((header['NAXIS1... | deapplegate/wtgpipeline | coaddinputs.py | Python | mit | 2,055 |
"""MSAView - HMMER support.
Copyright (c) 2011 Joel Hedlund.
Contact: Joel Hedlund <yohell@ifm.liu.se>
MSAView is a modular, configurable and extensible package for analysing and
visualising multiple sequence alignments and sequence features.
This package provides support for parsing hmmsearch result files.
If... | yohell/msaview | msaview_plugin_hmmer/__init__.py | Python | mit | 6,895 |
#!/usr/bin/python
"""
Salt Publish commands to the salt system from the
command line on the master.
"""
import os
import sys
import time
import logging
import threading
import traceback
import zmq
from salt.utils import parsers, print_cli
def hubot_salt_pull():
context = zmq.Context()
socket = context.sock... | alexchenfeng/hubot | src/SaltAPI/hubot_salt_master_api.py | Python | mit | 1,861 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# cssqc/__init__.py
#
# css quality control
# ----------------------------------------------------------------
# copyright (c) 2014 - Domen Ipavec
# Distributed under The MIT License, see LICENSE
# -------... | matematik7/CSSQC | cssqc/parser.py | Python | mit | 3,492 |
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Reshape
from keras.layers.core import Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Convolution2D, MaxPooling2D, UpSampling2D
from keras.layers.convolutional im... | jskDr/jamespy_py3 | gans/dcgans_amc.py | Python | mit | 13,329 |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | plaid/plaid-python | plaid/model/bank_transfer_network.py | Python | mit | 7,085 |
'''
Class for displaying the high scores to the user, and controlling sprites required for this menu item/level
Ashley Ingram
'''
import pygame, error
from highscoremonitor import HighScoreMonitor
class HighScore:
__instance = None
@staticmethod
def getInstance(screen):
"""static met... | AshleyIngram/This-Game-Has-Asteroids | highscore.py | Python | mit | 3,308 |
import pandas as pd
def p2f(x):
return 0 if x == "" else float(x.strip('%'))
rel = pd.read_csv('religions.csv', converters={'Other/UnSpecified': p2f, 'None': p2f})
rel.fillna(0)
rel['Non-religious'] = rel['Other/UnSpecified'] + rel['None']
def printNonReligious(country):
print rel[rel['Country'].str.contains(count... | m1key/data-science-sandbox | religion.py | Python | mit | 495 |
# -*- coding: utf-8 -*-
from datetime import date, datetime
import numpy as np
import win32com.client
class DaishinCybosEngine(PyKrStock):
item2code = {}
cpcybos = win32com.client.Dispatch("CpUtil.CpCybos")
cpstockcode = win32com.client.Dispatch("CpUtil.CpStockCode")
stockchart = win32com.client.Disp... | maczniak/PyKrStock | DaishinCybosEngine.py | Python | mit | 5,842 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
| guykisel/python-autocast-decorator | tests/__init__.py | Python | mit | 196 |
from chips.api.api import Output
class Leds(Output):
def __init__(self, chip, name):
Output.__init__(self, chip, name)
def data_sink(self, data):
print "leds:", bin(data)
| dawsonjon/Chips-Demo | demo/io_models/leds.py | Python | mit | 195 |
#!/usr/bin/env python
#from setuputils import setup
from distutils.core import setup
sctk = {
"name": "silhouette",
"description": "Python based silhouette framework",
"author":"Giles Hall",
"packages": ["silhouette"],
"package_dir": {"silhouette": "src"},
"py_modules":[
"silhouette.__... | vishnubob/silhouette | setup.py | Python | mit | 494 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
opts = []
codes = []
infos = []
pattern = re.compile('^\w+_DECLARE.+')
for line in open("/usr/local/opt/freexl/include/freexl.h"):
if line.startswith('#define FREEXL_'):
c = line.split()
codes.append(c[1])
template = """
// generated by cod... | thedumptruck/go-freexl | _tool/codegen.py | Python | mit | 689 |
"""Utilities for creating hashes.
@see: Cake Build System (http://sourceforge.net/projects/cake-build)
@copyright: Copyright (c) 2010 Lewis Baker, Stuart McMahon.
@license: Licensed under the MIT license.
"""
import binascii
try:
import hashlib
def sha1(*args, **kwargs):
return hashlib.sha1(*args, **kwargs)
... | lewissbaker/cake | src/cake/hash.py | Python | mit | 936 |
import unittest
import os, shutil, json
from GeometrA.src.File.WorkSpace import WorkSpace
from xml.etree import ElementTree as ET
class WorkSpaceTestSuite(unittest.TestCase):
@classmethod
def setUpClass(cls):
if os.path.isdir('./tests/File/Project1'):
shutil.rmtree('./tests/File/Project1',... | NTUTVisualScript/Visual_Script | tests/File/test_WorkSpace.py | Python | mit | 8,832 |
from setuptools import setup
from setuptools import find_packages
setup(
name='cors-python',
version='0.0.1',
description='Python CORS Integration for WSGI Applications',
author='Monsur Hossain',
author_email='monsur@gmail.com',
url='https://github.com/monsur/cors-python',
packages=find_pac... | monsur/cors-python | setup.py | Python | mit | 372 |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | plaid/plaid-python | plaid/model/transfer_authorization_proposed_transfer.py | Python | mit | 8,838 |
import numpy as np
import matplotlib.pyplot as pl
import pysir
import time
from tqdm import tqdm
l = [['1',-500,10,1500]]
SIR = pysir.SIR(l)
psf = np.loadtxt('PSF.dat', dtype=np.float32)
SIR.set_PSF(psf[:,0].flatten(), psf[:,1].flatten())
out = np.loadtxt('model.mod', dtype=np.float32, skiprows=1)[:,0:8]
out = np.del... | aasensio/pySIR | test/example2.py | Python | mit | 704 |
from . import about
from . import cfg
from . import ev
from . import gs
from collections import namedtuple
import copy
import os
import re
import string
import sublime
import subprocess
import time
try:
STARTUPINFO = subprocess.STARTUPINFO()
STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
STARTUPINFO.wShowWi... | DisposaBoy/GoSublime-next | gosubl/sh.py | Python | mit | 8,543 |
import numpy as np
import pytest
from hypothesis import assume, given
from hypothesis.strategies import builds, integers
import lttb
def load_test_data():
csv = "tests/timeseries.csv"
data = np.genfromtxt(csv, delimiter=",", names=True)
xs = data["X"]
ys = data["Y"]
return np.array([xs, ys]).T
... | javiljoen/lttb.py | tests/test_lttb.py | Python | mit | 2,217 |
from flask import Blueprint
from flask import render_template, redirect, url_for, jsonify
import controllers
corpus_storage = Blueprint('corpus_storage', __name__)
@corpus_storage.route('/')
def default():
return 'Hello corpus_storage!'
@corpus_storage.route('/alt/')
def controller_default():
return control... | nbuechler/copious-affect-corpus | app/corpus_storage/views.py | Python | mit | 1,457 |
"""Support for ClearPass Policy Manager."""
from __future__ import annotations
from datetime import timedelta
import logging
from clearpasspy import ClearPass
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
DeviceScanner,
)... | rohitranjan1991/home-assistant | homeassistant/components/cppm_tracker/device_tracker.py | Python | mit | 2,430 |
from __future__ import unicode_literals
import abc
from mongoengine import *
class Team(Document):
name = StringField(max_length=200)
team_id = StringField(max_length=20)
bot_user_id = StringField(max_length=20)
bot_access_token = StringField(max_length=100)
class SlackMessage(object):
__metacla... | banctilrobitaille/RockETS-Basestation | slack/models.py | Python | mit | 1,328 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('counselling', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='appointment',
name=... | oinopion/cardiff-wellbeeing | counselling/migrations/0002_optionaltimeslot.py | Python | mit | 916 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from paypal.standard.ipn.models import PayPalIPN
class PayPalIPNAdmin(admin.ModelAdmin):
date_hierarchy = 'payment_date'
fieldsets = (
(None, {
"fields": [
"flag", "txn_id", "txn_type", "payment_... | drfraser/django-paypal | paypal/standard/ipn/admin.py | Python | mit | 2,591 |
import unittest
class myTestSuite(unittest.TestCase):
def setup(self):
pass
def tearDown(self):
pass
def number2roman(self, number):
if(number<0):
return ""
preset_roman = {0:"",5:"V",10:"X",50:"L",100:"C",500:"D",1000:"M"}
if(preset_roman.has_key(number)):
return preset_rom... | feedfood/TDD | kata_dojo/kata_roman_numerals/roman_numerals.py | Python | mit | 2,116 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | Azure/azure-sdk-for-python | sdk/azureadb2c/azure-mgmt-azureadb2c/azure/mgmt/azureadb2c/aio/_cpim_configuration_client.py | Python | mit | 6,828 |
import logging
from thesis.models import (
DBSession,
Base,
Layer,
DEFAULT_PROJECTION,
ST_Collect,
ST_SnapToGrid,
ST_MakeEnvelope,
MappablePoint,
GriddedMappablePoint,
BoundMappablePoint,
)
from sqlalchemy import (
Column,
Integer,
Text,
Unicode,
Foreign... | robertpyke/PyThesis | thesis/models/gridded_and_bound_mappable_point.py | Python | mit | 2,544 |
# -*- coding: utf-8 -*-
"""
WSGI config for file_upload 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.envi... | grschafer/django-meetup-fileupload | file_upload/wsgi.py | Python | mit | 423 |