code
stringlengths
6
947k
repo_name
stringlengths
5
100
path
stringlengths
4
226
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
# Copyright 2018 Joseph Wright <joseph@cloudboss.co> # # 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, mer...
cloudboss/bossimage
bossimage/cli.py
Python
mit
5,303
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
starze/openhab2
openhab2/scripts/nilan_connectiontest.py
Python
mit
1,939
from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ import re class ComplexPasswordValidator(object): def validate(self, password, user=None): regex = '(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@#!%*?&])[A-Za-z\d$@#!%*?&]' if not re.match(regex, passwo...
foundertherapy/django-users-plus
accountsplus/validators.py
Python
mit
711
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("admin_interface", "0008_change_related_modal_background_opacity_type"), ] operations = [ migrations.AddField( m...
fabiocaccamo/django-admin-interface
admin_interface/migrations/0009_add_enviroment.py
Python
mit
960
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
ibackus/compare-changa-builds
compchanga/runTest.py
Python
mit
17,957
"""A high-speed, production ready, thread pooled, generic HTTP server. Simplest example on how to use this module directly (without using CherryPy's application machinery):: from cherrypy import wsgiserver def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Cont...
CodyKochmann/sync_lab
simple_notepad_server/cherrypy/wsgiserver/wsgiserver2.py
Python
mit
90,364
# Generated by Django 2.2.25 on 2022-01-03 12:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("users", "0022_auto_20191015_0510"), ] operations = [ migrations.AlterField( model_name="user", name="notify_unassig...
watchdogpolska/poradnia
poradnia/users/migrations/0023_auto_20220103_1354.py
Python
mit
618
import jwt from time import time from partner_data import partners """ Returns the partner object of given partnerId Args: ssoId Id of the partner Returns: The partner object """ def getSSOPartnerById(ssoId): if ssoId in partners and partners[ssoId]['is_active']: return partners[ssoId] rais...
linways/SSO-with-JWT
examples/python/utils.py
Python
mit
1,137
from setuptools import setup, find_packages import sys if sys.version_info[0] < 3 or sys.version_info[1] < 5: sys.exit('Sorry, Python < 3.5 is not supported') setup(name='waybackscraper', version='0.5', description='Scrapes a website archives on the wayback machine using asyncio.', author='Arthu...
abrenaut/waybackscraper
setup.py
Python
mit
608
"""Gopher protocol client interface.""" __all__ = ["send_selector","send_query"] # Default selector, host and port DEF_SELECTOR = '1/' DEF_HOST = 'gopher.micro.umn.edu' DEF_PORT = 70 # Recognized file types A_TEXT = '0' A_MENU = '1' A_CSO = '2' A_ERROR = '3' A_MACBINHEX = '4' A_PCBIN...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/gopherlib.py
Python
mit
5,564
import scrapy from scrapy import Request class CWACResultsSpider(scrapy.Spider): name = "cw-all-candidates" def start_requests(self): for i in range(60): if self.endpoint == 'archive': yield Request('https://web.archive.org/web/20160823114553/http://eciresults.ni...
factly/election-results-2017
manipur/manipur/spiders/results_spider.py
Python
mit
2,491
"""Module with views for the employee feature.""" from django.contrib import messages from django.contrib.auth import logout from django.contrib.auth.decorators import login_required, permission_required from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render from...
VirrageS/io-kawiarnie
caffe/employees/views.py
Python
mit
2,869
# coding=utf-8 """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base....
angadpc/Alexa-Project-
twilio/rest/taskrouter/v1/workspace/__init__.py
Python
mit
24,809
import tornado.ioloop import tornado.web import json import MySQLdb class MainHandler(tornado.web.RequestHandler): # def fetch_states(self): # pincode_file = open('pincode.json') # pincode_json = json.load(pincode_file) # state_list = {} # state_list['states'] = [] # state_list['state_count'] = 0 # for...
Mitali-Sodhi/CodeLingo
Dataset/python/pincode.py
Python
mit
3,279
__all__ = ['setup', 'get_db'] from modelplus.store import redis_db, sqlite_db store = None def setup(params): """ 'redis' : { host, port, db } 'sqlite' : { file } 'mysql' : { host, port, db } 'riak' : { host, port, bucket } 'mongodb' : { host, port, bucket } ""...
koblas/modelplus
modelplus/__init__.py
Python
mit
552
#!/usr/bin/env python """ Test cases for tournament.py """ from tournament import * def testDeleteMatches(): """ test deleteMatches. """ deleteMatches() print "1. Old matches can be deleted." def testDelete(): deleteMatches() deletePlayers() print "2. Player records can be deleted." def t...
recto/udacity_full_stack_web_developer
P2_Tournament_Results/tournament_test.py
Python
mit
12,215
#!/usr/bin/python import os, sys # low level handling, such as command line stuff import string # string methods available import re # regular expressions import getopt # comand line argument handling from low import * # custom functions, written by myself from misa import MisaSSR from collecti...
lotharwissler/bioinformatics
python/misa/exonic-ssrs-to-genes.py
Python
mit
3,457
# coding:utf-8 from django.test import TestCase # Create your tests here.
giliam/turbo-songwriter
backend/songwriter/tests.py
Python
mit
75
from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ArticleView) urlpatterns = router.urls
shady831213/myBlog
myBlog/articles/urls.py
Python
mit
156
import unittest import os import numpy as np from tools.sampling import read_log_file from tools.walk_trees import walk_trees_with_data from tools.game_tree.nodes import ActionNode, BoardCardsNode, HoleCardsNode LEDUC_POKER_GAME_FILE_PATH = 'games/leduc.limit.2p.game' class SamplingTests(unittest.TestCase): def...
JakubPetriska/poker-cfr
test/sampling_tests.py
Python
mit
2,099
#!/usr/bin/env python """ timed_out_and_back.py - Version 1.1 2013-12-20 A basic demo of the using odometry data to move the robot along and out-and-back trajectory. Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2012 Patrick Goebel. All rights reserved. This program is free software; you ca...
robertjacobs/zuros
zuros_test/src/timed_out-and-back.py
Python
mit
3,599
__author__ = 'thor' import ut as ms import pandas as pd import ut.pcoll.order_conserving from functools import reduce class SquareMatrix(object): def __init__(self, df, index_vars=None, sort=False): if isinstance(df, SquareMatrix): self = df.copy() elif isinstance(df, pd.DataFrame): ...
thorwhalen/ut
daf/struct.py
Python
mit
2,689
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
animekita/selvbetjening
selvbetjening/core/mailcenter/models.py
Python
mit
6,200
import argparse import sys import os from django.template import Template, Context from django.conf import settings as django_settings import django __author__ = 'moshebasanchig' def _create_file_from_template(template_file_name, destination_file_name, topology_name): with open(template_file_name, 'r') as templa...
Convertro/Hydro
src/hydro/hydro_cli.py
Python
mit
3,144
from os import environ environ['THIS'] = 'that'
oh-my-fish/plugin-foreign-env
test.py
Python
mit
49
import sys import unittest import json import logging from representor import Representor from representor.adapters.hale_json import HaleJSONAdapter hale_example = """{ "_meta": { "any": { "json": "object" } }, "attribute": "value", "_links": { "self": { ...
the-hypermedia-project/representor-python
tests/adapters/hale_json_test.py
Python
mit
4,564
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright @ 2014 Mitchell Chu from __future__ import (absolute_import, division, print_function, with_statement) import tornado.web import torndsession.session class SessionBaseHandler(tornado.web.RequestHandler, torndsession.session.SessionM...
MitchellChu/torndsession
torndsession/sessionhandler.py
Python
mit
964
import os import subprocess from pymongo import MongoClient from flask import Flask, redirect, url_for, request, flash from flask_bootstrap import Bootstrap from flask_mongoengine import MongoEngine from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider...
mass-project/mass_server
mass_flask_config/app.py
Python
mit
2,133
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import tornado.ioloop try: import WebApp except ImportError, ImportWarning: import entire as WebApp if __name__ == "__main__": ip = os.environ['OPENSHIFT_DIY_IP'] port = int(os.environ['OPENSHIFT_DIY_PORT']) WebApp.application.listen(port,...
swoiow/iabe-tool
openshift.py
Python
mit
370
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
altvod/pymander
examples/simple.py
Python
mit
1,893
from django.conf.urls.defaults import * from django.contrib.auth import views as auth_views from app_auth.views import * from app_auth.views import login as custom_login, logout as custom_logout urlpatterns = patterns('', # Home url(r'^$', home, name="app_auth.home"), # Login / logout url(r'^login/...
marco-lancini/Showcase
app_auth/urls.py
Python
mit
1,930
from urllib.parse import urlparse from collections import namedtuple import socket import requests from requests.packages import urllib3 from bs4 import BeautifulSoup import rethinkdb as r from celery import Celery from celery.utils.log import get_task_logger import pyasn import geoip2.database, geoip2.errors import ...
NicolasLM/crawler
crawler/crawler.py
Python
mit
3,682
from __future__ import absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def setUp(self): self.da = deviantart.Api(C...
neighbordog/deviantart
tests/test_api.py
Python
mit
1,335
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Flask-Dance example. This example demonstrates how to integrate a server application with Authentiq Connect. It uses the popular Flask-Dance package to make this trivial in Flask. """ from __future__ import ( absolute_import, division, print_function, u...
AuthentiqID/examples-flask
example_dance.py
Python
mit
2,000
# 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 may ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_express_route_circuit_connections_operations.py
Python
mit
19,491
#!/usr/bin/env python #coding: utf-8 class DoError(RuntimeError): pass
meganlkm/dopy
dopy/exceptions.py
Python
mit
77
from google.appengine.ext import db class MyEntity(db.Model): name = db.StringProperty()
toomoresuch/pysonengine
parts/gaeunit/sample_app/model.py
Python
mit
92
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-26 14:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0013_auto_20170718_2137'), ] operations = [ migrations.AlterModelOption...
pattisdr/lookit-api
accounts/migrations/0014_auto_20170726_1403.py
Python
mit
702
# postgresql/__init__.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import base, psycopg2, pg8000, pypostgresql, zxjdbc base.dialect = psyc...
michaelBenin/sqlalchemy
lib/sqlalchemy/dialects/postgresql/__init__.py
Python
mit
1,233
''' Created on Jan 5, 2014 @author: Rob ''' import unittest class ObjectTreeTests(unittest.TestCase): def setUp(self): from byond.objtree import ObjectTree self.tree = ObjectTree() def test_consumeVariable_basics(self): test_string = 'var/obj/item/weapon/chainsaw = new' ...
ComicIronic/ByondToolsv3
tests/ObjectTree.py
Python
mit
2,925
# -*- coding: utf-8 -*- """ Authentication, Authorization, Accouting @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: (c) 2010-2015 Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated docum...
michaelhowden/eden
modules/s3/s3aaa.py
Python
mit
357,874
answer1 = widget_inputs["check1"] answer2 = widget_inputs["check2"] answer3 = widget_inputs["check3"] answer4 = widget_inputs["check4"] is_correct = False comments = [] def commentizer(new): if new not in comments: comments.append(new) if answer1 == True: is_correct = True else: is_correct = is_c...
udacity/responsive-images
grading_scripts/2_5.py
Python
mit
1,377
from delete import PostDeleteHandler from show import PostShowHandler from edit import PostEditHandler from create import PostNewHandler from index import BlogIndexHandler
brusznicki/multi-user-blog
handlers/post/__init__.py
Python
mit
171
""" Django settings for CollegeSeatAllocation project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from django.core.urlresolvers import reverse_lazy from os.pat...
abhijithanilkumar/CollegeSeatAllocation
src/CollegeSeatAllocation/settings/base.py
Python
mit
4,017
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools import find_packages from os.path import join, dirname import pyss import unittest setup( name='pyss', version=pyss.__version__, packages=find_packages(), long_de...
vpv11110000/pyss
setup.py
Python
mit
533
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
indico/indico
indico/web/flask/wrappers.py
Python
mit
9,269
letras=[] i=1 while i <= 10: letras.append(input("letras : ")) i+=1 i=0 cont=0 while i <=9: if letras[i] not in 'aeiou': cont+=1 i+=1 print("foram lidos %d consoantes" %cont)
andersonsilvade/python_C
Python32/aulas/letras.py
Python
mit
199
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import request from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH...
indico/indico
indico/modules/auth/blueprint.py
Python
mit
2,168
from setuptools import setup setup( name='kf5py', py_modules = ['kf5py'], version='0.1.8', author='Chris Teplovs', author_email='dr.chris@problemshift.com', url='http://problemshift.github.io/kf5py/', license='LICENSE.txt', description='Python-based utilities for KF5.', install_requ...
problemshift/kf5py
setup.py
Python
mit
711
import socket from logging import Filter from summer.settings import APP_CONFIG class IPFilter(Filter): def __init__(self, name=''): super(IPFilter, self).__init__(name) self.ip = socket.gethostbyname(socket.gethostname()) def filter(self, record): record.ip = self.ip + ':%s' % APP_CO...
blakev/sowing-seasons
summer/ext/logs.py
Python
mit
362
import logging # noinspection PyUnresolvedReferences import feature #noqa logging.basicConfig(level=logging.DEBUG) class Rollout(object): __version__ = '0.3.5' def __init__(self, feature_storage=None, user_storage=None, undefined_feature_access=False): """ Manage feature flags for groups, u...
brechin/pyrollout
pyrollout/rollout.py
Python
mit
2,301
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('session', '0012_auto_20160904_1130'), ] operations = [ migrations.AlterField( model_name='serversetting', ...
PeteTheAutomator/ACServerManager
session/migrations/0013_auto_20160904_1252.py
Python
mit
858
from datetime import date from django.db import models from smart_selects.db_fields import ChainedForeignKey from urlparse import urlparse class Organization(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Season(models.Model): name = models....
cooperthompson/ct-com
soccercal/models.py
Python
mit
3,010
# coding: utf8 from matriochkas.core import ParsingEntities from collections import Counter from threading import Thread from time import sleep import copy ######################################################################################################################## class InstanceParsingEntity(ParsingEnt...
JCH222/matriochkas
matriochkas/tests/ParsingEntities.py
Python
mit
69,308
# -*- coding: utf-8; -*- import sys import os.path import fnmatch from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, s...
scottdarch/Arturo
ano/filters.py
Python
mit
2,756
import os import internetarchive folder = 'pages' def from_IA(book, item, filepattern, start, steps, finish): if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book): os.makedirs(os.getcwd() + os.sep + folder + os.sep + book) session = internetarchive.ArchiveSession() re_item = sess...
the-it/WS_THEbotIT
archive/offline/download_RE_pics_OCR/make_single_pages.py
Python
mit
1,366
import requests import json import os API_TAGO = os.environ.get('TAGO_API') or 'https://api.tago.io' REALTIME = os.environ.get('TAGO_REALTIME') or 'https://realtime.tago.io' class RunUser: def __init__(self, token): self.token = token self.default_headers = { 'content-type': 'application/json', 'Devi...
tago-io/tago-python
tago/run_user/__init__.py
Python
mit
3,335
import argparse import importlib import inspect import os import sys import traceback from bokeh.plotting import output_file, show from fabulous.color import bold, red from app import create_app def error(msg, stacktrace=None): """Print an error message and exit. Params: ------- msg: str Er...
saltastro/salt-data-quality-site
test_bokeh_model.py
Python
mit
2,995
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
TwoBitAlchemist/PyBaseConvert
base_convert.py
Python
mit
2,899
import RPi.GPIO as GPIO import time import os import psutil import subprocess # Get framebuffer resolution proc = subprocess.Popen(["fbset | grep 'mode '"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() i = out.index('"') + 1 out = out[i:] i = out.index('"') out = out[:i] i = out.index('x') xres ...
kr15h/digital-fabrication-studio
examples/anne-marie-projected-notebook/switch.py
Python
mit
1,658
#! /usr/bin/env python2.7 ''' Substitutions that make reading the news more fun! Inspired from https://xkcd.com/{1004,1031,1288,1418,1625,1679}/. ''' import re import sys import json import random import hashlib import textwrap import itertools from datetime import datetime from argparse import (ArgumentParser, RawDe...
clickyotomy/xkcd-substitutions
read.py
Python
mit
11,006
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-30 17:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0062_auto_20171223_1552'), ] operations = [ migrations.AddField( ...
OKThess/website
main/migrations/0063_event_date_end.py
Python
mit
469
# Copy of ntptime.py with millisecond-accurate sync try: import usocket as socket except: import socket try: import ustruct as struct except: import struct # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 3155673600 MILLIS_PER_SECOND = 1000 host = "pool.ntp.org" def time(ms_accur...
puhitaku/AutoChime
ntptime_kai.py
Python
mit
1,216
import numpy as np from .base_signal import BaseSignal __all__ = ['CAR'] class CAR(BaseSignal): """Signal generatpr for continuously autoregressive (CAR) signals. Parameters ---------- ar_param : number (default 1.0) Parameter of the AR(1) process sigma : number (default 1.0) Sta...
TimeSynth/TimeSynth
timesynth/signals/car.py
Python
mit
1,472
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-14 14:16 from __future__ import unicode_literals from django.db import migrations def move_region_to_regions(apps, schema_editor): PublicBody = apps.get_model("publicbody", "PublicBody") for pb in PublicBody.objects.filter(region__isnull=False)...
fin/froide
froide/publicbody/migrations/0024_auto_20181114_1516.py
Python
mit
556
from time import time start = time() sum = 0 for i in range(1, 1001): sum += i ** i print(str(sum)[-10:]) end = time() print(end - start)
kayson-hansen/Project-Euler
Python/048_self_powers.py
Python
mit
156
# Copyright (c) 2007-2009 Thomas Herve <therve@free.fr>. # See LICENSE for details. """ Test utilities. """ from twisted.trial.unittest import TestCase as TrialTestCase class TestCase(TrialTestCase): """ Specific TestCase class to add some specific functionalities or backport recent additions. """
therve/twotp
twotp/test/util.py
Python
mit
320
from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_user_item( item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None ): item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit} return item
tiangolo/fastapi
docs_src/query_params/tutorial006b.py
Python
mit
301
'http://fastml.com/best-buy-mobile-contest/' import sys, csv, re def prepare( query ): query = re.sub( r'[\W]', '', query ) query = query.lower() return query popular_skus = [9854804, 2107458, 2541184, 2670133, 2173065] input_file = sys.argv[1] test_file = sys.argv[2] output_file = sys.argv[3] i = open( input_f...
zygmuntz/kaggle-bestbuy_small
train.py
Python
mit
1,432
"""Tests for the frequency module in analysis""" import pytest from lantern.analysis import frequency def test_frequency_analyze(): """Testing frequency analyze works for ngram = 1""" assert frequency.frequency_analyze("abb") == {'a': 1, 'b': 2} def test_frequency_analyze_bigram(): """Testing frequenc...
CameronLonsdale/lantern
tests/analysis/test_frequency.py
Python
mit
2,466
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from .test_base import BaseSparrayTest, dense2d class TestTrueDivision(BaseSparrayTest): def test_truediv(self): c = 3 assert_array_almost_equal(dense2d / c, (self.sp2d / c).toarray()) with np.errstate(divide='ignor...
perimosocordiae/sparray
sparray/tests/test_truediv.py
Python
mit
662
import struct import binascii import binwalk.core.plugin class UBIValidPlugin(binwalk.core.plugin.Plugin): ''' Helps validate UBI erase count signature results. Checks header CRC and calculates jump value ''' MODULES = ['Signature'] current_file=None last_ec_hdr_offset = None peb_size...
sviehb/binwalk
src/binwalk/plugins/ubivalid.py
Python
mit
2,142
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
comger/migrant
doc/importnews.py
Python
mit
1,183
from browser.models import Crop from django.contrib import admin admin.site.register(Crop)
georgejlee/croptrends
browser/admin.py
Python
mit
91
import os import tempfile import re import bottle import PIL.Image import PIL.ImageDraw import PIL.ImageFont formats = { 'png': { 'format': 'PNG', 'mimetype': 'image/png' }, 'jpg': { 'format': 'JPEG', 'mimetype': 'image/jpeg' }, 'gif': { 'format': 'GIF', ...
whardier/holder.graphics
passenger_wsgi.py
Python
mit
3,866
import cv2 import sys #cascPath = sys.argv[1] #faceCascade = cv2.CascadeClassifier(cascPath) faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') video_capture = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2...
papajijaat/Face-Detect
code/face_detect.py
Python
mit
869
from django.http import JsonResponse
sussexstudent/falmer
falmer/studentgroups/views.py
Python
mit
37
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
tooringanalytics/pyambiguity
m2py.py
Python
mit
1,433
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6): print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1) install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requi...
spreaker/android-publish-cli
setup.py
Python
mit
975
#!/usr/bin/python # -*- coding: utf-8 -*- # Error Log model import logging logger = logging.getLogger('con_science_bot') hdlr = logging.FileHandler('logs/error.log') formatter = logging.Formatter('\n%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.IN...
hsadler/con-science-twitter-bot
models/error_log.py
Python
mit
1,068
import os from keen.client import KeenClient from keen.exceptions import InvalidEnvironmentError __author__ = 'dkador' _client = None project_id = None write_key = None read_key = None master_key = None base_url = None def _initialize_client_from_environment(): ''' Initialize a KeenClient instance using environm...
keenlabs/KeenClient-Python
keen/__init__.py
Python
mit
31,368
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def register_package(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localprox...
Dinoshauer/pryvate
pryvate/blueprints/pypi/pypi.py
Python
mit
1,874
class ArrayList: def __init__(self, ): self.sizeExponent = 0 self.maxSize = 0 self.lastIndex = 0 self.myArray = [] def append(self,val): if self.lastIndex > self.maxSize-1: self.__resize() self.myArray[self.lastIndex] = val self.lastInde...
robin1885/algorithms-exercises-using-python
source-code-from-author-book/Listings-for-Second-Edition/listing_8_1.py
Python
mit
640
""" Platform for Ecobee Thermostats. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.ecobee/ """ import logging from os import path import voluptuous as vol from homeassistant.components import ecobee from homeassistant.components.climate import...
betrisey/home-assistant
homeassistant/components/climate/ecobee.py
Python
mit
9,405
from abc import ABCMeta, abstractmethod class Edge: """ Phylogenetic tree edge. Connects start and end node with some given distance measure """ def __init__(self, startNode, endNode, distance): self.distance = distance self.setEndNode(endNode) self.setStartNode(startNode) def setStartNode(self, node...
usoban/pylogenetics
pylogen/tree.py
Python
mit
2,030
"""Tests for the main nhlscraper CLI module""" from subprocess import PIPE, getoutput from unittest import TestCase from nhl_logo_scraper import __version__ as VERSION class TestHelp(TestCase): def test_returns_usage_information(self): output = getoutput("nhlscraper -h") self.assertTrue('Usage:' ...
blindman/nhl-logo-scraper
tests/test_cli.py
Python
mit
604
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 import os.path from PIL import Image import piexif import argparse # Commandline Handling parser = argparse.ArgumentParser(description='Export faces from Lightroom DB') parser.add_argument('-d', '--database', help='Input Database', required=True) parser.add_ar...
ThomasMoritz/exportlightroomfaces
getfaces.py
Python
mit
5,178
# coding: utf-8 import datetime from mock import patch, ANY from django.core.urlresolvers import reverse from django.test.utils import override_settings from django.test import TestCase from django.contrib.auth.models import User from .utils import mock_signal_receiver from .models import EmailConfirmation, Confirmat...
futurecolors/django-confirmanager
confirmanager/tests.py
Python
mit
10,684
'''GUI for PyMOLProbity plugin.''' from __future__ import absolute_import import logging import Pmw import sys if sys.version_info[0] < 3: import Tkinter as tk import tkMessageBox else: import tkinter as tk import tkinter.messagebox as tkMessageBox from pymol import cmd from . import main logger =...
jaredsampson/pymolprobity
pymolprobity/gui.py
Python
mit
24,033
import os, sys, subprocess, tarfile, shutil def unpack_prebuilt_postgres(): if not os.access( POSTGRES_BINARY_ARCHIVE, os.F_OK ): print "unpack_prebuilt_postgres(): No binary archive of Postgres available for this platform - will build it now" build_postgres() else: print "unpack_prebui...
dbcls/dbcls-galaxy
scripts/scramble/scripts/psycopg2.py
Python
mit
4,933
"""Geometry functions and utilities.""" from enum import Enum from typing import Sequence, Union import numpy as np # type: ignore from pybotics.errors import PyboticsError class OrientationConvention(Enum): """Orientation of a body with respect to a fixed coordinate system.""" EULER_XYX = "xyx" EULER...
nnadeau/pybotics
pybotics/geometry.py
Python
mit
4,716
from qcodes.instrument.base import Instrument from qcodes.utils import validators as vals from qcodes.instrument.parameter import ManualParameter import numpy as np class SimControlCZ(Instrument): """ Noise and other parameters for cz_superoperator_simulation_new """ def __init__(self, name, **kw): ...
DiCarloLab-Delft/PycQED_py3
pycqed/instrument_drivers/virtual_instruments/sim_control_CZ.py
Python
mit
11,275
"""Contains logic that is unique to the horizontal grid lines.""" from lib.grid_lines import GridLines class Horizontal(GridLines): """Contains logic that is unique to the horizontal grid lines.""" def __init__(self, image): """Build horizontal grid lines.""" super().__init__(image) ...
rafelafrance/boyd-bird-journal
lib/horizontal_lines.py
Python
mit
850
#This doesn't actually do anything, its just a gui that looks like the windows one(kinda) from Tkinter import * mGui=Tk() mGui.geometry('213x240') mGui.title('Calculator') mGui["bg"]="#D9E3F6" ##set images image1 = PhotoImage(file="images/mc.gif") image2 = PhotoImage(file="images/mr.gif") image3 = PhotoImage(file="i...
covxx/Random-Python-Stuff
WindowsCalc.py
Python
mit
4,314
from . import Model, LazyModelMixin, LazyDictFromArrayModel, ArrayModel, Account, Amount, Images, PdfableModelMixin, NoneableModelMixin from eactivities.parsers.finances import FinancesParser, BankingRecordsParser, SalesInvoicesParser, ClaimsParser, PurchaseOrdersParser, \ TransactionCorrectionsParser, InternalCh...
lukegb/ehacktivities
eactivities/models/finances.py
Python
mit
7,365
#!/usr/bin/env python import os import sys from importlib import import_module if __name__ == "__main__": settings_module = "example.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from...
jonykalavera/django-tastypie-batch
example/manage.py
Python
mit
418
import json import os import re import base64 import datetime import mistune import dbconn import dbutil from contextlib import suppress from hashlib import md5 from steem.blockchain import Blockchain from steem.utils import block_num_from_hash from bs4 import BeautifulSoup from langdetect import detect class Article:...
taeminlee/steemtrend.crawler
crawl.py
Python
mit
2,436
import requests import json NL_KEY = '*' TL_KEY = '*' def translate(text): tmp_payload = {"q": text, "target": "en"} s = requests.post('https://translation.googleapis.com/language/translate/v2?key=' + TL_KEY, json=tmp_payload) data = s.json()['data']['translations'][0] return data['translatedText'] d...
thiagoald/hardmob_information_extractor
sources/generate_sentiments.py
Python
mit
1,731
import os import sys from icbd.type_analyzer import type_system, type_checker, builtins from . import compiler_types from .code_emitter import CodeEmitter class InferredTypeOutput(object): def __init__(self, fn, pythonpath=[]): self._made_classes = {} fn = os.path.abspath(fn) e = type_che...
kmod/icbd
icbd/compiler/type_conversion.py
Python
mit
10,551
def test_PointMutationExecutor(): from pkg_resources import resource_filename from simtk import unit from perses.app.relative_point_mutation_setup import PointMutationExecutor pdb_filename = resource_filename("perses", "data/ala_vacuum.pdb") PointMutationExecutor( pdb_filename, "1"...
choderalab/perses
perses/tests/test_relative_point_mutation_setup.py
Python
mit
1,033