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 subprocess
import click
@click.command()
def cli():
""" Start all services. """
cmd = 'honcho start'
return subprocess.call(cmd, shell=True)
| z123/build-a-saas-app-with-flask | cli/commands/cmd_all.py | Python | mit | 163 |
"""Database Populate module.
This module contains functions for populating a database with PAF data.
The data is split across a number of files (as explained elsewhere), and so
each file must be parsed and the data inserted into the database.
"""
from paf_tools import database
from paf_tools.database.tables import ... | DanMeakin/paf-tools | paf_tools/populate/populate.py | Python | mit | 1,589 |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
#-*- coding: utf-8 -*-
import json
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User as DjangoUs... | rogeriofalcone/treeio | finance/api/tests.py | Python | mit | 15,550 |
import numpy
class Clusters(object):
def __init__(self, data_in, clusters_in):
self.data = data_in
if type(clusters_in) is int:
#self.clusters = [Cluster(get_random_value_from_list(data_in)) for i in range(0, clusters_in)]
#self.clusters = []
cluster_origins = [... | FlintHill/SUAS-Competition | UpdatedImageProcessing/UpdatedImageProcessing/ShapeDetection/utils/cluster.py | Python | mit | 3,430 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of Pynspect package (https://pypi.python.org/pypi/pynspect).
# Originally part of Mentat system (https://mentat.cesnet.cz/).
#
# Copyright (C) since 2016 CESNET, z.s.p.o (h... | honzamach/pynspect | pynspect/tests/test_filters_idea.py | Python | mit | 19,028 |
import math
import bitstring as bt
from research.coding.common import BitEncoder, BitDecoder
class Decoder(BitDecoder):
def decode(self):
return self.stream.read('ue')
class Encoder(BitEncoder):
def encode(self, n):
self.bit_stream.append(bt.pack('ue', n))
| west-tandon/ReSearch | research/coding/golomb.py | Python | mit | 287 |
from req import Service
from service.base import BaseService
from utils.form import form_validation
class SchoolService(BaseService):
def __init__(self, db, rs):
super().__init__(db, rs)
SchoolService.inst = self
def get_school_list(self):
res = yield self.db.execute('SELECT * FROM sch... | Tocknicsu/nctuoj | backend/service/school.py | Python | mit | 784 |
"""
WSGI config for DevelopersShelf project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJAN... | hkdahal/DevelopersShelf | DevelopersShelf/wsgi.py | Python | mit | 407 |
from mesa.visualization.ModularVisualization import ModularServer
from LabModel import LabModel
from CoffeMakerAgent import CoffeMakerAgent
from TVAgent import TVAgent
from AccessAgent import AccessAgent
from PC import PC
from DrawLabMapBackEnd import DrawLabMapBackEnd
from DrawLabMapBackEnd import RepresentationModule... | gsi-upm/soba | projects/oldProyects/EWESim/Visual.py | Python | mit | 2,183 |
#!/bin/python
# -*- coding: utf-8 -*-
import urllib2
import re
import logging
def webpage_urlopen(url, crawl_timeout):
"""
webpage_urlopen - Function to get content from specific url.
Args:
url: The source url to be request.
crawl_timeout: The request timeout value.
Retur... | fivezh/Keepgoing | py_spider/webpage_urlopen.py | Python | mit | 2,074 |
# -*- coding: utf-8 -*-
from lode_runner import dataprovider
from unittest import TestCase
try:
from mock import patch, Mock
except ImportError:
from unittest.mock import patch, Mock
from tests.helpers import get_response_from_file, wait_for
from stf_utils.stf_connect.client import SmartphoneTestingFarmClien... | 2gis/stf-utils | tests/test_stf_connect_client.py | Python | mit | 6,649 |
#!/usr/bin python
# -*- coding: utf-8 -*-
"""
This file is part of the pyquaternion python module
Author: Kieran Wynn
Website: https://github.com/KieranWynn/pyquaternion
Documentation: http://kieranwynn.github.io/pyquaternion/
Version: 1.0.0
License: The MIT License (MIT)
Copyright (c... | KieranWynn/pyquaternion | pyquaternion/test/test_quaternion.py | Python | mit | 42,034 |
# from config import DevelopmentConfig
# configs = DevelopmentConfig()
import os
import re
def config(key):
val = os.environ.get(key)
if val and re.match('true', val, re.I):
val = True
elif val and re.match('false', val, re.I):
val = False
return val | whittlbc/jarvis | jarvis/helpers/configs.py | Python | mit | 265 |
from ..domain import Image, Font
from ._base import Service
class ImageService(Service):
def __init__(self, template_store, font_store, image_store, **kwargs):
super().__init__(**kwargs)
self.template_store = template_store
self.font_store = font_store
self.image_store = image_st... | DanLindeman/memegen | memegen/services/image.py | Python | mit | 881 |
# coding:utf-8
def hello(fn):
fn('asd')
def test(name):
print name
hello(test)
# 匿名
def hello(fn):
print fn('asd')
hello(lambda x: 'hello '+x ) | seerjk/reboot06 | 08/bootstrap/08.py | Python | mit | 165 |
# -*- coding: utf-8 -*-
"""
Запуск моделирования, остановка и пауза сети.
"""
from openre.agent.decorators import action
from openre.agent.domain.decorators import state
@action(namespace='domain')
@state('run')
def run(event):
"""
Запуск моделирования
"""
agent = event.pool.context['agent']
net ... | openre/openre | openre/agent/domain/action/run.py | Python | mit | 1,604 |
# Copyright (C) 2017 Zhixian MA <zxma_sjtu@qq.com>
"""
Rename samples of Best into the JHHMMSS.ss+/-DDMMSS.s style
Reference
=========
[1] math.modf
http://www.runoob.com/python/func-number-modf.html
"""
import os
import math
import numpy as np
import time
import argparse
def batch_rename_csv(listpath, batch, f... | myinxd/agn-ae | utils/sample-rename.py | Python | mit | 3,882 |
#!/usr/bin/python
from __future__ import print_function
import argparse
import sys
from .cmds import define
def main():
parser = argparse.ArgumentParser(
description="Find the board specification from Arduino IDE board.txt files" )
subparsers = parser.add_subparsers( metavar = 'command' )
defin... | devberry/cliduino | cliduino/__main__.py | Python | mit | 531 |
import argparse
import gzip
import sys
import re
import FeaturesCombiner
parser = argparse.ArgumentParser(description='combine POS tags (from tree-tagged file) with morphological features (from lefff lexicon)')
parser.add_argument('--language', default='french', type=str,
help='available languages... | arianna-bis/glass-box-nmt | combine_pos_morph_features.py | Python | mit | 1,559 |
import requests
import json
import datetime
TOGGL_URL = "https://www.toggl.com/api/v8"
class TogglUser(object):
def __init__(self, email, password):
self._auth = (email, password)
self.workspaces = {}
def currentTimeEntry():
resp = self.apiRequest("time_entries/current")
if re... | ramblex/lite-toggl | lite_toggl/toggl_api.py | Python | mit | 4,943 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-18 03:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('forms', '0001_initial'),
]
operations = [
migrations.AddField(
... | mleger45/turnex | forms/migrations/0002_turnexform_publish.py | Python | mit | 475 |
"""Test the validation for the core configuration schema."""
import json
import pytest
from flask_jsondash import charts_builder as app
def _schema(**vals):
"""Default schema."""
data = dict(
id='a-b-c-d-e',
date="2016-08-23 15:03:49.178000",
layout="grid",
name="testlayout",... | christabor/flask_jsondash | tests/test_jsonschema.py | Python | mit | 7,161 |
import unittest
from Db import Db
from Server import Prudence
from Server import User
from Server import Super_user
class MyTest(unittest.TestCase):
def test(self):
d = Db('localhost')
p = Prudence('ad','bb','localhost')
users_type = {True:Super_user,False:User}
raw_user = p.get_raw_user()
user = p.get_us... | arpho/bb | exporter/unitest.py | Python | mit | 692 |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import random
from pyqrllib.pyqrllib import bin2hstr
from pyqryptonight.pyqryptonight import UInt256ToString
from twisted.internet import reactor
from twisted.internet... | theQRL/QRL | src/qrl/core/p2p/p2pfactory.py | Python | mit | 24,304 |
#####
# Author : David Stewart
# Date : April 14, 2016
# Problem : https://projecteuler.net/problem=33
# Brief : There exist exactly four fractions of the form XY / ZX, YX / ZX, or XY / XZ such that removing the X digit preserves the answer. Find them, then find the lowest common denominator if they are m... | DavidOStewart/ProjectEuler | 33.py | Python | mit | 1,392 |
'''
TODO:
* More testing!
* Change 'similarities' from N*N to linear, so that speed is sub-second.
* Write a tutorial, in Jupyter notebook, to show what I did, and how it is SO FRIGGIN COOL!!!
* Fix other errors
'''
testWord = 'बन्दीप्रतिकोव्यवहारसम्बन्धीमापदण्डअनुकूलको'
def split_word(word):
'''Takes a word, r... | shirish93/CoLing | word_segmentation.py | Python | mit | 3,444 |
import os
import numpy as np
from vsm.structarr import arr_add_field
from vsm.split import split_corpus
__all__ = [ 'BaseCorpus', 'Corpus', 'add_metadata', 'align_corpora' ]
class BaseCorpus(object):
"""
A BaseCorpus object stores a corpus along with its tokenizations
(e.g., as sentences, paragraphs ... | iSumitG/vsm | vsm/corpus/base.py | Python | mit | 24,737 |
"""
WSGI config for EMEARoster 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... | faisaltheparttimecoder/EMEARoster | EMEARoster/wsgi.py | Python | mit | 489 |
import json
import threading
import accounts
lock = threading.Lock()
_stats = None
def _load():
global _stats
if _stats is None:
try:
_stats = json.loads(open(accounts.getFile('stats.txt')).read())
except Exception:
_stats = {}
def update(name, value):
with lock:
... | kalinochkind/vkbot | stats.py | Python | mit | 639 |
#!-*- coding:utf-8 -*-
"""
代理存活检测工具
结合gevent指定并发数进行并发存活检测
仿Yii框架中的console application执行方式
"""
import os
import time
import codecs
import gevent
import requests
import json
import sys
import gevent.monkey
gevent.monkey.patch_socket()
from gevent import monkey
monkey.patch_ssl()
sys.path.append('..')
from model.pro... | wanghuafeng/spider_tools | proxy_alive_check_utils.py | Python | mit | 9,900 |
"""
Functions for working with the CrossRef.org rest api.
"""
import re
import sys
import urllib
import requests
import unicodedata
from operator import itemgetter
from refkit.util import doi
from refkit.util import isbn
from refkit.util import citation
from refkit.metadata import Metadata
# Defaul... | CitrineInformatics/refkit | lookup/crossref.py | Python | mit | 13,256 |
# coding:utf-8
from flask.ext.login import UserMixin
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
active = db.Column(db.Boolean, default=False)
username = db.Column(db.String(60), ... | abacuspix/NFV_project | Build_Web_With_Flask/Building web applications with Flask_Code/chapter09/ex05/database.py | Python | mit | 1,108 |
import os
from subprocess import Popen
from multiprocessing import Pool
import pyxnat
url = 'https://imagen.cea.fr/imagen_database'
interface = pyxnat.Interface(url, login, password)
def bet(in_image):
path, name = os.path.split(in_image)
in_image = os.path.join(path, name.rsplit('.')[0])
out_image = os... | BrainIntensive/OnlineBrainIntensive | resources/HCP/pyxnat/pyxnat/examples/examples.py | Python | mit | 868 |
#from django.db.models import Model, TextField
#from djangotoolbox.fields import ListField, EmbeddedModelField, DictField
from django.contrib.auth.models import User
from django.db import connections
from bson.objectid import ObjectId
from pymongo.errors import InvalidId
import csv, re, json, datetime, random
from col... | abegong/textbadger | textbadger/tb_app/models.py | Python | mit | 17,389 |
# 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_11_01/aio/operations/_route_filters_operations.py | Python | mit | 30,024 |
#!/usr/bin/env python
import os
import datetime
import re
import sqlite3
# this function returns a count of the immediate subdirectories as an integer
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
# the base bath of t... | finoradin/moma-utils | pre-ingest-metrics/metrics.py | Python | mit | 6,065 |
from apps.account.models import User
from apps.common.hasher import get_hasher
from apps.common.serializers import HashidModelSerializer
from django.test import TestCase
class TestUserSerializer(HashidModelSerializer):
"""
For testing
"""
class Meta:
fields = ('pk', 'email')
model = Us... | RonquilloAeon/django-golden-image | src/apps/common/test/test_serializers.py | Python | mit | 955 |
from __future__ import unicode_literals
# -*- coding: utf-8 -*-
# Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
ganho = float(raw_input("Quanto você ganha por hora? \n"))
horas = int(raw_input("Quantas horas vo... | josecostamartins/pythonreges | lista1/exercicio7.py | Python | mit | 432 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Title(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattercarpet.marker.colorbar"
_path_str = "scattercarpet.marker.colorbar.title"
_valid_props... | plotly/python-api | packages/python/plotly/plotly/graph_objs/scattercarpet/marker/colorbar/_title.py | Python | mit | 6,786 |
from setuptools import find_packages, setup
import proxyprefix
setup(
name='proxyprefix',
version=proxyprefix.__version__,
description='Prefix SCRIPT_NAME with X-Forwarded-Prefix header',
long_description=proxyprefix.__doc__,
author='Yola',
author_email='engineers@yola.com',
license='MIT ... | yola/proxyprefix | setup.py | Python | mit | 769 |
def cycle_sort(nums):
n = len(nums)
for cycle_index in range(n - 1):
item, index = nums[cycle_index], cycle_index
for i in range(cycle_index + 1, n):
if nums[i] < item:
index += 1
if index == cycle_index:
continue
while item == nu... | sshh12/SchoolCode | Algorithms/SortingSeaching/CycleSort.py | Python | mit | 869 |
# Copyright (c) 2017 Weitian LI <liweitianux@live.com>
# MIT license
"""
Portal to 'acispy' module/package
"""
import os
import sys
sys.path.insert(
0,
os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
)
import acispy
| liweitianux/chandra-acis-analysis | bin/_context.py | Python | mit | 243 |
import math
for a in range(1,1000,1):
for b in range(1,1000,1):
c = math.sqrt(a**2+b**2)
if a + b +c == 1000:
print a, b, c
print a * b * c
else:
pass | WinCanton/PYTHON_CODE | PythagoreanTriplet/PythagoreanTriplet.py | Python | mit | 215 |
"""
An Armstrong number is equal to the sum of its own digits each raised to the
power of the number of digits.
For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers.
On-Line Encyclopedia of Integer Sequences... | TheAlgorithms/Python | maths/armstrong_numbers.py | Python | mit | 3,035 |
import random
class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
"""Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text]
key = []
cipher = []
for i in plain:
k = random.randint(1, 300)
... | TheAlgorithms/Python | ciphers/onepad_cipher.py | Python | mit | 872 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#現在日時を表示。
import datetime
if __name__ == "__main__":
today = datetime.date.today()
todaydetail = datetime.datetime.today()
print "now year is '", todaydetail.year, "'."
print "now month is '", todaydetail.month, "'."
print "n... | kotaro920oka/freescripts | show-now.py | Python | mit | 782 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# operation platform documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 1 12:57:18 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present i... | goodking-bq/golden-note | source/conf.py | Python | mit | 6,165 |
from django.db.models import F
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template... | hckrtst/learnpython | django/mysite/polls/views.py | Python | mit | 1,786 |
from __future__ import print_function
from itertools import chain
from collections import deque
from rbtree import rbtree
from log import get_logger
from trade import Trade
from orders import LimitBuyOrder, LimitSellOrder
logger = get_logger(__name__)
class OrderBook(object):
def __init__(self, trade_callback=p... | amidvidy/multimatch | multimatch/book.py | Python | mit | 4,553 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-03-22 17:44
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('visualize', '0002_loa... | brookefitzgerald/neural-exploration | neural_exploration/visualize/migrations/0003_binneddata.py | Python | mit | 2,380 |
'''
This uses the homemade Feather Wing doubler: one of the top boards is the
Feather Wing SSD1306 OLED and the other is a homemade board that has a
play/pause button and a potentiometer.
This micropython script displays songs that are being scrobbled to the mqtt broker
running in AWS EC2
On Huzzah ESP8266 Feather, bu... | slzatz/esp8266 | sonos_remote.py | Python | mit | 4,881 |
from collections import namedtuple
Notam = namedtuple('Notam', 'intro attributes')
Intro = namedtuple('Intro', 'id operation target')
NotamID = namedtuple('NotamID', 'series number year raw')
Attribute = namedtuple('Attribute', 'type body')
Coordinates = namedtuple('Coordinates', 'lon lat radius')
| dbrgn/notam-parse | notam/ast.py | Python | mit | 301 |
import logging
logging.basicConfig(level=logging.DEBUG, \
format="%(asctime)s" "[%(module)s:%(funcName)s:%(lineno)d]\n" "%(message)s \n" \
)
| ZhiweiYAN/weixin_project_logging | logmsg.py | Python | mit | 180 |
# Jorge Castanon, March 2016
# Data Scientist @ IBM
# run in terminal with comamnd sitting on YOUR-PATH-TO-REPO:
# ~/Documents/spark-1.5.1/bin/spark-submit ml-scripts/w2vAndKmeans.py
# Replace this line with:
# /YOUR-SPARK-HOME/bin/spark-submit ml-scripts/w2vAndKmeans.py
import numpy as np
import pandas as pd
import ... | castanan/w2v | ml-scripts/w2vAndKmeans.py | Python | mit | 4,285 |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | onshape-public/onshape-clients | python/onshape_client/oas/models/bt_export_tessellated_edges_body890_all_of.py | Python | mit | 5,176 |
import base64
def HexToBase64(hex_input):
hex_decoded = hex_input.decode("hex")
base64_encoded = base64.b64encode(hex_decoded)
return base64_encoded
def main():
assert "3q2+7w==" == HexToBase64("deadbeef"), HexToBase64("deadbeef")
assert "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" ==... | aawc/cryptopals | sets/1/challenges/common/hex_to_base64.py | Python | mit | 493 |
# Test various argument semantics for sendmess
#a dummy method so there is something to connect to
def nothing(rip,rport,msg,handle):
pass
# test that the locaip used by openconn is getmyip
def test_remoteip(rip,rport,msg,handle):
if rip != getmyip():
print 'remoteip did not equal getmyip: '+rip+' vs '+ge... | sburnett/seattle | network_semantics_tests/tests/sendmess/sendmess_arg.py | Python | mit | 1,901 |
#-*- coding: utf-8 -*-
# Todo : keras model 에서 predict_probs() 할 때 message off 하는 방법
# evaluator.run(img_files, do_nms=False) 에서 do_nms option 을 사용하지 않도록 detector 자체의 class 에서 nms 객체를 갖고 있도록 하자.
import cv2
import numpy as np
import digit_detector.region_proposal as rp
import digit_detector.detect as detect
import di... | penny4860/SVHN-deep-digit-detector | 4_evaluate.py | Python | mit | 2,449 |
import sys
from setuptools import setup
assert sys.version_info[0] > 2
if sys.version_info[0] == 3 and sys.version_info[1] < 5:
raise RuntimeError("Python >= 3.5 is required to install Streamis.")
def read(fname):
with open(fname, 'r') as f:
text = f.read()
return text
setup(
name="streamis",... | mivade/streamis | setup.py | Python | mit | 713 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: oesteban
# @Date: 2015-06-15 14:50:01
# @Last Modified by: Oscar Esteban
# @Last Modified time: 2015-06-23 13:05:13
| oesteban/diffantom | diffantom/scripts/__init__.py | Python | mit | 177 |
# -*- coding: utf-8 -*-
"""
Utility for generating placeholder images from http://placehold.it/
"""
import random
URL = 'http://placehold.it/%(width)sx%(height)s/%(bcolor)s/%(tcolor)s/'
def _get_random_color():
"""
Returns a random color hex value.
"""
return '%02X%02X%02X' % (
random.randint(... | datadesk/django-greeking | greeking/placeholdit.py | Python | mit | 1,207 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""http://www.pythonchallenge.com/pc/ring/bell.html:repeat:switch"""
__author__ = "子風"
__copyright__ = "Copyright 2015, Sun All rights reserved"
__version__ = "1.0.0"
import get_challenge
from PIL import Image
img = Image.open(get_challenge.download("http://ww... | z-Wind/Python_Challenge | Level28_Image_ch.py | Python | mit | 951 |
# coding=utf-8
from __future__ import absolute_import, division
import os
from typing import Union
from keras.preprocessing.image import img_to_array, array_to_img
import numpy as np
from pathlib import Path
from PIL import Image as PILImage, ImageOps
# I/O
def files_under(path: Path):
for f in path.glob("*"):
... | PavlosMelissinos/enet-keras | src/data/utils.py | Python | mit | 8,335 |
from __future__ import print_function
import os
import sys
import shutil
import pickle
from tinytag import TinyTagException
from tinytag import TinyTag
def removeNonAscii(s): return "".join(i for i in s if ord(i)<128 and ord(i)>0)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class MusicOr... | kpatsis/music_organizer | MusicOrganizer.py | Python | mit | 3,622 |
import urllib2
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
class ServiceGroupModel(models.Model):
"""
ServiceGroupModel holds services, so that you can have more than
one physical service per group, e.g. two databases
"""
n... | ograycode/ServiceZen | services/models.py | Python | mit | 3,131 |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore
from serieswatcher.config import Config
from serieswatcher.thetvdb import TheTVDB
class MakeSearch(QtCore.QObject):
searchFinished = QtCore.pyqtSignal(list)
def __init__(self, userInput):
super(MakeSearch, self).__init__()
self._userInput = us... | lightcode/SeriesWatcher | serieswatcher/serieswatcher/tasks/makesearch.py | Python | mit | 611 |
import logging
import json
from googleapiclient.discovery import build
logger = logging.getLogger(__name__)
class GoogleImageSearchService:
DEFAULT_SEARCH_FIELDS = 'items(fileFormat,image(byteSize,height,width),labels,link,mime,snippet,title),queries,searchInformation(searchTime,totalResults)'
DEFAULT_PAGE_... | kakkoyun/image_searcher | google_image_search_service.py | Python | mit | 2,223 |
#! /usr/bin/env python
"""
Create symbolic links of yersinia and anthracis in a new folder.
sys.argv[1]: data/pathogens-to-samples.txt
sys.argv[2]: data/runs-to-samples.txt
mkdir sra-pathogens
mkdir sra-pathogens/anthracis
mkdir sra-pathogens/yersinia
"""
import os
import errno
import glob
import sys
def mkdir(dire... | Read-Lab-Confederation/nyc-subway-anthrax-study | data/01-accessing-data-and-controls/map-pathogens.py | Python | mit | 1,850 |
import torch.nn as nn
import torch.optim as optim
from ptutils.model import Model
from ptutils.model.net import MNIST
from ptutils.contrib.datasource import mnist
from ptutils.datastore import MongoDatastore
from ptutils.coordinator.trainer import Trainer
class MNISTModel(Model):
def __init__(self, *args, **kwa... | alexandonian/ptutils | examples/mnist.py | Python | mit | 1,580 |
from collections import Counter
import numpy as np
def calculate_pmf(y):
"""
calculate the probability mass function given sample data.
"""
assert(len(y.shape) == 1)
# values = np.unique(y)
counter = Counter(y)
for k, v in counter.items():
counter[k] = v / len(y)
return counter
... | Alexoner/skynet | skynet/metrics/__init__.py | Python | mit | 2,038 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Sync's doctype and docfields from txt files to database
perms will get synced only if none exist
"""
import frappe
import os, sys
from frappe.modules.import_file import i... | cadencewatches/frappe | frappe/model/sync.py | Python | mit | 1,785 |
import functools
try:
unicode_str = unicode
except NameError:
unicode_str = str
try:
memoryview
except NameError:
memoryview = bytes
def metaclass(mcs):
def _decorator(cls):
attrs = dict(vars(cls))
try:
if isinstance(cls.__slots__, str):
slots = (cls.__... | renskiy/marnadi | marnadi/utils/__init__.py | Python | mit | 1,859 |
from ConfigParser import SafeConfigParser
class Config():
def __init__(self, path):
self.config = SafeConfigParser()
self.config.read(path)
def get_aws_keys(self):
key = self.config.get('aws', 'key')
secret_key = self.config.get('aws', 'secret_key')
return {'key': key,
... | hirokikana/s3-encfs-fuse | s3encfs/config.py | Python | mit | 548 |
try:
import ujson as json
except ImportError:
import json
import falcon
from falcon_dbapi.exceptions import ParamException
class BaseResource(object):
"""
Base resource class that you would probably want to use to extend all of your other resources
"""
def __init__(self, objects_class):
... | Opentopic/falcon-api | falcon_dbapi/resources/base.py | Python | mit | 16,078 |
import os.path
# Don't write any files, just create and discard content?
DRY_RUN = False
# Just get one?
SINGLE_TOPIC = False
# output directory
PATH_PREFIX = "output" + os.path.sep
# MySQL table prefix
TABLE_PREFIX = "forumgr_"
# how to determine internal links
def isInternalLink( url ):
return u"darth-arth.de" i... | mrwonko/phpbb2_to_html | phpbb2_to_html/config.py | Python | mit | 326 |
#!/usr/bin/python
# encoding: utf-8
import sys
import re
from workflow import Workflow, web
import sqlite3
import urllib2
import json
import difflib
__version__ = "0.3"
log = None
def rest(url):
base = "http://api.wormbase.org/rest/field/"
req = urllib2.Request(base + url)
req.add_header("Content-Type",... | danielecook/wormbase-alfred | query_wb.py | Python | mit | 5,156 |
#!/usr/bin/env python
import sys
from optparse import OptionParser
from pypipeline import scrape
from pypipeline.scrape import Scraper
if __name__ == "__main__":
usage = "%prog [top_dir...]"
parser = OptionParser(usage=usage)
scrape.add_options(parser)
(options, args) = parser.parse_args(sys.argv)
... | mgormley/pypipeline | scripts/scrape_exps.py | Python | mit | 486 |
NODE_GROUP_TYPE_CPU = "cpu"
NODE_GROUP_TYPE_GPU = "gpu"
NODE_GROUP_TYPE_SYSTEM = "system"
ALL_NODE_GROUP_TYPES = {
NODE_GROUP_TYPE_CPU,
NODE_GROUP_TYPE_GPU,
NODE_GROUP_TYPE_SYSTEM,
}
| sigopt/sigopt-python | sigopt/orchestrate/node_groups.py | Python | mit | 190 |
from __future__ import unicode_literals
__version__ = "5.0.0-beta"
| indictranstech/internal-frappe | frappe/__version__.py | Python | mit | 67 |
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from django.db.models import ImageField, signals
from django.dispatch import dispatcher
import os
def get_image_path(instance, filename):
return os.path.join(str(instance.name), filename)
class Location(MPTTModel):
name = models.CharF... | Reinaldowijaya/explorind | explorind_project/locations/models.py | Python | mit | 960 |
from django.conf.urls import patterns, url
from premises.views import (ContentionDetailView, HomeView,
ArgumentCreationView, PremiseCreationView,
PremiseDeleteView, ContentionJsonView,
PremiseEditView, ArgumentUpdateView,
... | Arthur2e5/arguman.org | web/premises/urls.py | Python | mit | 3,336 |
HTTP_CODE_OK = 200
HTTP_FORBIDDEN = 403
HTTP_TOO_MANY_REQUESTS = 429
BIZ_CODE_OK = 0
URL_PREFIX = "https://api.housecanary.com"
DEFAULT_VERSION = "v2"
| housecanary/hc-api-python | housecanary/constants.py | Python | mit | 153 |
# -*- coding: utf-8 -*-
"""
Datebook year views
"""
import datetime
import calendar
from django.views import generic
from braces.views import LoginRequiredMixin
from datebook.mixins import DateKwargsMixin
class DatebookYearView(LoginRequiredMixin, DateKwargsMixin, generic.TemplateView):
"""
Datebook year vi... | sveetch/django-datebook | datebook/views/year.py | Python | mit | 1,523 |
"""Module responsible for accessing the Run data in the FileStore backend."""
import datetime
import json
import os
from sacredboard.app.data.filestorage.filestorecursor import FileStoreCursor
from sacredboard.app.data.rundao import RunDAO
class FileStoreRunDAO(RunDAO):
"""Implements the Data Access Object for F... | chovanecm/sacredboard | sacredboard/app/data/filestorage/rundao.py | Python | mit | 3,187 |
#pvprograms.weebly.com
#Say 100
import http.client
data = "token: Q37PK3OVsjXJGSEWjQ8ANjc5\n"
conn = http.client.HTTPConnection("codeabbey.sourceforge.net")
conn.request("POST", "/say-100.php", data)
response = conn.getresponse()
#print(str(response.status) + " " + response.reason)
test = response.read()
print(test... | paolo215/problems | PY/Say 100.py | Python | mit | 637 |
"""
Copyright (c) 2013 Wei-Cheng Pan <legnaleurc@gmail.com>
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... | legnaleurc/kczzz | util.sikuli/util.py | Python | mit | 1,841 |
import struct
import socket
from time import sleep
class Client:
def __init__(self, host, port):
self.host = host
self.port = port
self.connection = None
self.response = None
def connect(self):
data = 'hello'
message = struct.pack('>i', len(data)) + str.encode(data)
self.connection = socket.socket(... | amol9/mayloop | mayloop/test/mock_client.py | Python | mit | 604 |
"""tests for lineage.py"""
# pylint: disable=missing-function-docstring, protected-access
from unittest.mock import MagicMock, patch
import pytest
from ncbitax2lin import lineage
@patch("multiprocessing.cpu_count", return_value=999, autospec=True)
def test__calc_num_procs(mock_cpu_count: MagicMock) -> None:
ac... | zyxue/ncbitax2lin | tests/test_lineage.py | Python | mit | 919 |
"""
Revision ID: 0193_add_ft_billing_timestamps
Revises: 0192_drop_provider_statistics
Create Date: 2018-05-22 10:23:21.937262
"""
from alembic import op
import sqlalchemy as sa
revision = '0193_add_ft_billing_timestamps'
down_revision = '0192_drop_provider_statistics'
def upgrade():
op.add_column('ft_billing... | alphagov/notifications-api | migrations/versions/0193_add_ft_billing_timestamps.py | Python | mit | 578 |
import logging
from protorpc import remote
from protorpc.wsgi import service
from tbans.models.service.messages import TBANSResponse, PingRequest, VerificationRequest, VerificationResponse
package = 'tbans'
class TBANSService(remote.Service):
""" The Blue Alliance Notification Service.... Service """
def... | jaredhasenklein/the-blue-alliance | tbans/tbans_service.py | Python | mit | 3,719 |
# -*- coding: utf-8 -*-
""" Utilities """
super_entity = s3mgr.model.super_entity
super_link = s3mgr.model.super_link
super_key = s3mgr.model.super_key
s3_action_buttons = s3base.S3CRUD.action_buttons
# -----------------------------------------------------------------------------
def s3_register_validation():
""... | flavour/helios | models/00_utils.py | Python | mit | 25,333 |
import math
import fvh2, fvh
import supercircle
masterCircleSet=set()
circlecalled = 0
checkcirclescalled = 0
MINOFFSET=5
class Circle():
def __init__(self,x,y,r,lm=None, keep=True):
global circlecalled
circlecalled+=1
self.keep = keep
self.center=(x,y)
self.radius=r
self.checkStr... | jeremiahmarks/dangerzone | scripts/python/turtleRelated/circleint.py | Python | mit | 34,847 |
#!/usr/bin/env python
import os
import json
import requests
import time
import sys
from jwcrypto import jwk, jws as cryptoJWS, jwe
from jwcrypto.common import json_encode, json_decode
from jwcrypto.common import base64url_decode, base64url_encode
from jose import jws
from hyperwallet.exceptions import HyperwalletExc... | hyperwallet/python-sdk | hyperwallet/utils/encryption.py | Python | mit | 6,786 |
from __future__ import division
import numpy as np
__author__ = "Eric Chiang"
__email__ = "eric[at]yhathq.com"
"""
Measurements inspired by Philip Tetlock's "Expert Political Judgment"
Equations take from Yaniv, Yates, & Smith (1991):
"Measures of Descrimination Skill in Probabilistic Judgement"
"""
def calib... | steinam/teacher | jup_notebooks/data-science-ipython-notebooks-master/analyses/churn_measurements.py | Python | mit | 2,795 |
import _plotly_utils.basevalidators
class BordercolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="bordercolorsrc", parent_name="cone.hoverlabel", **kwargs
):
super(BordercolorsrcValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/cone/hoverlabel/_bordercolorsrc.py | Python | mit | 436 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2009 Benoit Chesneau <benoitc@e-engura.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | adamlofts/couchdb-requests | couchdbreq/ext/django/schema.py | Python | mit | 7,084 |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
athlete = Table('athlete', pre_meta,
Column('id', INTEGER, primary_key=True, nullable=False),
Column('name_first', VARCHAR(length=64)),
Column('name_last', VARCHAR(length=64)),
... | ericgarig/runner_tracker | db_repository/versions/013_migration.py | Python | mit | 2,906 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pronto_praise.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensu... | prontotools/pronto-praise | pronto_praise/manage.py | Python | mit | 817 |
from django import forms
from django.forms import ModelForm
from budget.models import Account, AccountType
class AccountForm(ModelForm):
class Meta:
model = Account
account_type = forms.ModelChoiceField(queryset=AccountType.objects.all())
fields = [
'name',
'... | tom08/BudgetTracker | budget/forms.py | Python | mit | 349 |
import hmac
import hashlib
import os
from rest_framework import permissions
from rest_framework.exceptions import NotFound
from .api import get_repo_permissions
from builder.models import Site
from core.exceptions import BadRequest
class GithubOnly(permissions.BasePermission):
""" Security Check - Certain API e... | istrategylabs/franklin-api | franklin/github/permissions.py | Python | mit | 2,864 |