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 |
|---|---|---|---|---|---|
import json
import click
from tabulate import tabulate
@click.command('notes', short_help='List notes')
@click.option('--alert-id', '-i', metavar='UUID', help='alert IDs (can use short 8-char id)')
@click.pass_obj
def cli(obj, alert_id):
"""List notes."""
client = obj['client']
if alert_id:
if ob... | alerta/python-alerta | alertaclient/commands/cmd_notes.py | Python | mit | 1,034 |
from os.path import isdir
def conda_is_installed(conda_directory_path):
return all(
(isdir("{}/{}".format(conda_directory_path, name)) for name in ("bin", "lib"))
)
| UCSD-CCAL/ccal | ccal/conda_is_installed.py | Python | mit | 184 |
import requests
import time
from selenium import webdriver
# file path
import os
BASE_DIR = os.path.dirname(__file__)
phjs_path = os.path.join(BASE_DIR,'login.phjs.js')
print ('*******'+phjs_path+'*******')
driver = webdriver.PhantomJS(executable_path=phjs_path)
driver.get('http://autoinsights.autodmp.com/user/login')... | Veblin/pythonDemo | spiders/logins.py | Python | mit | 401 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
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, includ... | FrUh/userpass-manager | Main.py | Python | mit | 3,835 |
import copy
import exceptions
import json
import math
import time
try:
import RPi.GPIO as gpio
except:
gpio = None
from twisted.application import service
from twisted.internet import task, reactor, defer
from twisted.python import log
from twisted.python.filepath import FilePath
from twisted.web import serve... | calston/pitool | pitool/service.py | Python | mit | 6,191 |
from django.template import Context, loader
from pokemon.models import Pokemon
from django.http import HttpResponse
from django.http import Http404
def index(request):
Pokemons = Pokemon.objects.all().order_by('id_pokemon')
t = loader.get_template('pokemon/index.html')
c = Context({
'Pokemons': Pok... | pgrimaud/django-pokedex | pokemon/views.py | Python | mit | 616 |
from aiohttp import web
import json
from foo import storage
async def index(request):
bars = await storage.get_some_bar()
bars = {
"id": bars[0],
"name": bars[1],
"created_at": bars[2].isoformat(),
}
return web.Response(body=json.dumps(bars).encode())
| Unit03/aio_web_sandbox | foo/views.py | Python | mit | 295 |
# -*- coding: utf-8 -*-
__author__ = 'study_sun'
from lxml import etree
from entity import *
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class IndexParser(object):
def parse_index_list(self, index_list_content):
# 编码还是有问题哦
index_list_content = index_list_content.encode('ISO-8859-1').de... | s6530085/FundSpider | index/parser.py | Python | mit | 1,325 |
# 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/maintenance/azure-mgmt-maintenance/azure/mgmt/maintenance/operations/_updates_operations.py | Python | mit | 10,836 |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... | imayhaveborkedit/discord.py | discord/client.py | Python | mit | 44,891 |
#!/usr/bin/python
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy #flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy_utils import ScalarListType
db = SQLAlchemy()
login_manager = LoginManager()
# User
# email, password, authenticated (once user logins)
class User(db.Model):
... | adrisj7/scouter-app | util/database.py | Python | mit | 1,742 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import pho
requisites = []
setup(
name='mpho',
version=pho.__version__,
description='PytHon utility for Organizing tasks',
scripts=['scripts/pho'],
long_d... | hvnsweeting/pho | setup.py | Python | mit | 637 |
# Django settings for servicezen project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dat... | ograycode/ServiceZen | servicezen/settings.py | Python | mit | 5,916 |
import unittest
from katas.beta.number_to_bytes import to_bytes
class NumberToBytesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_bytes(0), ['00000000'])
def test_equals_2(self):
self.assertEqual(to_bytes(1), ['00000001'])
def test_equals_3(self):
self.a... | the-zebulan/CodeWars | tests/beta_tests/test_number_to_bytes.py | Python | mit | 827 |
"""Check for definitions and usage happening on the same line."""
#pylint: disable=missing-docstring,multiple-statements,no-absolute-import,parameter-unpacking,wrong-import-position,unnecessary-comprehension
from __future__ import print_function
print([index
for index in range(10)])
print((index
for inde... | ruchee/vimrc | vimfiles/bundle/vim-python/submodules/pylint/tests/functional/d/defined_and_used_on_same_line.py | Python | mit | 703 |
import xmlrpc.client
import sys, re, base64, gzip, os , io
# Autor Jan Hrivnak
# ISJ projekt
# Soubor: Aplikace.py
# spoustet s : export LC_ALL=cs_CZ.UTF-8;
class Aplikace:
def __init__(self):
self.IMDBid=0 #IMDB id filmu
self.subID=0 #ID zadanych titulku
self.nazevFilmu=""
self.aut... | ScOrPiOn9/FIT | ISJ/Projekt - automatické stahování titulků k filmům/Aplikace.py | Python | mit | 17,098 |
import functools
import os
import numpy as np
import pygmo as pg
from simulation import simulate, statistical
from solving import value_function_list
from util import constants as cs, param_type
class HumanCapitalSearchProblem(object):
def fitness(self, params_nparray, gradient_eval=False):
params_param... | mishpat/human-capital-search | humancapitalsearch.py | Python | mit | 4,080 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
from curl2share.config import log_file, log_level
loglevel = {'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARN,
'INFO': logging.INFO,
'DEBUG... | cuongnv23/curl2share | curl2share/__init__.py | Python | mit | 691 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
@p... | mozillazg/lark | lark/music/models.py | Python | mit | 1,119 |
import sys
if sys.version > '3':
PY3 = True
else:
PY3 = False
from .uarm import UArm, UArmConnectException
from .config import ua_dir, home_dir
from .util import get_uarm
from .version import __version__
| uArm-Developer/pyuarm | pyuarm/__init__.py | Python | mit | 215 |
#! /usr/bin/env python
import rospy
import sys
from time import sleep
import actionlib
import yaml
from random import randint
#from threading import Timer
import strands_tweets.msg
import image_branding.msg
from std_msgs.msg import String
from sensor_msgs.msg import Image
#from cv_bridge import CvBridge, CvBridge... | hawesie/strands_social | card_image_tweet/scripts/tweet_card.py | Python | mit | 2,961 |
from django import forms
class ImageUploadForm(forms.Form):
'''Image upload form.'''
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
| jr55662003/Diabetic-Retinopathy-website | website/diabetics/forms.py | Python | mit | 178 |
import os
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Bio.PDB as PDB
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklear... | Kortemme-Lab/protein_feature_analysis | ProteinFeatureAnalyzer/features/RamachandranFeature.py | Python | mit | 8,582 |
# Copyright (c) 2017 Jared Crapo, K0TFU
# serialization options http://stackoverflow.com/questions/2627555/how-to-deserialize-an-object-with-pyyaml-using-safe-load
import persistent
class Operator(persistent.Persistent):
"""Model class for a ham radio operator
Attributes
----------
callsign: st... | kotfu/netcontrol | netcontrol/operator.py | Python | mit | 642 |
#!/usr/bin/env python
# encoding: utf-8
'''
Created on Apr 8, 2013
@author: redw0lf
'''
import pygame, sys, os, random
from pygame.locals import *
class MenuItem (pygame.font.Font):
'''
The Menu Item should be derived from the pygame Font class
'''
def __init__(self, text, position, fontSize=55, anti... | hjorturlarsen/Kapall | menu.py | Python | mit | 5,750 |
in1 = """
[aaa]
a = 123
456
789
b =
321
654
987
c =
135
246
999
"""
in2 = """
[cmd]= ok
[cmd] << 40+2
x << 123*2
[cmd]
<<<
x = 42
y = 123
print(x,y)
... print ok
[data] =
1 2 3
4 5 6
7 8 9
[tsv]
head = no
cols = a b c
out >> tab
[insert] << tab
table = mydata
"""
in2 = """
[aaa] <<<
jest
... | mobarski/smash | test/test-parse2.py | Python | mit | 600 |
#http://pymotw.com/2/socket/multicast.html
import socket
import struct
import sys
multicast_group = '224.3.29.71'
server_address = ('', 10000)
# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock.bind(server_address)
# Tell the operating system to add the soc... | btbuxton/python-pomodoro | research/multi_recv.py | Python | mit | 864 |
from project.models.fields.Field import Field
from project.models.fields.exceptions import FieldValidException
THEME_MIN_LENGTH = 0
THEME_MAX_LENGTH = 128
class ThemeField(Field):
def __init__(self, theme):
self.set(theme)
def set(self, theme):
if x = chain_of_conditions()
raise ... | AbramovVitaliy/Abramov-RIS-13 | lab4_5_6/project/models/fields/ThemeField.py | Python | mit | 734 |
import pytest
from cleo.exceptions import LogicException
from cleo.exceptions import ValueException
from cleo.io.inputs.option import Option
def test_create():
opt = Option("option")
assert "option" == opt.name
assert opt.shortcut is None
assert opt.is_flag()
assert not opt.accepts_value()
a... | sdispater/cleo | tests/io/inputs/test_option.py | Python | mit | 2,858 |
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
# Can't use the callable because the app registry is not ready yet.
# Really trusting users her... | jameshiew/dj-stripe | djstripe/migrations/0003_auto_20150128_0800.py | Python | mit | 948 |
#!/usr/bin/env python3
from chewing import userphrase
def main():
phrase = '內稽'
bopomofo = 'ㄋㄟˋ ㄐㄧ'
rtn = userphrase.remove(phrase, bopomofo)
print(rtn)
if __name__ == '__main__':
main()
| samwhelp/demo-libchewing | python/prototype/chewing_userphrase_remove/20-module/main.py | Python | mit | 211 |
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
from math import sqrt
def isPrimeNumber(number):
for divisor in xrange(3, int(sqrt(number))+1, 2):
if number % divisor == 0:
return False
return True
def do(evilNumber, p... | hickeroar/project-euler | 000/solution003.py | Python | mit | 686 |
# -*- coding: utf8 -*-
from typing import List, Tuple
import numpy as np
from yarll.functionapproximation.function_approximator import FunctionApproximator
class TileCoding(FunctionApproximator):
"""Map states to tiles"""
def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_ti... | arnomoonens/DeepRL | yarll/functionapproximation/tile_coding.py | Python | mit | 2,943 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import calendar
import json
import locale
import re
import requests
from bs4 import BeautifulSoup
# Use German month names
locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
URL = "http://www.theater-chemnitz.de/spielplan/repertoire"
BASE_URL = "http://www.t... | CodeforChemnitz/TheaterWecker | scraper/app.py | Python | mit | 3,322 |
import unittest
import StringIO
from packetsexample import PacketsExample
from prers import RdBit
class TestRdBit(unittest.TestCase):
def reinit(self):
self.__stringbuffer1 = StringIO.StringIO()
self.__p1 = RdBit(self.__stringbuffer1)
def data_example(self):
data = PacketsExample()
... | niclabs/ratadns-filters | tests/test_rdbit.py | Python | mit | 925 |
#!/usr/bin/env python
import pprint
import json
import subprocess
root_dir = subprocess.check_output([
'git', 'rev-parse', '--show-toplevel'
]).decode().strip()
def path(s):
return "{}/{}".format(root_dir, s)
# Create the output directory
subprocess.call(['mkdir', '-p', path('ec2instances/info')])
# M... | powdahound/ec2instances.info | scripts/package.py | Python | mit | 1,037 |
import rdflib
from rdflib.plugin import register, Serializer, Parser
from rdflib.namespace import DCTERMS, VOID, RDF, XSD
from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef
graph_dump = Graph()
graph_dump.parse('observed_withCategories.ttl', format="turtle")
graph = Graph()
query = """SELECT * WHERE {... | jerdeb/lodqa | LODQA/generateCategoriesForLuzzu.py | Python | mit | 1,243 |
__all__ = ["engine", "graphics", "input", "data", "rrt", "profiler"]
| JoeOsborn/hyped | player/__init__.py | Python | mit | 69 |
import pytest
from mock import patch, call, Mock, MagicMock
from blt.tools import aws
@pytest.fixture
def cmds():
config = {
"aws": {
"AWS_ACCESS_KEY_ID": "JLKSNLBNLSKDFJWOEI"
, "AWS_SECRET_ACCESS_KEY": "JFvnwoaifeIOJFnegoiwfaqEF"
, "AWS_BUCKET_NAME": "matter-developers"
... | dencold/blt | blt/test/test_aws.py | Python | mit | 2,431 |
# -*- coding: utf-8 -*-
import api | vollov/build-tracker | src/api/__init__.py | Python | mit | 34 |
import recurly
class RecurlyError(Exception):
@classmethod
def error_from_status(cls, status):
return recurly.errors.ERROR_MAP.get(status, "")
class ApiError(RecurlyError):
def __init__(self, message, error):
super(ApiError, self).__init__(message)
self.error = error
class Netw... | recurly/recurly-client-python | recurly/base_errors.py | Python | mit | 353 |
#!/usr/bin/env python
# Standard library modules
import ConfigParser
import argparse
import os
import textwrap
def create_config(configuration):
""" Function used to create the configuration file
if it does not exist in the program's path.
It returns a ConfigParser object
"""
configuration.add_s... | vickz84259/XKCD | scripts/argument.py | Python | mit | 2,906 |
from __future__ import print_function
import io
import os.path
import re
from distutils.text_file import TextFile
from setuptools import find_packages, setup
home = os.path.abspath(os.path.dirname(__file__))
missing = object()
def read_description(*files, **kwargs):
encoding = kwargs.get('encodin... | by46/flask-kits | setup.py | Python | mit | 2,009 |
from grano.core import db, url_for
from grano.model.util import make_token
from grano.model.common import IntBase
class Account(db.Model, IntBase):
__tablename__ = 'grano_account'
github_id = db.Column(db.Unicode)
twitter_id = db.Column(db.Unicode)
facebook_id = db.Column(db.Unicode)
full_name =... | clkao/grano | grano/model/account.py | Python | mit | 2,682 |
"""
Global configuration for the problem settings
"""
import numpy as np
from scipy import stats
horizon = 300
runs = 40
DefaultConfiguration = {
"price_buy" : [1.2,2.1,3.3],
"price_sell" : [1,2,3],
"price_probabilities" : np.array([[0.8, 0.1, 0.1],[0.1, 0.8, 0.1],[0.1, 0.1, 0.8]]),
"initial_capacity... | marekpetrik/RAAM | raam/examples/inventory/configuration.py | Python | mit | 5,606 |
import OpenPNM
import scipy as sp
class GenericNetworkTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[10, 10, 10])
def teardown_class(self):
ctrl = OpenPNM.Base.Controller()
ctrl.clear()
def test_find_connected_pores_numeric_not_flattend(self):
a = se... | amdouglas/OpenPNM | test/unit/Network/GenericNetworkTest.py | Python | mit | 8,477 |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('remotestatus.views',
url(r'^remote-box/(?P<remote_box_id>[0-9]+)/$', 'remote_box_detail', name='rs-remote-box-detail'),
url(r'^(?P<call_round_id>[0-9]+)/$', 'dashboard', name='rs-dashboard'),
url(r'^$', 'dashboard', name='rs-dashbo... | cooncesean/remotestatus | remotestatus/urls.py | Python | mit | 328 |
# -*- coding:Utf-8 -*-
#####################################################################
#This file is part of RGPA.
#Foobar is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, ... | pylayers/pylayers | pylayers/location/geometric/util/boxn.py | Python | mit | 27,884 |
"""
This module models the host variant call object.
"""
import json
import logging
import os
import string
from cutlass.iHMPSession import iHMPSession
from cutlass.Base import Base
from cutlass.aspera import aspera
from cutlass.Util import *
# pylint: disable=W0703, C1801
# Create a module logger named after the mo... | carze/cutlass | cutlass/HostVariantCall.py | Python | mit | 23,915 |
import json
import re
import requests
from_cmdline = False
try:
__file__
from_cmdline = True
except NameError:
pass
if not from_cmdline:
import vim
METHOD_REGEX = re.compile('^(GET|POST|DELETE|PUT|HEAD|OPTIONS|PATCH) (.*)$')
HEADER_REGEX = re.compile('^([^()<>@,;:\<>/\[\]?={}]+):\\s*(.*)$')
VAR_REGEX... | aquach/vim-http-client | plugin/http_client.py | Python | mit | 8,172 |
#!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, version=None):
if version:
json_file = 'pypi-%s-%s.json' % (package_name, version)
else:
... | nezhar/updatable | test/test_update_license.py | Python | mit | 2,049 |
import scipy
import numpy
import matplotlib.pyplot as pyplot
import pyfits
import VLTTools
ciao = VLTTools.VLTConnection(simulate=False)
ciao.get_InteractionMatrices()
ciao.dumpCommandMatrix(nFiltModes=10)
print "This is where we will Compute the Modal Basis from the IMs"
| soylentdeen/CIAO-commissioning-tools | sandbox/dumpModalBasis.py | Python | mit | 275 |
from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... | ntucker/django-user-accounts | account/auth_backends.py | Python | mit | 2,826 |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... | CalebBell/thermo | thermo/utils/t_dependent_property.py | Python | mit | 202,501 |
#!/usr/bin/env python3
import sys
import os
import path_utils
import git_lib
import svn_lib
REPO_TYPE_GIT_BARE="git/bare"
REPO_TYPE_GIT_STD="git/std"
REPO_TYPE_GIT_SUB="git/sub"
REPO_TYPE_SVN="svn"
REPO_TYPES = [REPO_TYPE_GIT_BARE, REPO_TYPE_GIT_STD, REPO_TYPE_GIT_SUB, REPO_TYPE_SVN]
def detect_repo_type(path):
... | mvendra/mvtools | detect_repo_type.py | Python | mit | 1,152 |
from cookiecutter.main import cookiecutter
import click
import requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()... | SarahJaine/mo-cli | mo.py | Python | mit | 1,542 |
def calc(x):
ret = 0
for i in range(N):
ret += min(M, x // (i+1))
return ret
N, M, K = map(int, input().split())
N, M = sorted([N, M])
low, high = 0, K+1
while high - low > 1:
mid = (low + high) // 2
if calc(mid) < K:
low = mid
else:
high = mid
print(high)
| knuu/competitive-programming | codeforces/cdf256_2d.py | Python | mit | 308 |
'''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to chec... | PythonProgramming/Python-3-basics-series | 9. if elif else.py | Python | mit | 972 |
import csv
import sys
from models import *
from datetime import datetime
import codecs
import json
# from models import Attorney, Organization
from flask_mail import Message
def load_attorneys_from_csv(filename):
with codecs.open(filename, mode='rb', encoding='utf-8') as csvfile:
attorneys = [row for row ... | mitzvotech/honorroll | app/utils.py | Python | mit | 2,178 |
# coding=utf-8
import time
import datetime
__author__ = 'JIE'
#! /usr/bin/env python
#coding=utf-8
from tornado.tcpserver import TCPServer
from tornado.ioloop import IOLoop
class Connection(object):
clients = set()
def __init__(self, stream, address):
Connection.clients.add(self)
self._stream... | stableShip/tornado_chatRoom | TcpServer.py | Python | mit | 1,361 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-25 23:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('journal', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | diegojromerolopez/djanban | src/djanban/apps/journal/migrations/0002_auto_20160926_0155.py | Python | mit | 819 |
from __future__ import absolute_import, division, print_function
from trakt.core.helpers import from_iso8601_datetime, to_iso8601_datetime
from hamcrest import assert_that, equal_to
import pytest
try:
import arrow
except ImportError:
arrow = None
def test_datetime_conversion():
if arrow is None:
... | fuzeman/trakt.py | tests/test_helpers.py | Python | mit | 519 |
#!/usr/bin/env python
import pantilthat
import time
import sys
import math
import servo_ranges
def tick():
time.sleep(0.010)
class Shelf(object):
def __init__(self, num, start, end, tilt):
self.count = num; # num of records
self.pan_start = start; # degress +
self.pan_end = end; # degrees -
self.tilt_pos =... | valentingalea/vinyl-shelf-finder | pantilthat/finder.py | Python | mit | 2,511 |
#!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class MUTCDGetterError(Exception):
pass
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default... | radicalbiscuit/mutcd-getter | mutcd-getter.py | Python | mit | 5,919 |
import os
from urllib import urlretrieve
import pandas as pd
FREEMONT_URL = "https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
def get_freemont_data(filename="Freemont.csv", url=FREEMONT_URL,
force_download=False) :
"""Download and cache the Freemont data
Param... | betogulliver/JupyterWorkflow | jupyterworkflow/data.py | Python | mit | 1,112 |
import random, time, pygame, sys
from pygame.locals import *
FPS = 25
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
BOXSIZE = 20
BOARDWIDTH = 10
BOARDHEIGHT = 20
BLANK = '.'
MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.1
XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2)
TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) -... | saintdragon2/python-3-lecture-2015 | civil_mid_final/알았조/tetris a.py | Python | mit | 15,222 |
"""
Add simple, flexible caching layer.
Uses `dogpile caching http://dogpilecache.readthedocs.org/en/latest/index.html`_.
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '9/26/15'
from dogpile.cache import make_region
def my_key_generator(namespace, fn, **kw):
fname = fn.__name__
def generate_ke... | realmarcin/data_api | lib/doekbase/data_api/cache.py | Python | mit | 847 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017-05-28 10:13:14
# @Author : Sizheree (sizheree.github.io)
# @Link :
# @Version : $1.0$
import logging
import time
import numpy as np
import matplotlib.pyplot as plt
# print(__package__, __file__)
logging.basicConfig(level=logging.INFO)
log = logging.... | earlybackhome/easy-expression | modules/DL/maxSim.py | Python | mit | 4,470 |
import cupy as cp
def read_code(code_filename, params):
with open(code_filename, 'r') as f:
code = f.read()
for k, v in params.items():
code = '#define ' + k + ' ' + str(v) + '\n' + code
return code
def benchmark(func, args, n_run):
times = []
for _ in range(n_run):
start... | cupy/cupy | examples/gemm/utils.py | Python | mit | 551 |
"""Tests for the models of the currency_history app."""
from django.test import TestCase
from mixer.backend.django import mixer
class CurrencyTestCase(TestCase):
"""Tests for the ``Currency`` model."""
def setUp(self):
self.currency = mixer.blend('currency_history.Currency')
def test_model(self)... | bitmazk/django-currency-history | currency_history/tests/models_tests.py | Python | mit | 949 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import os
import codecs
import shutil
from termcolor import colored
from jinja2 import Template
from studio.launch import ROOT_PATH
from jinja2 import Environment, FileSystemLoader
JDIR = os.path.join(ROOT_PATH, 'ji... | qisanstudio/qstudio-launch | src/studio/launch/commands/contrib.py | Python | mit | 2,178 |
# -*- coding: utf-8 -*-
from celery import Celery
from server import config
""" Celery configuration module.
"""
def make_celery(app):
""" Flask integration with celery. Taken from
http://flask.pocoo.org/docs/0.12/patterns/celery/
"""
celery = Celery(app.import_name, backend=config.CELERY_RESULT_BA... | abhishekpathak/recommendation-system | recommender/server/settings/celery_conf.py | Python | mit | 695 |
# encoding: utf-8
#
# Copyright (C) 2013 midnightBITS/Marcin Zdun
#
# 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, c... | mzdun/uml-seq | src/uml/sequence/_anchor.py | Python | mit | 1,902 |
################################################################################
# Copyright (C) 2013-2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Unit tests for `dot` module.
"""
import unittest
import nu... | bayespy/bayespy | bayespy/inference/vmp/nodes/tests/test_dot.py | Python | mit | 34,668 |
class Command(object):
def __init__(self, keyword, args=None):
self.keyword = keyword
self.args = args
| Le-Bot/cerebro | cerebro/neuron/entities.py | Python | mit | 123 |
from collections import defaultdict
import logging
import math
logger = logging.getLogger('lobster.algo')
class Algo(object):
"""A task creation algorithm
Attempts to be fair when creating tasks by making sure that tasks are
created evenly for every category and every workflow in each category
bas... | matz-e/lobster | lobster/core/create.py | Python | mit | 5,617 |
import numpy as np
import pandas as pd
import datetime
class Tariffs :
def __init__(self, scheme_name, retail_tariff_data_path, duos_data_path, tuos_data_path, nuos_data_path, ui_tariff_data_path):
self.scheme_name = scheme_name
self.retail_tariff_data_path = retail_tariff_data_path
self.du... | lukasmarshall/embedded-network-model | tariffs.py | Python | mit | 22,618 |
# -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget):
""... | lexrupy/gmate-editor | GMATE/status_position.py | Python | mit | 2,729 |
from benchmark import __version__
def test_version():
assert __version__ == '0.1.0'
| kkirstein/proglang-playground | Python/benchmark/tests/test_benchmark.py | Python | mit | 90 |
# -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2012 Yüce Tekol
#
# 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 ... | yuce/pyswip | tests/test_prolog.py | Python | mit | 4,048 |
#!/usr/bin/env python
import ctypes
import json
import os
from binascii import hexlify, unhexlify
import pytest
from pyasn1.codec.ber.decoder import decode as ber_decode
from pyasn1.codec.der.decoder import decode as der_decode
from pyasn1.codec.der.encoder import encode as der_encode
from pyasn1.type import namedtype... | trezor/trezor-crypto | tests/test_wycheproof.py | Python | mit | 21,271 |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.uic import *
import os
class ConnectorsInfoWnd(QDialog):
def __init__(self, treeModel, genus):
super(ConnectorsInfoWnd, self).__init__()
self.genus = genus
self.treeModel = treeModel
dirname, filename = os.path.sp... | go2net/PythonBlocks | components/ConnectorsInfoWnd.py | Python | mit | 5,295 |
def packages_path():
return 'XXX'
| SublimeText/SublimeHg | tests/sublime.py | Python | mit | 40 |
"""
mountains
~~~~~~~~~
Takes a CSV file either via local or HTTP retrieval and outputs information about the mountains according to spec.
Originally a programming skills check for a particular position. I've get it updated to current python versions
as well as packaging and testing methodologies.
:copyright: 2016... | c17r/catalyst | src/mountains/__init__.py | Python | mit | 465 |
from django.conf.urls.defaults import patterns, url
from reviewboard_persona.extension import RBPersona
urlpatterns = patterns('reviewboard_persona.views',
url(r'^$', 'configure'),
)
| smacleod/reviewboard-persona | reviewboard_persona/admin_urls.py | Python | mit | 190 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
def datestring_convert(s):
"""Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = ... | skitazaki/python-school-ja | src/datestring_convert.py | Python | mit | 783 |
import setpath
import functions
import json
registered=True
# Filters the input table using the filters argument
# For example
# lala table :
# [1|1[2|tear-prod-rate[3|normal[4|?
# --- [0|Column names ---
# [1|no [2|colname [3|val [4|nextnode
# var 'filters' from select tabletojson(colname,val, "colname,val") from lal... | madgik/exareme | Exareme-Docker/src/exareme/exareme-tools/madis/src/functionslocal/vtable/filtertable.py | Python | mit | 3,582 |
# -*- coding: utf-8 -*-
import os
import time
import util
import urllib, urllib2
import base64
from datetime import datetime
import env
from glob import glob
END_POINT = env.END_POINT
BASE_DIR = env.BASE_DIR
STORAGE_URL = env.STORAGE_URL
def get_latest_file(dirname):
dest = os.path.join(dirnam... | spin13/python_maclib | fsevent_dog.py | Python | mit | 1,485 |
# -*- coding: utf-8 -*-
import requests
URL = 'http://natas18.natas.labs.overthewire.org/'
AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP')
def get_password():
param = { 'username': 'admin', 'password': 'hoge' }
for i in range(640):
cookies = { 'PHPSESSID': str(i) }
r = requests.post(URL... | koki-sato/capture-the-flag | write-ups/OverTheWire/Natas/solver/natas18.py | Python | mit | 700 |
import mock
from nose.tools import assert_equals, raises
from scrapebrewtoad import Brewtoad
user = "me"
password = "password"
session = mock.Mock()
session.post.return_value.url = "http://dummyurl.com/blah/12345/"
@mock.patch("pyquery.PyQuery")
def test_init_stores_params_and_calls_login(PyQuery):
toad = Brewt... | oliverdrake/brewtoad-scraper | tests.py | Python | mit | 2,584 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import datetime
import django
sys.path.append('/var/django/tippspiel')
django.setup()
from tipps.models import Spiel, Mannschaft, Runde
spiele = """
V1 | 2016-06-10, 21:00 | fra | rou
V1 | 2016-06-11, 15:00 | alb | sui
V1 | 2016-06-11, 18:00 | wal | svk
V1 | 2016... | ugoertz/tippspiel | tippspiel/tools/vorrunde.py | Python | mit | 2,049 |
import sys
import pytest
from file_manip_toolkit.eswap import cli
# todo - parameterize
def test_parse_args():
args = cli.parse_args(['test.py', 'filetemp', '-o', 'here'])
assert args.file
assert args.format
assert args.output
with pytest.raises(AssertionError):
assert args.verbose
@pytes... | goosechooser/file-manip-toolkit | tests/eswap_cli_test.py | Python | mit | 794 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# called from wnf.py
# lib/wnf.py --install [rootpassword] [dbname] [source]
from __future__ import unicode_literals
import os, json, sys, subprocess, shutil
import frappe
import frappe.database
import getpass
import ... | elba7r/frameworking | frappe/installer.py | Python | mit | 12,017 |
# vim: set fileencoding=utf-8 :
import unittest
import pyvips
from .helpers import PyvipsTester
class TestIofuncs(PyvipsTester):
# test the vips7 filename splitter ... this is very fragile and annoying
# code with lots of cases
def test_split7(self):
def split(path):
filename7 = pyvip... | kleisauke/pyvips | pyvips/tests/test_iofuncs.py | Python | mit | 2,511 |
import subprocess
import sys
import string
import os
def start_carbon_relay_instance(name):
path = os.path.realpath(__file__)
subprocess.call(["python", "{0}/carbon-relay.py".format(os.path.dirname(path)), "--instance={0}".format(name), "start"])
def stop_carbon_relay_instance(name):
path = os.path.realpath(__fil... | yunstanford/GraphiteSetup | carbon_relay.py | Python | mit | 1,348 |
#!/usr/bin/env python2
# multi-regime.py
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:06:28 (jonah)>
# This is a library to plot and fit for omega(rho) variable. We choose
# omega so that we get the three distinct regimes for which we know
# the analytic solution with continuou... | Yurlungur/FLRW | MultiRegime.py | Python | mit | 2,168 |
#!/usr/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Tests for cheminformatics toolkit wrappers
"""
# ==============================... | open-forcefield-group/openforcefield | openff/toolkit/tests/test_toolkits.py | Python | mit | 163,747 |
import os
from flask import render_template, redirect, url_for, abort, flash
from flask.ext.login import login_required
from flask.ext.rq import get_queue
from wtforms.fields import SelectField
from wtforms.validators import (
Optional
)
from .. import db
from ..models import EditableHTML, Resource, ContactCatego... | hack4impact/maps4all | app/contact/views.py | Python | mit | 4,825 |
#!/usr/bin/env python
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum1, sum2, lb = 0, 0, min(nums)
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
for num in nums:
sum1 += ((nu... | eroicaleo/LearningPython | interview/leet/137_Single_Number_II.py | Python | mit | 1,076 |
"""Packets supported by the parser."""
from .eddystone import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \
EddystoneTLMFrame, EddystoneEIDFrame
from .ibeacon import IBeaconAdvertisement
from .estimote import EstimoteTelemetryFrameA, EstimoteTelemetryFrameB, EstimoteNearable... | citruz/beacontools | beacontools/packet_types/__init__.py | Python | mit | 427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.