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 |
|---|---|---|---|---|---|
import cv2
import numpy as np
import sys, time, math
data = []
for j in range(1,6):
for i in range(1,12):
img = cv2.imread('calibration/'+str(12*i)+'x'+str(16*j)+'.png',1)
if img==None:
print "cannot open ",filename
else:
#img[:,:,1] = 0
gimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
circles = cv2.Hou... | skyleradams/tim-howard | Vision/calibrationCodeAndImages/vis.py | Python | mit | 976 |
import csv
import itertools
import random
import ast
import sys
#usage
# python parseResults.py results.txt
fname = '../results/nullutterance_results.txt'
file_names = [fname]
itemfile = open("items.txt")
items = [" ".join(l.rstrip().split()) for l in itemfile.readlines()]
itemfile.close()
#print items
lines = []... | thegricean/sinking-marbles | models/complex_prior/smoothed_unbinned15/scripts/parseNullUtteranceResults.py | Python | mit | 2,789 |
# coding: utf-8
import pytest
from statemachine import StateMachine, State
from statemachine import exceptions
class MyModel(object):
"A class that can be used to hold arbitrary key/value pairs as attributes."
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
... | fgmacedo/python-statemachine | tests/test_statemachine.py | Python | mit | 10,767 |
# -*- coding: utf-8 -*-
#
# Objective-Revision-Evaluation-Service documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 23 09:13:08 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in th... | he7d3r/ores | docs/conf.py | Python | mit | 9,556 |
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView,ListAPIView
from rest_framework.permissions import IsAuthenticated
from api.serializers import UserSerializer, ArticleSerializer,ArticleDetailSerializer
fro... | munisisazade/developer_portal | api/views.py | Python | mit | 839 |
import json
from django.views import generic
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from ..models import User, Join, Event, Tag
from .decorators import login_decorator
from .utils import get_user_notifications
@method_decorator(login_decorator, name='get')
class Pro... | LorenzSelv/pinned | core/views/profile_view.py | Python | mit | 1,744 |
#!/usr/bin/env python3
# Author: Severin Kaderli <severin.kaderli@gmail.com>
#
# Project Euler - Problem 12:
# What is the value of the first triangle number to have over
# five hundred divisors?
import math
def get_triangle_number_with_n_factors(n):
"""Return the value of the first triangle number with more than n f... | severinkaderli/Project-Euler-Python | 012.py | Python | mit | 818 |
"""Some standard gradient-based stochastic optimizers.
These are just standard routines that don't make any use of autograd,
though you could take gradients of these functions too if you want
to do meta-optimization."""
from __future__ import absolute_import
import autograd.numpy as np
from builtins import r... | barak/autograd | examples/optimizers.py | Python | mit | 1,847 |
import numpy as np
import matplotlib.pyplot as plt
import sys
import pickle
import os
from pprint import pprint
from scipy.optimize import curve_fit
import math
from datetime import datetime
from matplotlib import dates
os.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/coatings/')
file = open('MMD_an... | annahs/atmos_research | WHI_long_term_plot_MMD_and_DpDc.py | Python | mit | 7,204 |
#!/usr/bin/python -i
from circuits import Event, Component, Manager
class foo(Event):
"""foo Event"""
channels = ("a",)
class bar(Event):
"""bar Event"""
class A(Component):
channel = "a"
def foo(self):
return "Foo"
class B(Component):
channel = "b"
def foo(self):
... | treemo/circuits | tests/core/test_channel_selection.py | Python | mit | 1,020 |
import pytest
@pytest.fixture
def anchorless_yaml():
yield """
e:
f: f
h:
- j
- k
"""
@pytest.fixture
def anchored_yaml():
yield """
a: &anchor
b: c
d: 11
e:
<<: *anchor
... | Cognexa/cxflow | cxflow/tests/conftest.py | Python | mit | 401 |
#!/usr/bin/env python3
import time
import sys
while True:
print("This is output!")
time.sleep(1)
| Thezomg/gsc | test.py | Python | mit | 107 |
# -*- coding: utf-8 -*-
"""
From this script, experiments for ImageNet pictures can be started.
See "configuration" below for the different possible settings.
The results are saved automatically to the folder ./results
It is recommended to run caffe in gpu mode when overlapping is set
to True, otherwise the calculatio... | lmzintgraf/DeepVis-PredDiff | experiments_imagenet.py | Python | mit | 5,870 |
from rest_framework.serializers import ModelSerializer
from gcm.utils import get_device_model
Device = get_device_model()
class DeviceSerializer(ModelSerializer):
class Meta:
model = Device
exclude = ('id', 'creation_date', 'modified_date', 'is_active')
| hugobrilhante/django-gcm-android-ios | gcm/serializers.py | Python | mit | 278 |
#!/usr/local/bin/python
import re
import os
refsbib = open('refs.bib', 'r').read()
p = re.compile('@.+{(.*),')
g = p.findall(refsbib)
for f in g:
name = f + '.pdf'
if os.path.isfile(os.path.join('./live/files/', name)):
print("[OK] %s ready" % f)
else:
print("[--] %s not found" % f)
| lukeolson/lukeo.cs.illinois.edu | check-files.py | Python | mit | 315 |
"""Implementations of authorization abstract base class query_inspectors."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers... | mitsei/dlkit | dlkit/abstract_osid/authorization/query_inspectors.py | Python | mit | 20,768 |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# mininode.p... | bitdeal/bitdeal | qa/rpc-tests/test_framework/mininode.py | Python | mit | 54,390 |
from munch import munchify
import requests
import arrow
from . import BASE_URL
EVENTS_URL = (BASE_URL + "/events?page=1&limit=40&timezone=America/New_York"
"&sort_direction=ASC&sub_types=SportEvent,MediaEvent"
"&sort=eventDate&start_date={}")
SCHEDULE_URL = (BASE_URL + "/events?page=1&limi... | pennlabs/pennathletics | pennathletics/events.py | Python | mit | 965 |
# -*- coding: utf-8 -*-
"""
Folium Tests
-------
"""
import pytest
import os
import json
try:
from unittest import mock
except ImportError:
import mock
import pandas as pd
import jinja2
from jinja2 import Environment, PackageLoader
import vincent
import folium
import base64
from folium.six import PY3
from fo... | BibMartin/folium | tests/test_folium.py | Python | mit | 30,299 |
import sys
import socket
import time
import os
import getpass
def handshake(address):
print ("Attempting handshake...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket
port = 5010 #specify port
s.connect((address,port)) #connect
s.sendall('110') #send data
reply = s.recv(5... | Samathy/dotsync | src/send.py | Python | mit | 2,165 |
"""
Simple User model creation tests.
"""
import csv
import datetime
import json
import tempfile
from django.core.management import call_command
from django.core.urlresolvers import reverse_lazy
from django.test import TransactionTestCase
from mixer.backend.django import mixer
from .base import BaseAPITestCase
from .... | fle-internal/content-curation | contentcuration/contentcuration/tests/test_user.py | Python | mit | 4,941 |
__author__ = 'metjush'
# Implementation of Classification Tree Bagging
# ============================================
# This Bag of Trees is built on the Classification Tree object implemented in classtree.py
#
# It uses bootstrap aggregating to grow the forest
#
# The primary parameters to input are the number of tre... | metjush/decision_tree | decision_tree/ClassTreeBagging.py | Python | mit | 5,931 |
class TaxBracket(object):
"""
creates a tax bracket object
verifies the bracket integrity
allows for passing calculations to the bracket
"""
def __init__(self, bracket: list, deduction: float) -> None:
self.__validate_bracket(bracket)
self.deduction = deduction
self.brac... | cwiki/monthly_budget | monthly_budget/models/tax_bracket.py | Python | mit | 3,060 |
# coding=utf-8
"""
Summation of primes
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from primes import *
print reduce(lambda x, y: x + y, primesList(2000000))
| Ladeia/ProjectEuler | Problem010/Python/solution_1.py | Python | mit | 236 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, modify, merge, publish... | rwl/PyCIM | CIM15/IEC61970/Meas/Command.py | Python | mit | 3,451 |
#!/usr/bin/env python
'''
crawler.py
Adam Canady
Jeff Ondich, CS257
October 4, 2013
This project is a single-threaded web crawler that returns a number of basic useful functionalities
directed towards webmasters or website content managers.
Usage: python crawler.py [--linklimit int] [--sea... | AdamCanady/CS257-Crawler | crawler.py | Python | mit | 6,934 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-26 02:48
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('home'... | maxwallasaurus/arboretum | home/migrations/0015_auto_20161026_0248.py | Python | mit | 845 |
# Copyright (c) 2017 Uber Technologies, Inc.
#
# 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, modify, merge, publ... | uber/rides-python-sdk | uber_rides/utils/request.py | Python | mit | 4,020 |
from unittest.mock import patch, PropertyMock
from bs4 import BeautifulSoup
from django.utils import translation
from django.core.urlresolvers import reverse
from core.tests.helpers import create_response
@patch('directory_cms_client.client.cms_api_client.lookup_by_slug')
@patch('core.views.LandingPageCMSView.page'... | uktrade/directory-ui-supplier | core/tests/test_views.py | Python | mit | 3,369 |
"""
WSGI config for gestionale 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.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Dj... | DavideTonin99/gestionaleFabLab | gestionale/wsgi.py | Python | mit | 489 |
import os
from keras import backend as K
import tensorflow as tf
from tensorflow.python.tools.freeze_graph import freeze_graph
def exportModelToTF(tfModelOutputDir):
if not os.path.exists(tfModelOutputDir):
os.makedirs(tfModelOutputDir)
# Save checkpoint
saver = tf.train.Saver()
save_path =... | SlipknotTN/Dogs-Vs-Cats-Playground | deep_learning/keras/lib/tfutils/export.py | Python | mit | 924 |
import unittest
from unittest import mock
# noinspection PyUnresolvedReferences
from accrocchio.badgeofshame import accrocchio, detonator, epoxy, compromise, blinder, flypaper
from accrocchio.badgeofshame import this_is_a, this_is_an
from accrocchio.observers import AccrocchioObserver
class TestBadgeOfShame(unittest... | fcracker79/accrocchio | test/accrocchio/test_badgeofshame.py | Python | mit | 7,581 |
from distutils.version import StrictVersion
import json
import django
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
class UserSetting(models.Model):
TYPE_STRING = "string"
TYPE_NUMBER = "number"
TYPE_BOOL = "bool"
TYPE_JSON = "js... | miraculixx/django-dynamic-usersettings | django_dynamic_usersettings/models.py | Python | mit | 3,541 |
import requests
class SubScraper:
def __init__(self, subreddit, num):
self.url = "https://www.reddit.com/r/{}.json".format(subreddit)
self.no_of_stories = num
self.main_stories = []
self.links = []
self.data = []
self.fetch_data()
def fetch_data(self):
... | rhys-fernandes/JAMM | subreddit_scraper.py | Python | mit | 779 |
# -*- coding:utf-8 -*-
import tornado.escape
from torcms.core import tools
from torcms.model.abc_model import MHelper
from torcms.model.core_tab import TabWikiHist
class MWikiHist():
@staticmethod
def get_last(postid):
'''
Get the last wiki in history.
'''
recs = TabWikiHist.... | bukun/TorCMS | torcms/model/wiki_hist_model.py | Python | mit | 1,639 |
import collections
from supriya.enums import CalculationRate
from supriya.ugens.PureUGen import PureUGen
class SinOscFB(PureUGen):
"""
::
>>> sin_osc_fb = supriya.ugens.SinOscFB.ar(
... feedback=0,
... frequency=440,
... )
>>> sin_osc_fb
SinOscFB.a... | Pulgama/supriya | etc/pending_ugens/SinOscFB.py | Python | mit | 3,110 |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
# Copyright (c) 2019 Nicolas Iooss
#
# 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... | fishilico/shared | glossaries/check_sort_order.py | Python | mit | 7,722 |
#!/usr/bin/env python
from pygecko.Messages import Twist, Image, IMU, Joystick, Vector, Array, Dictionary
from pygecko.Messages import Pose, Compass, Range, Quaternion
from pygecko.Messages import Buttons, Axes
from pygecko.Messages import serialize, deserialize
# from pygecko.lib.ZmqClass import Pub, Sub
import numpy... | walchko/pygecko | retired/old_version/original/tests/test_msg.py | Python | mit | 4,300 |
"""
@author: Maneesh D
@email: maneeshd77@gmail.com
"""
from random import randint
from urllib import request
def download_img(url):
num = randint(1, 1000)
file_name = "ManUtd_" + str(num) + ".png"
request.urlretrieve(url, file_name)
def main():
url = "https://lh3.googleusercontent.com/-iDzlv7IG4rY/... | maneeshd/PyTutorial | Basics/Download_Image_Web.py | Python | mit | 441 |
from unittest import TestCase
from nose.tools import ok_, eq_
from OrderedFormat.formatter import *
class TestOrderedFormat(TestCase):
def test_iter_depth_zero(self):
eq_(iter_depth([]), 0)
eq_(iter_depth(()), 0)
def test_iter_depth_one(self):
eq_(iter_depth([1]), 1)
eq_(iter_... | Himenon/OrderedFormat | tests/test_formatter.py | Python | mit | 1,074 |
from .production import *
DEBUG = True
ALLOWED_HOSTS += ["coll.in", "0.0.0.0"]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
"rest_framework_jwt.authentication.JSONWebToken... | andela-cmutembei/III | plana/settings/develop.py | Python | mit | 597 |
"""empty message
Revision ID: 39769d358276
Revises: 383e1224b4e7
Create Date: 2015-12-03 17:23:48.689959
"""
# revision identifiers, used by Alembic.
revision = '39769d358276'
down_revision = '383e1224b4e7'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... | taras1k/flask_auth_service | server/migrations/versions/39769d358276_.py | Python | mit | 2,536 |
import threading
import time
import CrawelerMod
import IndexerMod
class myThread (threading.Thread):
def __init__(self, threadID, name, counter,Lock, CorI):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.Lock = Lock
... | MohammedAlsayedOmar/APT-SearchEngine | SearchEngN/SearchEngN/ThreadingMod.py | Python | mit | 1,083 |
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
... | Hyyyyyyyyyy/acm | PythonTest/t35.py | Python | mit | 1,893 |
# Copyright (C) 2013 by Ben Morris (ben@bendmorris.com)
# Based on Bio.Nexus, copyright 2005-2008 by Frank Kauff & Cymon J. Cox
# and Bio.Phylo.Newick, copyright 2009 by Eric Talevich.
# All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file tha... | zjuchenyuan/BioWeb | Lib/Bio/Phylo/NeXMLIO.py | Python | mit | 11,094 |
max=10000
total=0
def palindrome_test(i):
for idx, char in enumerate(str(i)):
if not char==str(i)[-(idx+1)]:
return False
return True
def lychrel_test(i):
num_iter=0
while num_iter<50:
j=i+int(str(i)[::-1])
if palindrome_test(j):
return False
else:
i=j
num_iter+=1
ret... | lewisamarshall/euler | 055/055.py | Python | mit | 464 |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
from . import views
# DRF router and registered ViewSets
router = DefaultRouter()
router.register(r'groceryItems', views.GroceryItemViewSet,
base_name='groceryI... | jf248/scrape-the-plate | recipes/urls.py | Python | mit | 1,115 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime, date
from decimal import Decimal
from base import GAETestCase
from book_app.book_model import Book
from routes.books import rest
from gaegraph.model import Node
from mock import Mock
from mommygae import momm... | janairacs/tekton | backend/test/book_tests/book_rest_tests.py | Python | mit | 2,601 |
"""@package reconstructors
contains objects to use for reconstructing signals"""
from . import scorer, scorer_factory, sdr_scorer
| JeroenZegers/Nabu-MSSS | nabu/postprocessing/scorers/__init__.py | Python | mit | 131 |
#!/usr/bin/env python
"""
Create a client from json (not supported!)
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not run... | tanium/pytan | EXAMPLES/PYTAN_API/invalid_create_client_from_json.py | Python | mit | 4,312 |
#!/usr/bin/env python
import sys, os, math
c = 299792458
def main():
print("SpecialRel.py has been loaded.")
def ctometer(a): # Converts the speed that is in terms of c to meters per second.
return a * c
def metertoc(a): # Converts the speeed that is in terms of meters per second into terms of c.
... | defunSM/code | pyth/SpecialRel.py | Python | mit | 1,613 |
"""Filtering outliers"""
__author__ = 'thor'
import numpy as np
def outlier_lidx(data, method='median_dist', **kwargs):
if method == 'median_dist':
kwargs = dict({'thresh': 3}, **kwargs)
thresh = kwargs['thresh']
median_dist = np.abs(data - np.median(data))
mdev = np.median(median... | thorwhalen/ut | stats/filt.py | Python | mit | 798 |
# -*- coding: utf-8 -*-
from dp_tornado.engine.helper import Helper as dpHelper
class WebHelper(dpHelper):
pass
| why2pac/dp-tornado | dp_tornado/helper/web/__init__.py | Python | mit | 120 |
import cgi
import cgitb; cgitb.enable()
import matplotlib
matplotlib.use( 'Agg' )
import numpy as np
from scipy.stats.kde import gaussian_kde
import os,sys
import pylab
from PIL import Image
import uuid
def crop(arg1):
# size is width/height
img = Image.open(arg1)
left = 88
top = 41
width = 545
... | antoniofalcone89/webapp | plotModulo433.py | Python | mit | 5,954 |
#!/usr/bin/env python
import os.path
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel')
sys.exit()
def read(filename):
return open(os.path.join(os.path.dirname(_... | nateyoder/gspread | setup.py | Python | mit | 1,947 |
#!/usr/bin/env python
from datetime import datetime, timedelta
import unittest
from app import create_app, db
from app.models import User, Post
from config import Config
class TestConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
ELASTICSEARCH_URL = None
class UserModelCase(unittest.T... | miguelgrinberg/microblog | tests.py | Python | mit | 3,542 |
#!/usr/locals/bin python3
import os
COV = None
if os.environ.get('ICALC_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from app import create_app, db
from app.common.models import User, Role, Post
from flask_script import Manager, Shell, Server
from flask_mig... | cmacro/mogufsite | manage.py | Python | mit | 1,792 |
import copy
from .base import BaseCommand
class RepeatCommand(BaseCommand):
def __init__(self, args):
super(RepeatCommand, self).__init__(args)
try:
self.count = int(args)
except (TypeError, ValueError):
raise ValueError("Invalid repeat value, should be int")
... | hamstah/quack | quack/commands/repeat.py | Python | mit | 792 |
from model.Transport.Transport import Transport
class Bicycle(Transport):
'''
Class to store bike informations
'''
def __init__(self, travel_time, itinerary):
super().__init__(travel_time, itinerary, True)
| rmulton/lawen | model/Transport/Bicycle.py | Python | mit | 231 |
from django import template
register = template.Library()
# Messages
@register.inclusion_tag('widgets/messages.html', takes_context=True)
def messages(context):
django_messages = context['messages']
messages = []
for message in django_messages:
messages.append({'tags': message.tags, 'text': messa... | bruecksen/isimip | isi_mip/core/templatetags/messages.py | Python | mit | 374 |
"""
1D RootFind class.
Bruce Wernick
10 June 2021
"""
import sys
from math import sqrt, log10
from const import EPS, TINY
def MIN(a, b):
if a < b:
return a
return b
def SQR(x):
t = x
return t*t
def SIGN(a, b):
if b >= 0.0:
return abs(a)
return -abs(a)
def signum(a, b):
... | bru32/magz | magz/uroot.py | Python | mit | 18,710 |
from django import template
from datetime import datetime
from geelweb.django.editos.models import Edito
register = template.Library()
class EditoNode(template.Node):
DEFAULT_TEMPLATE = 'editos/carousel.html'
def __init__(self, template_file=None):
if template_file:
self.template = temp... | geelweb/django-editos | src/geelweb/django/editos/templatetags/editos.py | Python | mit | 1,429 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pyGADDAG documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 29 19:32:21 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | jorbas/pyGADDAG | docs/conf.py | Python | mit | 5,303 |
# -*- coding: utf-8 -*-
##
import sys
import csv
import json
import re
import time
import requests
import couchdb
import configure
#
#LAYOUT_PARSE_1 = re.compile(u"([^0-9]*)[0-9]{1,2}・[0-9]{1,2}")
#LAYOUT_PARSE_2 = re.compile(u"([^0-9]*)[0-9]{1,2}")
LAYOUT_PARSE_1 = re.compile(u"([^0-9]*)[0-9]{1,2},[0-9]{1,2}")
LAYO... | MizunagiKB/circlecheck | util/make_jsdata.py | Python | mit | 13,913 |
class botDatabase:
def __init__(self):
self.bots = {}
self.outputs = {}
def addBot(self,id):
if not id in self.bots:
self.bots[id] = {"low": -1, "high": -1}
def addOutput(self, id):
self.outputs[id] = []
def resetBot(self,id):
self.bots[id]["low"] = -1
self.bots[id]["high"] = -1
... | tbjoern/adventofcode | Ten/script.py | Python | mit | 2,827 |
import unittest
from mygrations.formats.mysql.file_reader.create_parser import CreateParser
class TableDifferenceColumnsTest(unittest.TestCase):
def test_drop_columns(self):
a = CreateParser()
a.parse(
"""CREATE TABLE `tasks` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,... | cmancone/mygrations | mygrations/tests/integration/table_difference_columns_test.py | Python | mit | 4,532 |
import json
import os
import tempfile
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from configdb import exceptions
from configdb.db.interface import base
from configdb.db.interface import sa_generator
class SqlAlchemyQueryCriter... | lavagetto/configdb | configdb/db/interface/sa_interface.py | Python | mit | 5,149 |
from rdflib import Graph
__all__ = ['BenchableGraph']
class BenchableGraph(object):
"""
Provides a convenient way to use a graph for benchmarks.
"""
def __init__(self, store, graph_id, store_config, graph_create=False):
"""
:param str store: Type of store to use.
:param str ... | vincent-octo/ktbs_bench_manager | ktbs_bench_manager/benchable_graph.py | Python | mit | 1,555 |
from django.conf.urls import url
from feasta.views import *
from feasta.forms import PasswordChangeForm
from django.conf import settings
from django.contrib.auth.views import logout, password_change
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^$',
login_required(Home.as_view(... | IIITS/Feasta | feasta/urls.py | Python | mit | 1,438 |
"""
Simple algorithms for the 2-SUM and 3-SUM problems.
R-SUM problem:
Check if a given list of numbers contains R elements that some to a target
value.
These algorithms can actually be used with any kind of items that support
summation, subtraction and equality tests.
Author:
Christos Nitsas
(nitsas)
(chrisni... | nitsas/py3algs | py3algs/algorithms/two_three_sum.py | Python | mit | 2,965 |
#!/usr/bin/env python
# coding=utf-8
"""
Run all unit tests.
"""
from __future__ import absolute_import
from __future__ import print_function
import glob
import os
import sys
import unittest
__author__ = "Alberto Pettarin"
__copyright__ = "Copyright 2016, Alberto Pettarin (www.albertopettarin.it)"
__license__ = "MIT... | pettarin/ipapy | run_all_unit_tests.py | Python | mit | 3,339 |
"""
mote-serial-log: Mote serial logger with output coloring.
Log printf and HDLC messages from serial port to terminal and logfile.
"""
from setuptools import setup, find_packages
from os.path import join as pjoin
import mote_serial_logger
doclines = __doc__.split("\n")
setup(name='mote_serial_logger',
versi... | thinnect/serial-logger | setup.py | Python | mit | 871 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracking', '0003_auto_20141023_0834'),
]
operations = [
migrations.AlterField(
model_name='bannedip',
... | letam/django-tracking | tracking/migrations/0004_alter_ip_address_fields.py | Python | mit | 640 |
#!/usr/bin/env python
from optparse import OptionParser
import multiprocessing
import gunicorn.app.base
import os
import sys
import re
import shutil
import tempfile
import pyferret
from paste.request import parse_formvars
import subprocess
from jinja2 import Template
import itertools
from PIL import Image
# =====... | PBrockmann/wms-pyferret | pyferretWMS.py | Python | mit | 17,176 |
from setuptools import setup
setup(
name='stack_dumpper',
version='0.0.2',
author='Jayson Reis',
author_email='santosdosreis@gmail.com',
description='Dump stack trace from all threads (including main thread) when CRTL + \ is pressed or SIGQUIT is received.',
url='https://github.com/jaysonsantos... | jaysonsantos/python-stack-dumpper | setup.py | Python | mit | 589 |
from .polo import optimal_leaf_ordering | adrianveres/polo | polo/__init__.py | Python | mit | 39 |
"""django_channels 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')
C... | sourcelair-blueprints/django-channels-chat | django_channels/urls.py | Python | mit | 771 |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import RegularPolyCollection
from BF_functions import user_rc
'''
Radial velocity plotter!
Makes a plot with two panels: top is RV vs. time, bottom is RV vs. orbital phase
You need to have these columns... | savvytruffle/cauldron | rvs/rvplotmaker.py | Python | mit | 6,377 |
# Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import logging
import httplib
from socket import timeout
from threading import Thread
from time import sleep
import ssl
from tweepy.models import Status
from tweepy.api import API
from tweepy.error import TweepError
from tweepy.utils import i... | memaker/tweepy | tweepy/streaming.py | Python | mit | 11,639 |
from django.contrib.auth.models import User
from rest_framework.generics import RetrieveAPIView
from snippets.serializers.UserSerializer import UserSerializer
class UserDetail(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
| sinner/testing-djrf | tutorial/snippets/views/UserDetail.py | Python | mit | 268 |
import collections
# def maxSum(arr):
# n = len(arr)
# q = collections.deque(arr)
# num_list = []
# for _ in xrange(n):
# tmp = q.popleft()
# num_list.append(list(q))
# q.append(tmp)
# DP = [[0] * (n-1) for _ in xrange(n)]
# for i in range(n):
# DP[i][0] = num_lis... | quake0day/oj | new_dp_3ncircle.py | Python | mit | 1,045 |
"""
Django settings for chatdemo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | Thinker-ru/sepiida-chat | chatdemo/chatdemo/settings.py | Python | mit | 2,272 |
import logging
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Other than that,... | eusyar/4fun | util/DesignPatterns.py | Python | mit | 1,289 |
import pytest
@pytest.fixture
def thyrus():
from api.scrapers.item import scrape_item
return scrape_item('d19447e548d')
def test_scrape_item_by_id(thyrus):
assert thyrus.id == 'd19447e548d'
assert thyrus.name == 'Thyrus Zenith'
assert thyrus.type == 'Two-handed Conjurer\'s Arm'
assert thyrus... | Demotivated/loadstone | api/tests/test_item.py | Python | mit | 2,023 |
"""
pyexcel_io.readers.tsv
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The lower level tsv file format handler.
:copyright: (c) 2014-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
"""
import pyexcel_io.constants as constants
from .csvr import CSVBookReader
class TSVBookReade... | caspartse/QQ-Groups-Spider | vendor/pyexcel_io/readers/tsv.py | Python | mit | 829 |
# Generated by Django 2.2.13 on 2021-04-14 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0144_auto_20210413_1010'),
]
operations = [
migrations.AddField(
model_name='meeting',
name='wrapup_... | p2pu/learning-circles | studygroups/migrations/0145_meeting_wrapup_sent_at.py | Python | mit | 410 |
import datetime
from .store import *
def create_textset(name, description, source, url, filename):
"""
creates a text set object
:param name: name of the text set
:param filename: filename of the data
:return: a textset object
"""
# create object and control data
creation_date = datet... | pierre-chaville/automlk | automlk/textset.py | Python | mit | 4,512 |
#!/usr/bin/env python
import re
from util.Cache import IndexedCache, SecondOrderCache
from util.Report import Report
from numpy import mean
class ParseEquations:
def __init__(self):
self.identity = None
self.nullTerm = "Nothing"
self.defaultLimit = (None,None)
self.ov... | bionomicron/Redirector | core/model/LinearModel.py | Python | mit | 28,564 |
#!/usr/bin/python
__author__ = 'vilelag'
import argparse
import numpy as np
def create_parsers():
#parser for the main program
parser = argparse.ArgumentParser(description='Calculate distance between representations, given 2 dictionaries'
'and a file with cl... | gustavo-momente/word2vec_variations | rep_dist.py | Python | mit | 2,489 |
#!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Bitcoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inF... | waynerjohn/johnwayner | share/qt/clean_mac_info_plist.py | Python | mit | 894 |
import argparse
settings = Namespace()
#default settings.
settings.metachar = '!'
settings.chat_prefix = '#'
settings.chat_color = 'f' # white
settings.log_level = 'INFO'
settings.console = True
settings.gui = False
| twoolie/Minecraft-Tools | src/minecraft/conf.py | Python | mit | 227 |
from . import queue_monitor
if __name__ == '__main__':
queue_monitor.main()
| gabfl/redis-priority-queue | src/__main__.py | Python | mit | 81 |
"""This is oldowan.genbank.parse."""
__all__ = ['parse_genbank']
from oldowan.genbank.constants import INCLUDE
from oldowan.genbank.utility import join_stripped_lines
import re
#
# PARSER
#
def parse_genbank(entry, include=INCLUDE):
"""Parse text of genbank entry into dictionary.
"""
include = set(inc... | ryanraaum/oldowan.genbank | oldowan/genbank/parse.py | Python | mit | 6,831 |
"""These are the actual Sphinx directives we provide, but they are skeletal.
The real meat is in their parallel renderer classes, in renderers.py. The split
is due to the unfortunate trick we need here of having functions return the
directive classes after providing them the ``app`` symbol, where we store the
JSDoc ou... | erikrose/sphinx-js | sphinx_js/directives.py | Python | mit | 2,863 |
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
luckyday = models.DateField('lucky day', blank=True, null=True)
def __unicode__(self):
return u'Profile of user: %s... | youtaya/mothertree | monthertree/muser/models.py | Python | mit | 576 |
from common import *
import unittest
import run4v
run4v.VERBOSE = False
class TestVaspFile(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_createFile(self):
fileName = "TEST_VASPFILE"
vaspFile = run4v.VASPFile(fileName = fileName, autogen = Fals... | alejandrogallo/run4v | run4v/tests/test_vaspfiles.py | Python | mit | 1,712 |
# -*- coding: utf-8 -*-
#
# GopPy documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 16 15:40:24 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | jgosmann/goppy | doc/conf.py | Python | mit | 8,469 |
"""
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.
Usage as a context manager:
with manual_report("stats entry name"):
# Run time of this block will be reported under a stats entry called ... | locustio/locust | examples/manual_stats_reporting.py | Python | mit | 2,145 |
import h5py
class AuthException(Exception):
pass
class NotFoundException(Exception):
pass
class LoginError(Exception):
def __init__(self, message, redirect_url=None):
super(LoginError, self).__init__(message)
self.redirect_url = redirect_url
def validate_file(path: str) -> bool:
... | BiRG/Omics-Dashboard | omics/omics_dashboard/data_tools/util.py | Python | mit | 574 |
"""
<Program Name>
util.py
<Author>
Konstantin Andrianov
<Started>
March 24, 2012. Derived from original util.py written by Geremy Condra.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Provides utility services. This module supplies utility functions such as:
get_file_details() that com... | secure-systems-lab/securesystemslib | securesystemslib/util.py | Python | mit | 12,971 |