repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
waveform80/lars | utils.py | #!/usr/bin/env python
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk>
# Copyright (c) 2013 Mime Consulting Ltd. <info@mimeconsulting.co.uk>
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softwar... |
JmPotato/Pomash | run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.options
import tornado.httpserver
from Pomash import Application
from tornado.options import define, options
define("port", default=8080, help="run on the given port for develop", type=int)
def main():
tornado.options.parse_comm... |
tropo/tropo-webapi-python | samples/itty_session_api.py | #!/usr/bin/env python
"""
Hello world script for Session API ( https://www.tropo.com/docs/webapi/sessionapi.htm )
Upon launch, it will trigger a message to be sent via Jabber to the addess specified in
'number'.
"""
# Sample application using the itty-bitty python web framework from:
# http://github.com/toastdriven/... |
log0ymxm/corgi | setup.py | #!/usr/bin/env python
from setuptools import setup
with open('VERSION', 'r') as f:
version = f.read()
setup(name='corgi',
version=version,
description='Python data and analysis tools',
author='Paul English',
author_email='paulnglsh@gmail.com',
url='https://github.com/log0ymxm/corgi'... |
treehopper-electronics/treehopper-sdk | Python/treehopper/libraries/io/adc/nau7802_registers.py | ### This file was auto-generated by RegisterGenerator. Any changes to it will be overwritten!
from treehopper.libraries.register_manager_adapter import RegisterManagerAdapter
from treehopper.libraries.register_manager import RegisterManager, Register, sign_extend
class Gains:
x1 = 0
x4 = 1
x2 = 2
x8 =... |
anderson1008/NOCulator | hring/src/Script/compute.py | #!/usr/bin/python
import sys
import os
import re
import fnmatch
import string
def cmp_ipc (insns_persrc, active_cycle):
ipc = []
for i,j in zip (insns_persrc, active_cycle):
ipc = ipc + [ round (float (i) / float(j),3)]
#print ipc
return ipc
# compute weighted speedup
def cmp_ws (ipc_alon... |
aequitas/munerator | munerator/context.py | """Add game and player context to events
Usage:
munerator [options] context
Options:
-v --verbose Verbose logging
--events-socket url ZMQ socket for raw events [default: tcp://127.0.0.1:9001]
--context-socket url ZMQ socket for context events [default: tcp://0.0.0.0:9002]
--rcon-socket url Z... |
lingxz/todoapp | migrations/versions/2d57d1c9b9da_.py | """empty message
Revision ID: 2d57d1c9b9da
Revises: None
Create Date: 2016-07-31 00:18:08.365221
"""
# revision identifiers, used by Alembic.
revision = '2d57d1c9b9da'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... |
yuuta-togashi/tcc_ufba | Codigo/main.py | import beaglebone_pru_adc as adc
import smbus
import time
import Adafruit_BBIO.GPIO as GPIO
from flask import Flask, render_template, request, jsonify
import threading
GPIO.setup("P8_6", GPIO.IN)
GPIO.setup("P8_7", GPIO.IN)
class captureThread(threading.Thread):
def __init__(self, numSamples_ = 10000... |
yyang179/ngta | tests/test_runner.py | # coding: utf-8
import time
import ngta
import threading
from ngta.assertions import assert_that
@ngta.skip('not ready')
def test_init():
pass
def test_state__setting_and_getting():
received = []
class Observer(ngta.TestRunner.BaseObserver):
def emit(self, data):
received.append(da... |
l33tdaima/l33tdaima | pr1048m/longest_str_chain.py | from typing import List
class Solution:
def longestStrChain(self, words: List[str]) -> int:
dp = dict()
for w in sorted(words, key=len):
dp[w] = max(dp.get(w[:i] + w[i + 1 :], 0) + 1 for i in range(len(w)))
return max(dp.values())
# TESTS
for words, expected in [
(["a", "... |
jamesabel/osnap | launchers/util.py |
import platform
def is_windows():
return platform.system().lower()[0] == 'w'
def is_mac():
# macOS/OSX reports 'Darwin'
return platform.system().lower()[0] == 'd'
def get_os_name():
if is_mac():
return 'mac'
elif is_windows():
return 'win'
else:
raise NotImplemente... |
mi-schi/php-code-checker | app/metric/pdepend.py | from app.configuration import get_value
from app.helper import output_start, php, output_error
def execute():
output_start('pdepend')
metric_dir = get_value('metric-dir')
scan_dir = get_value('project-dir')+get_value('scan-dir')
excludes = ','.join(get_value('exclude-dirs'))
if excludes != '':
... |
opieters/wcamera | src/motion_detector.py | #!/usr/bin/env python
# this code was inspired by this tutorial by Adrian Rosebrock:
# http://www.pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/
import time, datetime, json, cv2, warnings
import RPi.GPIO as GPIO
from argparse import ArgumentParser
from imu... |
jacobj10/CrackMyARS | lib/CrackMyARS/attacks/wiener_attack.py | from CrackMyARS.attacks.attack import Attack
class KeyTooLargeException(Exception):
pass
def isqrt(n):
"""
Newton's method for finding integer square roots
:param n: The number to take the square root of
:return: The integer square root approximation (or exact value if n is a perf... |
alexismirandan/Edit-image-kivy-app | components/core_image.py | # -*- coding: utf-8 -*
import io
from kivy.core.image import Image as CoreImageKivy
from PIL import Image
class CoreImage(CoreImageKivy):
def __init__(self, arg, **kwargs):
super(CoreImage, self).__init__(arg, **kwargs)
def resize(self, fname, fname_scaled, width, height):
"""
reduces... |
AutorestCI/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/models/linux_configuration.py | # 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 ... |
tdickers/mitmproxy | test/pathod/test_language_generators.py | import os
from pathod.language import generators
import tutils
def test_randomgenerator():
g = generators.RandomGenerator("bytes", 100)
assert repr(g)
assert g[0]
assert len(g[0]) == 1
assert len(g[:10]) == 10
assert len(g[1:10]) == 9
assert len(g[:1000]) == 100
assert len(g[1000:1001... |
lluxury/P_U_S_A | 3_text/code/apache_log_parser_split.py | #!/usr/bin/env python
"""
USAGE:
apache_log_parser_split.py some_log_file
This script takes one command line argument: the name of a log file
to parse. It then parses the log file and generates a report which
associates remote hosts with number of bytes transferred to them.
"""
import sys
def dictify_logline(line... |
ViktorBarzin/TechFest | core/algebra/algebra.py | import re
from .parser import validate_equation, validate_inequality, extract_var, is_number
from sympy import simplify, Eq, solveset, Symbol
from sympy.solvers import solve
from sympy.logic.boolalg import BooleanTrue, BooleanFalse, Or, And
from sympy.solvers.inequalities import reduce_inequalities
from .exceptions imp... |
Bengt/AL-FanControl | python/fancontrol/control/controller_util.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from config.configuration import Configuration
def get_headrooms(temperatures):
"""
Calculate the thermal headroom for each sensor.
Thermal headroom is the remaining fraction of the temperature r... |
Sult/daf | tasks/management/commands/update_sovereignty.py | import sys
from django.core.management.base import BaseCommand
from apps.bulk.models import SovereigntyHolder, Sovereignty
import utils
# execute api tasks
class Command(BaseCommand):
#handle is what actualy will be executed
def handle(self, *args, **options):
systems = utils.connection.api_request(... |
josienb/python_exercises | pancake_glutton/pancake_glutton.py | # Pancake Glutton
# Created by Josien Braas to practice Python
def get_pancake_stats():
"""Ask the user for the pancake numbers."""
print("\nPlease provide the pancake intake for our visitors:\n")
list_of_people = []
for i in range(1, 11):
first_item = "Person " + str(i)
second_item = ... |
lyw07/kolibri | kolibri/deployment/default/settings/dev.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .base import * # noqa isort:skip @UnusedWildImport
INSTALLED_APPS += ["rest_framework_swagger"] # noqa
INTERNAL_IPS = ["127.0.0.1"]
ROOT_URLCONF = "kolibri.deployment.default.dev_urls"
DEVELO... |
RP-Hall/harry-plotter | src/Graph.py | """ This is the class which represents a Graph object """
from parser import *
import numpy as np
class Graph:
errorMsg = None
def __init__(self, expr=None, filename=None, dim=None, xMin=None, xMax=None, yMin=None, yMax=None, plotType=None, lineType="Solid", opacity="additive", lineWidth=2, name = None, colSt... |
adobe-type-tools/fontlab-scripts | Hinting/AutoHint.py | #FLM: Auto-Hint
__copyright__ = """
Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved.
This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0.
"""
__doc__ = """
AutoHint v1.9 May 1 200... |
glomex/gcdt-lookups | tests/test_lookups.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import maya
import mock
from gcdt_testtools.helpers import logcapture
from gcdt_lookups.lookups import _resolve_lookups, _identify_stacks_recurse, \
lookup, _find_matching_certificate, _acm_lookup
from gcdt_lookups.cred... |
MAPSuio/spring-challenge16 | balanced_brackets/generate.py | #!/usr/bin/env python
from random import choice, randint
def generate(depth):
"""Print random looking balanced expression of specified depth"""
typ = choice(["()", "[]", "{}"])
if depth == 0:
return ""
if depth == 1:
return typ
return choice([lambda _: typ[0] + generate(depth-1)... |
tehtechguy/mHTM | src/metrics.py | # metrics.py
#
# Author : James Mnatzaganian
# Contact : http://techtorials.me
# Organization : NanoComputing Research Lab - Rochester Institute of
# Technology
# Website : https://www.rit.edu/kgcoe/nanolab/
# Date Created : 02/20/16
#
# Description : Module for computing various... |
saurabh6790/frappe | frappe/cache_manager.py | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.desk.notifications import (delete_notification_count_for,
clear_notifications)
common_default_keys = ... |
mizuy/mizwiki | manage.py | #!/usr/bin/env python
from werkzeug import script
from werkzeug import DebuggedApplication
def make_app():
from mizwiki.application import application
return application
def make_debug_app():
return DebuggedApplication(make_app(), evalex=True)
def make_shell():
from mizwiki import models,local,cache
... |
earnshaws/chorlie-bucket | chorlie_bucket/urls.py | """chorlie_bucket URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
C... |
tatumdmortimer/formatConverters | EMBLtoBED.py | #!/usr/bin/env python
# This script will take an EMBL annotation file and convert to BED format
import sys
import os
import argparse
from Bio import SeqIO
def get_args():
parser = argparse.ArgumentParser(description='Converts EMBL to BED format')
parser.add_argument("embl", help="EMBL file name")
return... |
stefanfoulis/django-notifyme | notifyme/delivery_backends/base.py | #-*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import get_language, activate
from django.template.context import Context
def get_language_for_user(user):
return user.get_profile().preferred_language
class BaseDeliveryBackend(obj... |
martydill/url_shortener | code/venv/lib/python2.7/site-packages/IPython/html/base/handlers.py | """Base Tornado handlers for the notebook server."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import functools
import json
import os
import re
import sys
import traceback
try:
# py3
from http.client import responses
except ImportError:
from httpl... |
drewrobb/marathon-python | marathon/models/task.py | from datetime import datetime
from .base import MarathonResource, MarathonObject
class MarathonTask(MarathonResource):
"""Marathon Task resource.
:param str app_id: application id
:param health_check_results: health check results
:type health_check_results: list[:class:`marathon.models.MarathonHeal... |
gratipay/gratipay.com | gratipay/elsewhere/__init__.py | """This subpackage contains functionality for working with accounts elsewhere.
"""
from __future__ import division, print_function, unicode_literals
from collections import OrderedDict
from datetime import datetime
import hashlib
import json
import logging
from urllib import quote
from urlparse import urlparse, urlunp... |
galbiati/video-representations | models/model.py | import tensorflow as tf
from tensorflow.python.ops import rnn_cell_impl as tfrnn
class Model(object):
"""
Model is a wrapper for the full LSTM Encoder model.
// Future: modify to allow variable-length sequences using clever slicing,
rather than reshaping
// Future: can model be made in... |
lostorbit/secureirc | secure.py | try:
import weechat as wc
except ImportError:
print "This script must be run under WeeChat"
exit()
import codecs as c
# startup message
wc.register("encrypt", "lostorbit", "0.1", "GPL3", "two way encryption", "", "")
## ===============================================================
# user-callable e... |
briancline/maior-domus | gandi.py | #!/usr/bin/env python
from provider import gandi
import yaml
def heading(title):
print('\n%s %s' % (title, '=' * (73 - len(title))))
def subheading(title):
print('[ %s ]%s' % (title, '-' * (70 - len(title))))
if __name__ == '__main__':
with open('config.yaml', 'r') as config_file:
config = yaml.l... |
Jimdo/ansible-fastly | tests/test_fastly_cache_settings.py | #!/usr/bin/env python
import os
import unittest
import sys
from test_common import TestCommon
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'library'))
from fastly_service import FastlyConfiguration
class TestFastlyCacheSettings(TestCommon):
CACHE_SETTINGS_NAME = 'cache-settings-config-name'
... |
matthew-brett/pymc | pymc/examples/model_2.py | """
A model for the disasters data with no changepoint:
global_rate ~ Exp(3.)
disasters[t] ~ Po(global_rate)
"""
from pymc import *
from numpy import array
__all__ = ['global_rate', 'disasters', 'disasters_array']
disasters_array = array([ 4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6,
... |
allan920693/Captcha-Solver-using-Pytesseract | cut_min_x_axis.py |
# Input: 1. image and 2. the main color for recognition
# Output: the x_axis that contains least pixels with main color
def cut_min_x_axis(image,target_color):
pix = image.load()
temp_xsize, temp_ysize = image.size
min_count_x_axis=0
for x in range(int(0.25*temp_xsize),int(0.75*temp_xsiz... |
pjcunningham/Flask-Select2 | flask_select2/_compat.py | # coding: utf-8
__author__ = 'Paul Cunningham'
__copyright = 'Copyright 2017, Paul Cunningham'
import sys
PY2 = sys.version_info[0] == 2
VER = sys.version_info
if not PY2:
text_type = str
string_types = (str,)
integer_types = (int, )
iterkeys = lambda d: iter(d.keys())
itervalues = lambda d: ite... |
huddlej/msa_classifier | classify_msa_columns.py | """
Given a multiple sequence alignment, classify each column by the relative
contents of each row (e.g., all rows are equal, all rows are different, etc.)
and report the type of column per position.
This information can be used to resolve breakpoints between paralogous sequences
as reported in Antonacci and Dennis et... |
drewtempelmeyer/django-azurite | azurite/management/commands/syncstatic.py | import datetime
import mimetypes
import optparse
import os
from azure import WindowsAzureMissingResourceError
from azure.storage import BlobService
from azurite.settings import AZURITE
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Synchr... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/network/_template_builder.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
Azure/azure-sdk-for-python | sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_create_and_deploy_project.py | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError
from azure.core.credentials import AzureKeyCredential
from ... |
vileopratama/vitech | new-addons/reporting-engine-10.0/report_py3o/__manifest__.py | # -*- coding: utf-8 -*-
# Copyright 2013 XCG Consulting (http://odoo.consulting)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Py3o Report Engine',
'summary': 'Reporting engine based on Libreoffice (ODT -> ODT, '
'ODT -> PDF, ODT -> DOC, ODT -> DOCX, ODS -> ODS, etc.)... |
DailyActie/Surrogate-Model | 01-codes/deap-master/examples/ga/onemax_multidemic.py | # This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... |
volker48/namegen | namegen.py | #!/usr/bin/env python
import numpy
import os
import random
import cPickle as pickle
import argparse
class Namegen(object):
PROB_PATH = 'prob.pickle'
def __init__(self, corpus='male.txt'):
if not os.path.exists(Namegen.PROB_PATH):
self.prob, self.sums = self.read_corpus(corpus)
... |
devenney/reverie | campaign/forms.py | import datetime
from dal import autocomplete
from django import forms
from django.contrib.auth.models import User
from django.forms import widgets
from image_cropping import ImageCropWidget
from markdownx.fields import MarkdownxFormField
from .models import Campaign, Character, Faction, Item, Location, Log
from rever... |
fortyninemaps/karta | benchmarks/benchmark_init.py | import timeit
res = timeit.timeit(stmt="karta.Point((2,3))",
setup="import karta",
number=100000)
print("Point: {0}".format(res))
res = timeit.timeit(stmt="karta.Line(verts)",
setup="import karta; import random; verts = [(random.random(), random.random()) fo... |
Azure/azure-sdk-for-python | sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2021_06_01_preview/aio/operations/_bindings_operations.py | # 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 ... |
mossberg/pyipinfoio | pyipinfoio/pyipinfoio.py | #!/usr/bin/env python
"""
Simple wrapper around the ipinfo.io IP geolocation API.
"""
import json
import subprocess as sp
class IPLookupError(Exception):
pass
class IPLookup(object):
def __init__(self):
pass
def lookup(self, ip_address, param=None):
"""
Returns a diction... |
cerebrumaize/leetcode | Maximum Product of Word Lengths/1.py | #!/usr/bin/env python
'''code description'''
# pylint: disable = I0011, E0401, C0103
class Solution(object):
'''Solution description'''
def get_number(self, s):
l = []
for c in xrange(26):
l.append("0")
for c in s:
if l[122-ord(c)] != '1':
l[122-o... |
realdubb/flask-microblog | db_migrate.py | #!flask/bin/python
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_migration.py' % (v+1))
tm... |
jupiny/abacus-edu | abacus_edu/abacus_edu/settings/partials/database.py | import os
import dj_database_url
from .base import BASE_DIR
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# dj-database-url
# https:... |
borntyping/supermann | supermann/tests/test_supervisor.py | from __future__ import absolute_import
import os
import StringIO
import mock
import py.test
import supermann.supervisor
def local_file(name):
return os.path.join(os.path.dirname(__file__), name)
@py.test.fixture
def listener():
with open(local_file('supervisor.txt'), 'r') as f:
return supermann.s... |
greenac/mercury | mercury/mercury/settings.py | """
Django settings for mercury project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... |
adityahase/frappe | frappe/automation/doctype/assignment_rule/assignment_rule.py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.desk.form import assign_to
import frappe.cache_manager
from frappe import _
... |
wdv4758h/flake8 | setup.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
from setuptools import setup
try:
# Work around a traceback with Nose on Python 2.6
# http://bugs.python.org/issue15881#msg170215
__import__('multiprocessing')
except ImportError:
pass
try:
# Use https://docs.python.org/3/library/unittes... |
tomi77/ems-cli | ems_cli/commands/get_group_name_by_alias.py | import os
from . import BaseCommand
from ..i18n import _
class Command(BaseCommand):
name = os.path.splitext(os.path.basename(__file__))[0]
description = _('returns the group name given the alias name')
quiet_fields = {
'groupName': _('group name'),
}
def fill_arguments(self):
... |
mrpau/kolibri | kolibri/core/discovery/test/test_api.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import mock
import requests
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .. import models
from ..utils.network import ... |
foxscotch/advent-of-code | 2020/23/p1.py | # Python 3.8.3
class Repeating(list):
def __getitem__(self, k):
return super().__getitem__(k % len(self))
def pop(self, k):
return super().pop(k % len(self))
def main():
puzzle = Repeating([9, 4, 2, 3, 8, 7, 6, 1, 5])
cur = puzzle[0]
turns = 0
while turns < 100:
cur... |
DailyActie/Surrogate-Model | 01-codes/deap-master/doc/code/benchmarks/griewank.py | import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
try:
import numpy as np
except:
exit()
from deap import benchmarks
def griewank_arg0(sol):
return benchmarks.griewank(sol)[0]
fig = plt.figure()
ax = Axes3D(fig, azim=-29, elev=40)
# ax = Axes3D(fig)
X = ... |
October-66/Traveler-Pal | traveler_pal/app/urls.py | """app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
mback2k/django-bawebauth | bawebauth/settings/docker.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from .common import *
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'docker', ... |
unfoldingWord-dev/uwadmin | uwadmin/admin.py | from django.db.models import Q
from django.contrib import admin
import reversion
from uwadmin.models import (
LangCode,
Contact,
Organization,
Connection,
ConnectionType,
RecentCommunication,
OpenBibleStory,
PublishRequest,
LicenseAgreement
)
class LangCodeAdmin(admin.ModelAdmin... |
cocoaaa/ml_gesture | cos_vs_line.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 17:31:15 2015
@author: LLP-admin
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,np.pi,num= 20)
def f1(x):
return -2*x/np.pi +1;
def f2(x):
return np.cos(x);
fig = plt.figure(figsize = (6,8))
ax1 = fig.add_subplot(2,1,1);
ax1.set_xlabe... |
matthewperkins/abf_reader | chunker.py | from numpy import memmap, fromfile, float32, int16, memmap, issubdtype, all, array
from matplotlib.cbook import iterable
import pdb
class abf_chunker(object):
''' use this to return data in chunks from abf files'''
def __init__(self, abr, **kwds):
self.abr = abr
self.dp = self.abr.total_aq()
... |
PyConPune/pune.pycon.org | inventory/migrations/0004_auto_20171106_0516.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0003_auto_20170806_0041'),
]
operations = [
migrations.RemoveField(
model_name='tshirt',
... |
clkao/grano | demo/demo_simple/loader.py | from grano.logic import Loader
import unicodecsv
# This source URL will be applied to all properties without their own lineage:
DEFAULT_SOURCE_URL = 'http://www.opennews.org/'
# Any settings (free-form dict):
PROJECT_SETTINGS = {}
loader = Loader('opennews2', project_label='opennews',
project_settings=PROJECT... |
Culeshovi/cs229 | Regressions/logisticRegression.py | import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import pandas as pd
import numpy as np
import math
def logistic_runner(x,y,a,b,m,iterate):
new_m=m
new_b=b
for i in range(iterate):
[new_b,new_m]=gradient_ascent_algorithm(x,y,a,new_b,new_m)
return [new_b,new_m]
... |
dmnfarrell/peat | Protool/quatfit.py | """
Quatfit routines for PDB2PQR
This module is used to find the coordinates of a new
atom based on a reference set of
coordinates and a definition set of coordinates.
Original Code by David J. Heisterberg
The Ohio Supercomputer Center
1224 Kinnear Rd.
Columbus, OH 43212-1163
(614... |
greatghoul/pyremark | remark.py | # -*- coding: utf-8 -*-
import codecs, os, clik
remark = clik.App('remark', version='0.1.0', description='Remark slides utilities.')
@remark(usage='FOLDER-TO-CREATE')
def new(args, opts, console):
"""
Create a new remark slides
"""
if len(args) < 1:
console.error('<red>error:</> you must prov... |
exherb/idcard | tools/process_data.py | import json
def main():
areas = json.load(open('raw_areas.json'))
provinces = areas['province']
structed_provinces = {}
for province in provinces:
id = province['id']
text = province['text']
province_id = int(id[0:2])
structed_provinces[province_id] = {
'id... |
ramelito/pgw | pgw.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PGW
~~~~~~
Payment gateways VNF with RESTful API.
:copyright: (c) 2015 by Anton K. Komarov.
:license: MIT, see LICENSE for more details.
"""
import os
import sqlite3
from flask import Flask, g, abort, jsonify
from flask.ext.restful import Api, Resource, reqparse, fi... |
b09780978/SEH_Fuzzer | SEH_Fuzzer/demo/demo_parse_dll.py | import sys
import os
CURRENT_DIR = os.getcwd()
PE_DIR = "\\".join(CURRENT_DIR.split("\\")[:-1])
print "[+] Current position: %s" % (CURRENT_DIR)
print "[+] PE class position: %s" % (PE_DIR)
print
# add PE class folder
sys.path.append(PE_DIR)
from PE import *
exe = PE_DIR + "\\vuln\\ImageLoad.dll"
pe ... |
Fire-Proof/cue-csgo | cue_csgo/constants.py | DEFAULT_SETTINGS = {
"update_interval": 0.01,
"debug": False,
"hardware": {
"device_id": 0 # only change if use more than one corsair device, and it's interfering with the program
},
"renders": {
"active": ["BackgroundRender", "HpRender", "WeaponRender", "BombRender", "SmokeRender",... |
snclucas/stashy | UserManager.py | import json
import config
class UserManager:
"""User manager."""
def __init__(self, database):
self.database = database
self.salt = config.salt
def save_user(self, user):
if self.__check_user__(user):
result = self.find_user_by_username(user['username'])
... |
pombredanne/metamorphosys-desktop | metamorphosys/META/externals/HCDDES/src/lib/BlockTemplate/Python/GetCoefficients.py | from types import *
def GetCoefficientAux( zp_list, offset, power ):
if power == len( zp_list ):
return zp_list[ offset ]
result = 0
power += 1
for subOffset in range( offset + 1, power ):
result += GetCoefficientAux( zp_list, subOffset, power )
return zp_... |
squeaky-pl/japronto | examples/6_exceptions/exceptions.py | from japronto import Application, RouteNotFoundException
# These are our custom exceptions we want to turn into 200 response.
class KittyError(Exception):
def __init__(self):
self.greet = 'meow'
class DoggieError(Exception):
def __init__(self):
self.greet = 'woof'
# The two handlers below ... |
TUW-GEO-python-intro/Exercise-1 | ex1/dates_times.py | # Copyright (c) 2015,Vienna University of Technology,
# Department of Geodesy and Geoinformation
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the... |
seanbell/django-scripts | tmux_worker/start.py | #!/usr/bin/env python2.7
import multiprocessing
import numpy as np
import argparse
import subprocess
import socket
import psutil
def start_tmux_worker(hostname, utilization, ram, config, queue, worker_dir, venv_dir):
# ensure each worker has enough RAM
concurrency = int(np.clip(args.utilization, 0.0, 1.0) *... |
nwjs/nw.js | test/sanity/app-open-event/test.py | import time
import os
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
os.... |
DanielHopper/botty-bot-bot-bot | src/plugins/haiku/__init__.py | #!/usr/bin/env python3
import os, json, re, random
from ..utilities import BasePlugin
PUNCTUATION = r"[`~@#$%_\\'+\-/]" # punctuation that is a part of text
STANDALONE = r"(?:[!.,;()^&\[\]{}|*=<>?]|[dDpP][:8]|:\S)" # standalone characters or emoticons that wouldn't otherwise be captured
WORD_PATTERN = STANDALONE + r... |
jimcarreer/hpack | hpack/huffman.py | # -*- coding: utf-8 -*-
"""
hpack/huffman_decoder
~~~~~~~~~~~~~~~~~~~~~
An implementation of a bitwise prefix tree specially built for decoding
Huffman-coded content where we already know the Huffman table.
"""
from .compat import to_byte, decode_hex
from .exceptions import HPACKDecodingError
def _pad_binary(bin_str... |
scott-hand/elmerbot | elmerbot/commands/search.py | import discord
import string
from elmerbot.commands import ElmerCommand
__all__ = ["SearchCommand", "InfoCommand"]
class SearchCommand(ElmerCommand):
command = "search"
description = (
"Search for a whisky by name. Optionally put a number of results to limit it to in front of "
"your query.\... |
OrderFromChaos/wikibrowse | crawler.py | #The idea behind this code is relatively simple:
#Branching out from one Wikipedia article (for example, Compton Scattering), list
#all article hrefs. Query if they are physics related, then continue iterating over the list.
#When the page is complete, move to the next page and do the same thing.
#For r... |
jiadaizhao/LeetCode | 0201-0300/0297-Serialize and Deserialize Binary Tree/0297-Serialize and Deserialize Binary Tree.py | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import collections
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rt... |
thunderhoser/GewitterGefahr | gewittergefahr/deep_learning/gradient_boosting.py | """Methods for creating, training, and applying gradient-boosted trees (GBT).
The input data for GBT are features (outputs of the last "Flatten" layer)
created by a convolutional neural network (CNN).
"""
import pickle
import numpy
import xgboost
from gewittergefahr.gg_utils import file_system_utils
from gewittergefa... |
storborg/pylogic | setup.py | from setuptools import setup
setup(name='pylogic',
version='0.0.1.dev',
description='Tools for working with Saleae Logic.',
long_description='',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Pyt... |
Azure/azure-sdk-for-python | sdk/servicefabric/azure-mgmt-servicefabric/azure/mgmt/servicefabric/operations/_cluster_versions_operations.py | # 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 ... |
GiggleLiu/poorman_nn | poornn/spconv.py | '''
Convolution using sparse matrix.
'''
from __future__ import division
import numpy as np
import pdb
import time
from scipy import sparse as sps
from .lib.spconv import lib as fspconv
from .lib.spconv_cc import lib as fspconv_cc
from .utils import scan2csc, tuple_prod, spscan2csc,\
masked_concatenate, dtype2tok... |
mblaauw/Kaggle_CatsVsDogs | predict.py | __author__ = 'MICH'
"""
Produce a predictions file for Kaggle from OverFeat predictions on test images
Set your paths below
"""
import os
import csv
import random
from glob import glob
#
cats_file = 'data/cats.txt'
dogs_file = 'data/dogs.txt'
predictions_dir = 'data/overfeat_predictions_test/'
output_file = 'data/pr... |
hbussell/pinax-tracker | apps/tasks/filters.py | from django import forms
import django_filters as filters
from tasks.models import Task
from projects.models import Project
from django.contrib.auth.models import User
from milestones.models import Milestone
from django.contrib.contenttypes.models import ContentType
from django.utils.safestring import SafeString
cla... |
lmazuel/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/models/creation_data.py | # 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 ... |
davidtimmons/python-study | google-python-exercises/basic/list2.py | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Completed by David Timmons.
# Additional basic list exercises
# D. Given a list of nu... |
tlksio/tlksio | env/lib/python3.4/site-packages/pylint/reporters/__init__.py | # Copyright (c) 2003-2010 Sylvain Thenault (thenault@gmail.com).
# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
# This program 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 2 of the L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.