commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
1f3625b98de4edd8a0d0bcce882c5f79aeaf23b2 | Add file for tests, when no rule is specified | PatrikValkovic/grammpy | tests/rules_tests/NoRuleSpecifiedTest.py | tests/rules_tests/NoRuleSpecifiedTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class NoRuleSpecifiedTest(TestCase):
pass
if __name__ == '__main__':
main() | mit | Python | |
0c7b8a3054786fcf11ec98c1dff16ada12d711b6 | Add alg_knight_tour_dfs.py | bowen0701/algorithms_data_structures | alg_knight_tour_dfs.py | alg_knight_tour_dfs.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def build_knight_tour_graph():
pass
def main():
pass
if __name__ == '__main__':
main()
| bsd-2-clause | Python | |
044089aa97323487d59480bac353b018efe62925 | Add tool `cookbook2` for Python 2.7.9+. | leven-cn/52prog-www | tools/cookbook2.py | tools/cookbook2.py | #!/usr/bin/env python
'''Python 2 Cookbook.
Copyright 2015 Li Yun.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... | apache-2.0 | Python | |
4fb863c89f7e024cfa95234826ff58ea519e851d | allow configuration to be set via api | dongguangming/python-pdfkit,JazzCore/python-pdfkit,lucashtnguyen/python-pdfkit,phobson/python-pdfkit,Geosyntec/python-pdfkit,phobson/python-pdfkit,skybird6672/python-pdfkit,lucashtnguyen/python-pdfkit,skybird6672/python-pdfkit,Geosyntec/python-pdfkit,JazzCore/python-pdfkit,dongguangming/python-pdfkit | pdfkit/api.py | pdfkit/api.py | # -*- coding: utf-8 -*-
from .pdfkit import PDFKit
def from_url(url, output_path, options=None, toc=None, cover=None, configuration=None):
#TODO rework
"""
Convert file of files from URLs to PDF document
:param url: URL or list of URLs to be saved
:param output_path: path to output PDF file
:par... | # -*- coding: utf-8 -*-
from .pdfkit import PDFKit
def from_url(url, output_path, options=None, toc=None, cover=None):
#TODO rework
"""
Convert file of files from URLs to PDF document
:param url: URL or list of URLs to be saved
:param output_path: path to output PDF file
:param options: (optiona... | mit | Python |
923989e06d36b4476d4671a439b0be58c8edaf39 | Create ex5_1.py | laetrid/learning | First_course/ex5_1.py | First_course/ex5_1.py | #!/usr/bin/env python
DEBUG = False
# CDP data parser
# All data imports from test5_base.py
import test5_base
from sys import argv
if len(argv) != 1 and argv[1] == '-d': DEBUG = True
# Make list of show cdp neighbor detail commands from test5_base
sh_cdp_detail = []
for line in dir(test5_base):
if 'cdp' in line... | apache-2.0 | Python | |
571f1b38439bf50dc1c9af4c02f5a4bd9009a6b6 | add tweet puller | luozhaoyu/TTTT,luozhaoyu/TTTT,luozhaoyu/TTTT,luozhaoyu/TTTT | twitter_streamer.py | twitter_streamer.py | from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import sys
import datetime
OUTPUT_FILE="new_tweets.txt"
CONSUMER_SECRET="oKsGTjajzKBiFGjxVJGb7mh0RlTtLwS8TlfORTnBZlsVcKyuwz"
CONSUMER_KEY="gc5jBYM3eC3wFFI4pLipSvvU9"
TOKEN_SECRET="nHmgTX56HKaIFAKD3QQjHtbua... | mit | Python | |
01a67aaa5295d0e7fc83890b0916576645e1b676 | add migration for remote_base_url help_text | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/linked_domain/migrations/0016_update_remote_base_url_help_text.py | corehq/apps/linked_domain/migrations/0016_update_remote_base_url_help_text.py | # Generated by Django 2.2.24 on 2021-07-23 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('linked_domain', '0015_add_previews_to_choices_20210617_2010'),
]
operations = [
migrations.AlterField(
model_name='domainlink',... | bsd-3-clause | Python | |
8ef0cb26e53a42cf67b0a313f0a82083518992c2 | Create colorspaces.py | stiphyMT/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,danforthcenter/plantcv | plantcv/plantcv/visualize/colorspaces.py | plantcv/plantcv/visualize/colorspaces.py | # Visualize an RGB image in all potential colorspaces as one glance
import os
import cv2
import numpy as np
from plantcv.plantcv import params
from plantcv.plantcv import resize
from plantcv.plantcv import plot_image
from plantcv.plantcv import fatal_error
from plantcv.plantcv import print_image
from plantcv.plantcv i... | mit | Python | |
2cb905a4a0da9650135ab297d9e55c02bc7261c5 | Add a script for running pytest with the correct sys.path. | Uname-a/knife_scraper,Uname-a/knife_scraper,Uname-a/knife_scraper | pytest_run.py | pytest_run.py | # coding=utf-8
"""This is a script for running pytest from the command line.
This script exists so that the project directory gets added to sys.path, which
prevents us from accidentally testing the globally installed willie version.
pytest_run.py
Copyright 2013, Ari Koivula, <ari@koivu.la>
Licensed under the Eiffel F... | mit | Python | |
71b73143b0b33853a7584a8de8b8b6ddcb77286f | Add repro_acis.py: reprocess ACIS level=1 data and build manifest.yaml | liweitianux/chandra-acis-analysis,liweitianux/chandra-acis-analysis,liweitianux/chandra-acis-analysis | bin/repro_acis.py | bin/repro_acis.py | #!/usr/bin/env python3
#
# Copyright (c) 2017 Weitian LI <liweitianux@live.com>
# MIT license
#
# 2017-02-27
"""
Reprocess Chandra ACIS raw "secondary" (level=1) data using the
CIAO contrib tool ``chandra_repro``, and build the ``manifest.yaml``.
"""
import os
import argparse
import subprocess
import logging
from glo... | mit | Python | |
20f3b4f05aa1a29716e94efc8aca8d83cac78b3c | add excel | zhaochl/python-utils,zhaochl/python-utils,zhaochl/python-utils,zhaochl/python-utils,zhaochl/python-utils,zhaochl/python-utils,zhaochl/python-utils | utils/excel_util.py | utils/excel_util.py | #!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
#pip install xlrd
#pip install xlwt
import xlrd
import xlwt
import sys
from datetime import date,datetime
import os
def read_excel(filename):
workbook = xlrd.open_workbook(filename)
# print sheet2.name,sheet2.nrows,sheet2.ncols
sheet2 = workboo... | apache-2.0 | Python | |
6ce5acabb6fd5c6c9f5d6707197edf910e201240 | Create HelixMesh.py | nelinnemann/Salome-Scripts | Helix-Mesh/HelixMesh.py | Helix-Mesh/HelixMesh.py | # -*- coding: utf-8 -*-
###
### This file is generated automatically by SALOME v7.5.1 with dump python functionality
###
import sys
import salome
salome.salome_init()
theStudy = salome.myStudy
###
### GEOM component
###
import GEOM
from salome.geom import geomBuilder
geompy = geomBuilder.New(theStudy)
import math
... | mit | Python | |
eb5e6bde589f3598d955c0d7389f7054a3a3c642 | Add prototype code for testing scalability. | ron-rivest/2017-bayes-audit,ron-rivest/2017-bayes-audit | 2017-code/test_scalability.py | 2017-code/test_scalability.py | # test_scalability.py
# Ronald L. Rivest with Huasyn Karimi
import syn2
def tester(se):
# copy code here from syn2.test; modify as needed
def test_scale(k):
# start timer
se = syn2.SynElection()
# ... set parameters here based on k
# run "test"
# stop timer; print k and elapsed time
f... | mit | Python | |
f9419efec8051ecbd7edbaf4993e01ff7e7158f9 | Add setup.py | tosh1ki/pyogi,tosh1ki/pyogi | pyogi/setup.py | pyogi/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize('koma.pyx'))
| mit | Python | |
256667692e65ad98232e1c9ca8065aa3388cb8c9 | Reshape module | 255BITS/HyperGAN,255BITS/HyperGAN | hypergan/modules/reshape.py | hypergan/modules/reshape.py | import torch.nn as nn
class Reshape(nn.Module):
def __init__(self, *dims):
self.dims = dims
super(Reshape, self).__init__()
def forward(self, x):
return x.view(x.size()[0], *self.dims)
| mit | Python | |
1fafccc7df5179ce89b100537e45307417658512 | Add first basic unittests using py.test | clones/wtforms | tests/test_validators.py | tests/test_validators.py | """
test_validators
~~~~~~~~~~~~~~
Unittests for bundled validators.
:copyright: 2007-2008 by James Crasta, Thomas Johansson.
:license: MIT, see LICENSE.txt for details.
"""
from py.test import raises
from wtforms.validators import ValidationError, length, url, not_empty, email, ip_addres... | bsd-3-clause | Python | |
274b34169d1ca82e19c807ae610ea00011334300 | Add script that create the User system tables in local dev environment (#1991) | hasadna/anyway,hasadna/anyway,hasadna/anyway,hasadna/anyway | anyway/scripts/build_redacted_tables_for_dev.py | anyway/scripts/build_redacted_tables_for_dev.py | from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from anyway.config import SQLALCHEMY_DATABASE_URI
from anyway.models import Users, users_to_roles, Roles
"""This is a separated script that create the User system tables and all the default data in them.
To use... | mit | Python | |
dc2984a506d4882e408813a526f3de490bdd8422 | Create mission3-answer.py | neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu... | POH4/mission3-answer.py | POH4/mission3-answer.py | # coding: utf-8
(t, n) = [int(i) for i in raw_input().strip().split()]
maximum = 0
sum = 0
a = []
for i in xrange(n):
m = int(raw_input())
a.append(m)
if i >= t:
sum += m - a.pop(0)
else:
sum += m
if sum > maximum:
maximum = sum
print maximum
| mit | Python | |
493888fecc8c0a007fb208df8bb2a29b2ba409aa | move file | kaczmarj/neurodocker,kaczmarj/neurodocker | src/docker/miniconda.py | src/docker/miniconda.py | """Class to add Miniconda and create Conda environment."""
from __future__ import absolute_import, division, print_function
import os
from .utils import indent
from ..utils import logger, save_yaml, check_url
class Miniconda(object):
"""Class to add Miniconda installation and Conda environment to Dockerfile.
... | apache-2.0 | Python | |
ceb60141d5f8137fe912ccf3a8d191f7a31bc0c1 | Attach logic to node. | soasme/riotpy | riot/parse.py | riot/parse.py | # -*- coding: utf-8 -*-
import types
import re
from .observable import Observable
def attach_logic_to_node(script, node, opts):
self = node
exec script
fnnames = re.findall(r'^def ([a-zA-Z0-9_]+)', script, re.MULTILINE)
localfns = locals()
for fnname in fnnames:
attribute = types.MethodTy... | mit | Python | |
27a3334de65263852dbbe02a113c7395fd75b746 | Add gyp_nacl.py to make gyp_nacl importable on python 2.6 | sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client | build/gyp_nacl.py | build/gyp_nacl.py | #!/usr/bin/python
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This file is (possibly, depending on python version) imported by
# gyp_nacl when GYP_PARALLEL=1 and it creates sub-processes
# t... | bsd-3-clause | Python | |
3644e3dc2d97f87b3810f1295a98b8977fa0c387 | Add template filters test cases | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf | tests/test_template_filters.py | tests/test_template_filters.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import render_template_string
def test_nl2br_filter(app):
s = '{{ "\n"|nl2br }}'
rs = render_template_string(s)
assert rs == '<p><br/>\n</p>'
def test_blankspace2nbsp_filter(app):
s = '{{ " \t"|blankspace2nbs... | mit | Python | |
58bee0ac0df709f9a5cee83e7828dce148182d10 | Add a few tests for Tee | maxalbert/tohu | tests/v6/test_tee_generator.py | tests/v6/test_tee_generator.py | from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator
def test_tee_generator():
class QuuxGenerator(C... | mit | Python | |
c34f5307d4262fe358c5a6b503bbaad558793f06 | Add test cases for decode and extract password | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/hqwebapp/tests/test_utils.py | corehq/apps/hqwebapp/tests/test_utils.py | # -*- coding: utf-8 -*-
from django.test import TestCase, override_settings
from corehq.apps.hqwebapp.models import HashedPasswordLoginAttempt
from corehq.apps.hqwebapp.utils import decode_password, extract_password
HASHED_PASSWORD_MAPPING = {
"sha256$1e2d5bc2hhMjU2JDFlMmQ1Yk1USXpORFUyZjc5MTI3PQ==f79127=": "12345... | bsd-3-clause | Python | |
35d90ec69f81f039aa0607c11d7ef5c9284a5f8f | Create unitest.py | MichelJuillard/dlstats,mmalter/dlstats,Widukind/dlstats,mmalter/dlstats,MichelJuillard/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats | src/fetchers/unitest.py | src/fetchers/unitest.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import unittest
import eurostat
import pymongo
import types
import lxml.etree
import urllib
class TestEurostat(unittest.TestCase):
"""Test Eurostat"""
def setUp(self):
self.toto=eurostat.Eurostat()
webpage = urllib.request.urlopen("... | agpl-3.0 | Python | |
510b560921bb78b30cd9016d0de719da5781db01 | Create places_utils.py | GKalliatakis/Keras-VGG16-places365 | places_utils.py | places_utils.py | import json
import warnings
import numpy as np
from keras import backend as K
from keras.utils.data_utils import get_file
CLASS_INDEX = None
CLASS_INDEX_PATH = 'https://github.com/GKalliatakis/Keras-VGG16-places365/blob/master/places365_class_index.json'
def decode_predictions(preds, top=5):
"""Decodes the predi... | mit | Python | |
2f0dae0477a7614a0730eae27e2c925979ddff53 | Add setup.py for easy Cython ext building | leovp/graphics | HofstadterButterfly/setup.py | HofstadterButterfly/setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("cyhof", ["cyhof.pyx"])]
)
| mit | Python | |
11d976b50b8983174d9fdf8e6a276b1639cd0b95 | Fix with combined with os.open; doesn't work on Python2.6. | mmaker/bridgedb,mmaker/bridgedb,pagea/bridgedb,pagea/bridgedb,wfn/bridgedb,wfn/bridgedb | lib/bridgedb/crypto.py | lib/bridgedb/crypto.py | # -*- coding: utf-8 -*-
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org>
# please also see AUTHORS file
# :copyright: (c) 2007-2013, The Tor Project, Inc.
# (c) 2007-2013, all entities within the AUTHORS file... | # -*- coding: utf-8 -*-
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org>
# please also see AUTHORS file
# :copyright: (c) 2007-2013, The Tor Project, Inc.
# (c) 2007-2013, all entities within the AUTHORS file... | bsd-3-clause | Python |
8c7d365b6c749ade229fb87df9d93a03c7f1dec8 | Add __init__.py to plugins to make them importable | Frikster/Mesoscale-Brain-Explorer | src/plugins/__init__.py | src/plugins/__init__.py | #!/usr/bin/env python
| mit | Python | |
17480d9a74483dbe9e364c58afd728dc8308a0a2 | Create fs_downproject.py | laninsky/creating_dadi_SNP_input_from_structure,laninsky/creating_dadi_SNP_input_from_structure,laninsky/creating_dadi_SNP_input_from_structure | fs_downproject/fs_downproject.py | fs_downproject/fs_downproject.py | import numpy
import scipy
import matplotlib
import dadi
with open('file_name', 'r') as myfile:
dadi_input=myfile.read().replace('\n', '')
dd = dadi.Misc.make_data_dict(dadi_input)
with open(dadi_input, 'r') as myfile:
headerline=myfile.readline().replace('\n', '')
final_fs = 0
final spectrum = 0
fs = dadi.... | mit | Python | |
2b8e4806ab3b734f1e14ee572ba8ab84d70a156a | Create processcommunicator.py | MaxDistructo/ShellScripts,MaxDistructo/ShellScripts,MaxDistructo/ShellScripts,MaxDistructo/ShellScripts | processcommunicator.py | processcommunicator.py | import platform
from distutils.spawn import find_executable
import urllib2
from subprocess import call
javaInstallerMacOS = "https://www.dropbox.com/s/tbt0klckirvwrke/jre-8u191-macosx-x64.dmg?dl=1" #URL of MacOS Java Installer
aptRepositoryOracleJava = "ppa:webupd8team/java" #URL of Linux Oracle Java Repo
jarLocatio... | mit | Python | |
9d36f9f3019b9c86a69fcbaa47add914da7efc44 | Add some basic tests for some of the globals noted in #12292 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/integration/loader/globals.py | tests/integration/loader/globals.py | # -*- coding: utf-8 -*-
'''
integration.loader.globals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test Salt's loader regarding globals that it should pack in
'''
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../')
# Import salt libs
i... | apache-2.0 | Python | |
2d9cc52e6ce6a6d2584e1d73e3d84ca3538758d9 | Add a script to generate some files to be used for the sensor calibration | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | Sensors/recordCalibration.py | Sensors/recordCalibration.py | from pymavlink import mavutil
fileout = open('acc.txt', 'w')
filemag = open('mag.txt', 'w')
filegyro = open('gyro.txt', 'w')
# create a mavlink serial instance
master = mavutil.mavlink_connection('/dev/ttyUSB1', baud=57600, source_system=255)
try:
while True:
msg = master.recv_match(type='HEARTBEAT', bloc... | mit | Python | |
94b97eecaf9c7961fc7571b2c76836646af8cd07 | Create Deck.py - Create the Deck class to hold the cards. | VictorLoren/card-deck-python | Deck.py | Deck.py | #Deck
class Deck:
# '''Definition of a card deck.'''
def __init__(self,hasJoker=False):
self.suits = ['H','D','S','C']
self.values = [str(x) for x in range(2,11)] #2-10 cards
self.values.extend(['J','Q','K','A']) #Face cards
#Assemble deck
self.cards = [(v+s) for v in self.values for s in self.suits]
#A... | mit | Python | |
7074b26264e3f40a52a9b94daab3646299489527 | Add Hand.py - Defines a Hand object that contains Card objects. | VictorLoren/Crak-card-game-python | Hand.py | Hand.py | from Card import Card
#Hand
class Hand(Card):
#Initiate the hand
def __init__(self,cards=[]):
self.cards = cards
#Print out your whole hand
def __str__(self,joinWith=','):
handStr = ''
for card in self.cards:
handStr += str(card) + joinWith
#Returns all of the cards (with no trail joinWith character)
... | mit | Python | |
43e4e6b16531c537e3ab8257219668168893c0f5 | make sure urls work with or without slashes | puttarajubr/commcare-hq,gmimano/commcaretest,dimagi/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL... | django-hq/apps/xformmanager/api_/urls.py | django-hq/apps/xformmanager/api_/urls.py | from django.conf.urls.defaults import *
# this module is called api_ because importing from "api.xforms"
# conflicts with the builtin python namespace
from xformmanager.api_.xforms import *
urlpatterns = patterns('',
# remember: order urls by most qualified to least
# Registered xform sc... | from django.conf.urls.defaults import *
# this module is called api_ because importing from "api.xforms"
# conflicts with the builtin python namespace
from xformmanager.api_.xforms import *
urlpatterns = patterns('',
# remember: order urls by most qualified to least
# Registered xform sc... | bsd-3-clause | Python |
cc5d90dea2ab56dcdfa7ab987f59e3c091fdb28e | Create sastry[draft].py | JLJTECH/TutorialTesting | Edabit/sastry[draft].py | Edabit/sastry[draft].py | #This will be finished once i'm awake. This is but a placeholder while I work.
import math
def sass(n):
v = str(n - 1)
c = str(n)
forward = int(v + c)
while forward > 0:
print(forward)
print(math.sqrt(forward))
print("* * * " * 5 )
forward -= 1
sass(110)
| mit | Python | |
567e18b77fe2a89d722be857e842a25750bc216a | Fix unit test | jameslegg/boto,nexusz99/boto,s0enke/boto,awatts/boto,weebygames/boto,pfhayes/boto,acourtney2015/boto,jindongh/boto,ocadotechnology/boto,dablak/boto,TiVoMaker/boto,campenberger/boto,weka-io/boto,jotes/boto,clouddocx/boto,appneta/boto,Asana/boto,tpodowd/boto,stevenbrichards/boto,alfredodeza/boto,ddzialak/boto,varunarya10... | tests/unit/dynamodb2/test_layer1.py | tests/unit/dynamodb2/test_layer1.py | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates.
# All rights reserved.
#
# 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 right... | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates.
# All rights reserved.
#
# 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 right... | mit | Python |
df381322386549738c8011f3605769b950d27518 | introduce a mixin for getting changed fields in django models | adaptive-learning/proso-apps,adaptive-learning/proso-apps,adaptive-learning/proso-apps | proso/django/models.py | proso/django/models.py | from django.forms.models import model_to_dict
class ModelDiffMixin(object):
"""
A model mixin that tracks model fields' values and provide some useful api
to know what fields have been changed.
See: http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful
"""
def __... | mit | Python | |
f9f2f18cfa99c32e29206e4c950aa096c6645165 | Add 0002 file | Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python,Yrthgze/prueba-sourcetree2,Yrthgze/prueba-sourcetree2,Show-Me-the-Code/python,Yrthgze/prueba-sourcetree2,Yrthgze/prueba-sourcetree2,Yrthgze/prueba-sourcetree2,Yrthgze/prueba-sourcetree2,Show-Me-the-Code/python | Drake-Z/0002/0002.py | Drake-Z/0002/0002.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。'
__author__ = 'Drake-Z'
import mysql.connector
def write_to_mysql(filename):
f = open(filename, 'r')
conn = mysql.connector.connect(user='root', password='******', database='test')
print('登录数据库成功')
... | mit | Python | |
5daecaf60201e98b23fbfcb3585f92f2ded395de | Split out client to seperate file with no mopidy knowledge | mopidy/mopidy-dirble | mopidy_dirble/client.py | mopidy_dirble/client.py | from __future__ import unicode_literals
import json
import logging
import time
import urllib2
logger = logging.getLogger(__name__)
class Dirble(object):
"""Light wrapper for Dirble API lookup.
Important things to note:
- The client will do exponential back off when requests fail or timeout.
- The c... | apache-2.0 | Python | |
43916bdadc013f3df5cf2f6664facb19e98c1d90 | Create number-of-matching-subsequences.py | kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015 | Python/number-of-matching-subsequences.py | Python/number-of-matching-subsequences.py | # Time: O(n + w), n is the size of S, w is the size of words
# Space: O(1)
# Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
#
# Example :
# Input:
# S = "abcde"
# words = ["a", "bb", "acd", "ace"]
# Output: 3
# Explanation: There are three words in words that ... | mit | Python | |
a70bca61fe8d89b355737e17335fd3a0d6bfaf5c | Add module to calculate optimal CFF default and nominal glyph widths | googlefonts/fonttools,fonttools/fonttools | Lib/fontTools/cffLib/width.py | Lib/fontTools/cffLib/width.py | # -*- coding: utf-8 -*-
"""T2CharString glyph width optimizer."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.ttLib import TTFont, getTableClass
from collections import defaultdict
from operator import add
from functools import partial
class miss... | mit | Python | |
6ca79d2ce16f8745c8d58c3dea20174931820ef3 | Add User object to model | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | api/models.py | api/models.py | from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
from api import db
class User(db.Model):
id = db.Column(db.Inte... | mit | Python | |
09a7f1ecee1e8a96f9eec61265a2d97485163648 | add ip utils | garyelephant/pyutils | pyutils/ip.py | pyutils/ip.py | def binary_ipaddr( ip_str ):
return '.'.join([bin(int(x)+256)[3:] for x in ip_str.split('.')])
if __name__ == '__main__':
ip_base10 = '192.168.0.13'
ip_binary = binary_ipaddr( ip_base10 )
print ip_base10, '-->', ip_binary
# 192.168.0.13 --> 11000000.10101000.00000000.00001101
| mit | Python | |
bb8139bad026ebc46bf0cbdab9e049a1df3daf33 | fix en space | dragondjf/QFramer,dragondjf/QFramer,EmbolismSoil/QFramer,dragondjf/QFramer,EmbolismSoil/QFramer,EmbolismSoil/QFramer,dragondjf/QFramer,EmbolismSoil/QFramer,dragondjf/QFramer,EmbolismSoil/QFramer | qssbuilder.py | qssbuilder.py | # -*- coding: utf-8 -*-
import os
import sys
import copy
qssFolder = os.sep.join([os.getcwd(), 'skin', 'qss'])
qssTemplatePath = os.sep.join([qssFolder, 'template.qss'])
theme = {
'main_background_color': "qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgb(24, 148, 120), stop:0.5 rgb(220, 220, 220), ... | # -*- coding: utf-8 -*-
import os
import sys
import copy
qssFolder = os.sep.join([os.getcwd(), 'skin', 'qss'])
qssTemplatePath = os.sep.join([qssFolder, 'template.qss'])
theme = {
'main_background_color': "qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgb(24, 148, 120), stop:0.5 rgb(220, 220, 220), ... | lgpl-2.1 | Python |
8b9e86f97c26e04e1743fd5f155c2bd7b09ef602 | Add missing file from #11696. | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/test/test_msilib.py | Lib/test/test_msilib.py | """ Test suite for the code in msilib """
import unittest
import os
from test_support import run_unittest, import_module
msilib = import_module('msilib')
class Test_make_id(unittest.TestCase):
#http://msdn.microsoft.com/en-us/library/aa369212(v=vs.85).aspx
"""The Identifier data type is a text string. Identifi... | mit | Python | |
d09a45015c385f2ae1fdfaa496175bd48f1a51bf | test signal module | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/test/test_signal.py | Lib/test/test_signal.py | # Test the signal module
import signal
import os
pid = os.getpid()
# Shell script that will send us asynchronous signals
script = """
(
set -x
sleep 2
kill -5 %(pid)d
sleep 2
kill -2 %(pid)d
sleep 2
kill -3 %(pid)d
) &
""" % vars()
def handlerA(*args):
print "handlerA", args
HandlerBCalled = "HandlerBCall... | mit | Python | |
c1734bbf32ce7c3433a197b9c43ab75d2d69e097 | Add news.py file | chatea/NewsMap,chatea/NewsMap,chatea/NewsMap | news.py | news.py | import sys
reload(sys)
sys.setdefaultencoding('utf8')
from google.appengine.ext import db
class NewsModel(db.Model):
title = db.StringProperty(required=True)
content = db.StringProperty()
populatiry = db.IntegerProperty()
news_datetime = db.DateTimeProperty()
news_url = db.StringProperty(required=... | apache-2.0 | Python | |
61af8b00b9583f453d95cf3892bf1be493ef1452 | add reposting abilityes maybe? | mralext20/alex-bot | alexBot/cogs/games_reposting.py | alexBot/cogs/games_reposting.py | import logging
from typing import Dict
import discord
from discord import PartialEmoji
from discord.ext import commands
from discord.message import Message
from discord.webhook import AsyncWebhookAdapter, WebhookMessage
from emoji_data import EmojiSequence
from ..tools import Cog
log = logging.getLogger(__name__)
... | mit | Python | |
c77d2ea34125ad68194cda9cc5a161ac6756668c | Remove dash (#9089) | jnewland/home-assistant,nugget/home-assistant,GenericStudent/home-assistant,ct-23/home-assistant,PetePriority/home-assistant,ct-23/home-assistant,nkgilley/home-assistant,LinuxChristian/home-assistant,LinuxChristian/home-assistant,kennedyshead/home-assistant,DavidLP/home-assistant,balloob/home-assistant,tboyce021/home-a... | homeassistant/scripts/keyring.py | homeassistant/scripts/keyring.py | """Script to get, set, and delete secrets stored in the keyring."""
import os
import argparse
import getpass
from homeassistant.util.yaml import _SECRET_NAMESPACE
REQUIREMENTS = ['keyring>=9.3,<10.0']
def run(args):
"""Handle keyring script."""
parser = argparse.ArgumentParser(
description=("Modify ... | """Script to get, set and delete secrets stored in the keyring."""
import os
import argparse
import getpass
from homeassistant.util.yaml import _SECRET_NAMESPACE
REQUIREMENTS = ['keyring>=9.3,<10.0']
def run(args):
"""Handle keyring script."""
parser = argparse.ArgumentParser(
description=("Modify H... | apache-2.0 | Python |
4321c19ba57a65291c6b62c2b844ebdb609c7a5c | Add Python naive version | AlexLusitania/ProjectEuler | Problem001/multiples.py | Problem001/multiples.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author : Alexandre Pais Gomes
# Date : 23/05/2015
# Description : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
limit = 1000
r = 0
... | unlicense | Python | |
d57fab92485e403dd24321ded7090b9c46d61655 | Add sending raw packet example | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | send_packet.py | send_packet.py | from socket import *
def send_packet(src, dst, eth_type, payload, interface = "eth0"):
"""Send raw Ethernet packet on interface."""
assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses
assert(len(eth_type) == 2) # 16-bit ethernet type
s = socket(AF_PACKET, SOCK_RAW)
# From the docs: "For raw pack... | mit | Python | |
f7d7f86231ed0b6ebf8596ba64b939a4cb79079e | Add logging functions. | LegionXI/pydarkstar,AdamGagorik/pydarkstar | pydarkstar/logutils.py | pydarkstar/logutils.py | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import contextlib
import warnings
import logging
import logging.handlers
lfmt = '[%(asctime)s][%(process)5d][%(levelname)-5s]: %(message)s'
dfmt = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(level=logging.ERROR, format=lfmt, datefmt=dfmt)
logging.addLevelName... | mit | Python | |
b1d9027c460acb5507899099a57bc2f0ac494e8b | range of a ser solved | xala3pa/Computer-Science-cs101 | Lesson2/ProblemSet/range_a_set.py | Lesson2/ProblemSet/range_a_set.py | # The range of a set of values is the maximum value minus the minimum
# value. Define a procedure, set_range, which returns the range of three input
# values.
# Hint: the procedure, biggest which you coded in this unit
# might help you with this question. You might also like to find a way to
# code it using some built... | mit | Python | |
dc01f40f20e43bc6c46bb3ff8cf2c51b31850912 | Fix bug 1239380: Fix flake8 errors | jgmize/kuma,jwhitlock/kuma,mozilla/kuma,jgmize/kuma,escattone/kuma,SphinxKnight/kuma,safwanrahman/kuma,jwhitlock/kuma,jgmize/kuma,jgmize/kuma,mozilla/kuma,SphinxKnight/kuma,escattone/kuma,SphinxKnight/kuma,jgmize/kuma,yfdyh000/kuma,mozilla/kuma,Elchi3/kuma,yfdyh000/kuma,ollie314/kuma,escattone/kuma,Elchi3/kuma,Elchi3/k... | kuma/core/tests/test_commands.py | kuma/core/tests/test_commands.py | from django.core.management import call_command, CommandError
from django.utils.six import StringIO
from kuma.users.tests import user, UserTestCase
class TestIHavePowerCommand(UserTestCase):
def test_help(self):
out = StringIO()
with self.assertRaises(CommandError) as commanderror_cm:
... | from django.core.management import call_command, CommandError
from django.utils.six import StringIO
from kuma.users.tests import user, UserTestCase
class TestIHavePowerCommand(UserTestCase):
def test_help(self):
out = StringIO()
with self.assertRaises(CommandError) as commanderror_cm:
... | mpl-2.0 | Python |
9c6b979357d21c9a283707016436b163ccf47c5b | add json schema hook | NCI-GDC/gdc-client,NCI-GDC/gdc-client | bin/hook-jsonschema.py | bin/hook-jsonschema.py | from PyInstaller.hooks.hookutils import collect_data_files
datas = collect_data_files('jsonschema') | apache-2.0 | Python | |
0c1e69af2167292b3e1d03d5d697f1c719b2c1f2 | bump version number | ava-project/sdk,ava-project/sdk | sdk/__init__.py | sdk/__init__.py | __version__ = '0.1.2'
__author__ = 'dorianamouroux'
__description__ = 'Util python functions for AVA project'
__url__ = 'https://github.com/ava-project'
| apache-2.0 | Python | |
5f411b0ce564eba7a4b1f6c07d0d3209d63eef8e | Add basic search by pmcid | tarrow/epmclib | searchbypmid.py | searchbypmid.py | import requests, untangle
pmcid = 'PMC3834665'
epmc_basequeryurl = "http://www.ebi.ac.uk/europepmc/webservices/rest/search"
''' Make query to EuropePMC'''
query = {'query':pmcid,'resulttype':'core'}
r = requests.get(epmc_basequeryurl, params=query)
'''Use untangle to make python structure from xml'''
obj = untangle.... | mit | Python | |
4120399a110c8260da48feeda09191ddb47091c5 | Fix test_client_new for standalone and mongos. | mongodb/mongo-python-driver,brianwrf/mongo-python-driver,aherlihy/mongo-python-driver,bq-xiao/mongo-python-driver,rychipman/mongo-python-driver,macdiesel/mongo-python-driver,gormanb/mongo-python-driver,macdiesel/mongo-python-driver,inspectlabs/mongo-python-driver,aherlihy/mongo-python-driver,ShaneHarvey/mongo-python-dr... | test/test_client_new.py | test/test_client_new.py | # Copyright 2009-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright 2009-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | apache-2.0 | Python |
6f27690262a5de06ee87866a14f0c1411c0d451b | Add tests for globalvars.py | ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector,ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector | test/test_globalvars.py | test/test_globalvars.py | from globalvars import GlobalVars
def test_globalvars():
# Changing values in globalvars.py is fine for debugging, but when
# pushing, there should be made sure that the values are correct.
assert GlobalVars.charcoal_room_id == "11540"
assert GlobalVars.meta_tavern_room_id == "89"
assert GlobalVar... | apache-2.0 | Python | |
03b920d68baeb6a4e614556ba10215f3549040e8 | add new contact recorded | peruana80/python_training | test_add_new_contact.py | test_add_new_contact.py | # -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time, unittest
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class test_add_new_contact... | apache-2.0 | Python | |
9ee6399c52d4969b86d0693a732d35c7ab040da9 | Add web authentication. | SoyM/GK-CAC | WebAuthentication.py | WebAuthentication.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
import cookielib
import socket
localip = socket .gethostbyname(socket .gethostname() )
print localip
account = raw_input(u"账号\n")
password = raw_input(u"密码\n")
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'A... | apache-2.0 | Python | |
7e14d4c4d35ab880eb1a233467151584a8d8f6c3 | Test code for picamera | natewalck/raspberrypi | camera/take_picture.py | camera/take_picture.py | #!/usr/bin/python
import picamera
from time import sleep
def take_picture():
file_name = 'test001.jpg'
with picamera.PiCamera() as camera
camera.vflip = True
camera.start_preview()
time.sleep(2)
camera.capture(file_name)
def main():
take_picture()
if __name__ == '__ma... | apache-2.0 | Python | |
c5dd413c2fce6789a0330b7fa58d31cc4707cb07 | add missing file | BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit | client/python/elveos/feature.py | client/python/elveos/feature.py | from entity import Entity
class Feature(Entity):
pass
| agpl-3.0 | Python | |
a1b7f56982ed265b4e39754ba66d1afb71cf9953 | Create ch07_01_if.py | MurphyWan/Python-first-Practice | ch07_01_if.py | ch07_01_if.py | number = 23
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, bingo!') # New block starts here
print('(but you do not win any prizes!)') # New block ends here
elif guess < number:
print('No, it is a litter higher than that')
# you can do whatever you want in a ... | mit | Python | |
57c09aad6ad8de1fb5bb13d92b69db381f55cdac | Add functions to handle temp directory for download | noahfx/lobster | lobster/filemanager.py | lobster/filemanager.py | import os
import time
TMP_DIR = "/tmp/lobster"
def get_tempdir():
tmp_path = TMP_DIR
if not os.path.isdir(tmp_path):
os.mkdir(tmp_path)
return tmp_path
def get_workingdir():
tmp_dir = get_tempdir()
dir_name = str(int(time.time()))
path = "/".join([tmp_dir, dir_name])
os.mkdir(path... | mit | Python | |
0f92ab8056cb16e0d09686bb45b5ee77e50872f0 | Add tests for cli defaults | hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler | unit_tests/test_command_line_defaults.py | unit_tests/test_command_line_defaults.py | from unit_test_common import execute_csv2_command, initialize_csv2_request, ut_id
import sys
def main(gvar, user_secret):
if not gvar:
gvar = {}
if len(sys.argv) > 1:
initialize_csv2_request(gvar, sys.argv[0], selections=sys.argv[1])
else:
initialize_csv2_request(gva... | apache-2.0 | Python | |
5afbfb347bd0cfef35f4557ee02e3af9d65b88b2 | Add circular_footprint tests | larrybradley/photutils,astropy/photutils | photutils/utils/tests/test_footprints.py | photutils/utils/tests/test_footprints.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the footprints module.
"""
import numpy as np
from numpy.testing import assert_equal
import pytest
from ..footprints import circular_footprint
def test_footprints():
footprint = circular_footprint(1)
result = np.array([[0, 1, 0],
... | bsd-3-clause | Python | |
58ccd5e58e5f7d34547f7a48bd50440580940b5d | Create scrub.py | brainsqueeze/bipolar_osc | scrub.py | scrub.py | from math import *
import numpy as np
import matplotlib.pyplot as plt
import sys
L = 1.5*10**51
FluxTot = L*(10**-1 + 15**-1 + 4*20**-1)
Mu0 = 0.45*10**5
R = 40
deltaR = 0.25
deltaU = sqrt(1 - (10*R**-1)**2)/20
deltaP = 0.2
def fnuE (x):
Le = 4.1*np.power(10.,51.)
Lebar = 4.3*np.power(10.,51.)
Lmu = 7.9*... | mit | Python | |
e824e02d6ad8ef94a8c36a9349c2592d1030f7b8 | add initializemime | silenius/amnesia,silenius/amnesia,silenius/amnesia | amnesia/scripts/initializemime.py | amnesia/scripts/initializemime.py | from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import DBSession
types = {'application', 'audio', 'example', 'image', 'message', 'model',
'multipart', 'text', 'video'}
src = 'www.iana.org'
def main():
pass
#def us... | bsd-2-clause | Python | |
551c14784b48c98e3538a3f3a51130111dc20c24 | Create task_12_50.py | Mariaanisimova/pythonintask | IVTa/2014/ALEKSEEV_I_S/task_12_50.py | IVTa/2014/ALEKSEEV_I_S/task_12_50.py | # Задача 12. Вариант 50
# Разработайте игру "Крестики-нолики".
#(см. М.Доусон Программируем на Python гл. 6).
# Alekseev I.S.
# 20.05.2016
board = list(range(1,10))
def draw_board(board):
print("-------------")
for i in range(3):
print( "|", board[0+i*3], "|", board[1+i*3], "|", board[2+i*3], "|")
... | apache-2.0 | Python | |
7a0de1643230c0b02b9bc89b2311bab12a55b40f | Add page view tests. | birkbeckOLH/annotran,birkbeckOLH/annotran,birkbeckOLH/annotran | annotran/pages/test/views_test.py | annotran/pages/test/views_test.py | # -*- coding: utf-8 -*-
import mock
import pytest
from pyramid import httpexceptions
from annotran.pages import views
_SENTINEL = object()
def _mock_request(feature=None, settings=None, params=None,
authenticated_userid=_SENTINEL, route_url=None, **kwargs):
"""Return a mock Pyramid request obj... | mit | Python | |
5a1b2eda17d30f7268218112e27480b1780eedaa | add information about identifier check | ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study | reading-notes/CorePython/src/id_check.py | reading-notes/CorePython/src/id_check.py | # Copyright (c) 2014 ASMlover. 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 above copyright
# notice, this list ofconditions and the fol... | bsd-2-clause | Python | |
bc128ea235ff3f7172ac198a632c00c71eb01899 | Add standalone server. | techtonik/pydotorg.pypi,techtonik/pydotorg.pypi | standalone.py | standalone.py | #!/usr/bin/python
import config, webui, BaseHTTPServer, urllib
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
config = config.Config("config.ini")
def set_content_type(self, content_type):
self.send_header('Content-Type', content_type)
def run(self):
for scriptname in ('/mir... | bsd-3-clause | Python | |
308ec3422011c9beaed1699cfb96dff6fa2d0c56 | add a same architecture as avg.pool | NeuromorphicProcessorProject/snn_toolbox | ann_architectures/cifar10/cnn_max_pool.py | ann_architectures/cifar10/cnn_max_pool.py | """
Train a (fairly simple) deep CNN on the CIFAR10 small images dataset.
GPU run command:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py
Gets to about 0.5 test loss or 83% accuracy after 65 epochs.
"""
from __future__ import absolute_import
from __future__ import print_function
from ke... | mit | Python | |
4c565f308fb0499830a6a5ec7a62781f07ebcde7 | Add a basic test | menpo/cyrasterize,menpo/cyrasterize,menpo/cyrasterize | cyrasterize/test/basic_tests.py | cyrasterize/test/basic_tests.py | import numpy as np
from cyrasterize import CyRasterizer
from numpy.testing import assert_allclose
def test_basic_random():
c = CyRasterizer(width=100, height=100)
points = np.array([[-1, -1, 0], [1, -1, 0], [1, 1, 0], [-1, 1, 0]])
trilist = np.array([[0, 1, 2], [2, 3, 0]])
colours = np.random.uniform... | bsd-3-clause | Python | |
be041d87dd6c964a650ddcb50d578ee038858650 | Create Colorify.py | blackpan2/PyGrade | src/Colorify.py | src/Colorify.py | _author__ = 'George Herde'
def grey(string):
return "\033[1;30m" + string + "\033[1;m"
def red(string):
return "\033[1;31m" + string + "\033[1;m"
def green(string):
return "\033[1;32m" + string + "\033[1;m"
def yellow(string):
return "\033[1;33m" + string + "\033[1;m"
def blue(string):
ret... | apache-2.0 | Python | |
841f5a02e879b133b48bbdafe95f418b9c091ac9 | Improve SVR recording interface | bwc126/MLND-Subvocal | svr_record.py | svr_record.py | from tkinter import *
from pcf8591read import *
root = Tk()
def testytesty():
print ('oh look we used a callback')
words = ['dusty','march','direful','complete','superb','poised','wait','quaint','save','copy','interest','separate','bright','utter','bored','nondescript','license','vest','dance','money','languid',... | mit | Python | |
432d9e9d2e758c1c695422f89561171e0c0973a9 | add to consolidate backend common test codes | ssato/python-anyconfig,ssato/python-anyconfig | tests/backend/common.py | tests/backend/common.py | #
# Copyright (C) 2012 - 2017 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring
from __future__ import absolute_import
import copy
import os.path
import unittest
import tests.common
from anyconfig.compat import OrderedDict
CNF_0 = OrderedDict((("DEFAULT", OrderedDict((("a", "0")... | mit | Python | |
665307831f5c6114459043b64696ca81d1ca33ac | Test for UTF-16 keys | couchbase/couchbase-python-client,mnunberg/couchbase-python-client,couchbase/couchbase-python-client,mnunberg/couchbase-python-client | tests/test_encodings.py | tests/test_encodings.py | from couchbase import FMT_PLAIN
from couchbase.libcouchbase import Connection
from tests.base import CouchbaseTestCase
import sys
class ConnectionEncodingTest(CouchbaseTestCase):
def setUp(self):
super(ConnectionEncodingTest, self).setUp()
self.cb = Connection(self.host, self.port, self.username,
... | apache-2.0 | Python | |
3e52dcc7c4af0ab7208abebdfb59a079ee9b764b | Add tests for the IATI wiki | IATI/IATI-Website-Tests | tests/test_iati_wiki.py | tests/test_iati_wiki.py | import pytest
from web_test_base import *
class TestIATIWiki(WebTestBase):
urls_to_get = [
"http://wiki.archive.iatistandard.org/"
]
def test_locate_links(self, loaded_request):
"""
Tests that each page contains links to the defined URLs.
"""
result = self._get_link... | mit | Python | |
4c46aee070f26b13ec78aedfa74671f2b937d4dd | Add custom builders (for python extensions, mainly) | cournape/numscons,cournape/numscons,cournape/numscons | numscons/core/custom_builders.py | numscons/core/custom_builders.py | from os.path import join as pjoin
def NumpySharedLibrary(env, target, source, *args, **kw):
"""This builder is the same than SharedLibrary, except for the fact that it
takes into account build dir info passed by distutils, and put the target at
the right location in distutils build directory for correct in... | bsd-3-clause | Python | |
6f615e6dc9550daa639a316752cdc1123777c0b3 | Add script that compares output of pyreaper with REAPER | voicesauce/opensauce-python,voicesauce/opensauce-python,voicesauce/opensauce-python | tools/compare_reaper.py | tools/compare_reaper.py | import os
import sys
import glob
import numpy as np
import matplotlib.pyplot as plt
from subprocess import call
from scipy.io import wavfile
from pyreaper import reaper
def main(wav_dir, reaper_path):
"""Compare output from pyreaper with original REAPER
"""
# Find all wavfiles
wav_files = glob.glob(o... | apache-2.0 | Python | |
bd5978ab99bde08406dbe0799c3e7fb5db4002d9 | Add invoker class | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt | orges/parallelization/invoker.py | orges/parallelization/invoker.py | from orges.args import call
class Invoker(object):
def __init__(self, resources):
pass
def subinvoker(resources):
pass
def invoke(f, args, **vargs):
# ret = call(f, args)
# caller.on_result(args, **vargs)
def wait():
pass
# Warten bis für jeden Aufruf ... | bsd-3-clause | Python | |
6004b57b924a19b0e3a8c3ce60c117eda365c9c7 | Add script that automatically adds import statements to source | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | dev_tools/src/d1_dev/src-insert-import.py | dev_tools/src/d1_dev/src-insert-import.py | #!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... | apache-2.0 | Python | |
85829b614f0830b72cd5b10478113583162113c2 | Add tests | 5monkeys/django-enumfield,lamby/django-enumfield,lamby/django-enumfield,fcurella/django-enumfield,jessamynsmith/django-enumfield,joar/django-enumfield | django_enumfield/tests/test_validators.py | django_enumfield/tests/test_validators.py | import unittest
from django_enumfield.tests.models import BeerStyle
from django_enumfield.validators import validate_available_choice
from django_enumfield.exceptions import InvalidStatusOperationError
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
"""Test passing a va... | mit | Python | |
6082025098d93dcae2726068e61bce194f82b845 | Bump version to 1.2 | leasual/nogotofail,google/nogotofail,digideskio/nogotofail,joshcooper/nogotofail,mkenne11/nogotofail-pii,digideskio/nogotofail,google/nogotofail,mkenne11/nogotofail,mkenne11/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,leasual/nogotofail | nogotofail/__init__.py | nogotofail/__init__.py | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | apache-2.0 | Python |
000f61d079d110e0cc16000994906b67a024a260 | add util for context lookup | lotabout/pymustache | src/mustache.py | src/mustache.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#==============================================================================
# Context lookup.
# Mustache uses javascript's prototype like lookup for variables.
# A context is just a dict, and we use a list of contexts to represent the
# stack
# lookup('x', ({'x': 10... | mit | Python | |
12b0c4b079cc21e659c71cee6de5e7773900d717 | Add a secrets file to make envvars available to tests | nestauk/inet | tests/secrets.py | tests/secrets.py | # -*- coding: utf-8 -*-
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ['OPS_KEY']
OPS_SECRET = os.environ['OPS_SECRET']
| mit | Python | |
3d8e524186717ad71955ba40739435699cb12f91 | Add benchmark for SelectionScene | vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2 | src/mcedit2/test/time_selectionrender.py | src/mcedit2/test/time_selectionrender.py | """
time_selectionrender
"""
from __future__ import absolute_import, division, print_function
import logging
import timeit
from PySide import QtGui
from mcedit2.rendering.selection import SelectionScene
from mceditlib.selection import ShapedSelection, SphereShape
from mceditlib.selection import BoundingBox
log = l... | bsd-3-clause | Python | |
7479439a7a9bbb46dfd74fe95a251d8dfd9dfa62 | Create PostgreSQL.py | emeric254/gala-stri-website,emeric254/gala-stri-website,emeric254/gala-stri-website | Tools/PostgreSQL.py | Tools/PostgreSQL.py | # -*- coding: utf-8 -*-
import os
import logging
import psycopg2
logger = logging.getLogger(__name__)
def get_conf():
db_host = '127.0.0.1'
if 'OPENSHIFT_POSTGRESQL_DB_HOST' in os.environ:
db_host = os.environ['OPENSHIFT_POSTGRESQL_DB_HOST']
db_port = '5432'
if 'OPENSHIFT_POSTGRESQL_DB_PORT'... | mit | Python | |
85b5ea3d5635d47160b0bcf7e8efe693967edf07 | Add testRunner runner.py | oldani/HtmlTestRunner,oldani/HtmlTestRunner | HtmlTestRunner/runner.py | HtmlTestRunner/runner.py | import sys
import time
from datetime import datetime
from unittest import TextTestRunner
from .result import _HtmlTestResult
UTF8 = "UTF-8"
class HTMLTestRunner(TextTestRunner):
"""" A test runner class that output the results. """
def __init__(self, output, verbosity=2, stream=sys.stderr,
... | mit | Python | |
de3fd223ce1b9445a54602c2dfb04ae6fe05c3e0 | add related-view | chronossc/django-grappelli-svn,chronossc/django-grappelli-svn,codysoyland/django-grappelli,codysoyland/django-grappelli | views/related.py | views/related.py | # -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.db import models
def related_lookup(request):
if request.method == 'GET':
if request.GET.has_key('object_id') and request.GET.has_key('app_label') and request.GET.has_key('model_name'):
object_id = request.GET.get('... | bsd-3-clause | Python | |
72e75db6b2aa3471c59b72a8028d1b61ab603b14 | Create quiz.py | gaurav61/MIT6.00x | quiz.py | quiz.py | # PROBLEM 1 :
def isPalindrome(aString):
if len(aString)<=1:
return True
return aString[0]==aString[-1] and isPalindrome(aString[1:-1])
# PROBLEM 2 :
def dotProduct(listA, listB):
pro=0
for i in range(0,len(listA)):
pro=pro+(listA[i]*listB[i])
return pro
# PROBLEM ... | mit | Python | |
ddc52e704ec3435070b0fb15cecd6bd0a88a092c | split model into encoder, decoder, encoder_layer, decoder_layer | hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping | py/pytorch/testgrad.py | py/pytorch/testgrad.py | import torch
from torch import autograd
torch.manual_seed(123)
a = torch.rand(3, 2)
print('a', a)
# a_var = autograd.Variable(a)
a_var = autograd.Variable(a, requires_grad=True)
print('a_var', a_var)
print('a_var.creator', a_var.creator)
print('a_var.grad', a_var.grad)
print('a_var.data', a_var.data)
print('a_var.req... | apache-2.0 | Python | |
46ae8097f12a24a8d7533d7602e740b5dedd3f48 | add utils | shymonk/django-datatable,shymonk/django-datatable,arambadk/django-datatable,arambadk/django-datatable,arambadk/django-datatable,shymonk/django-datatable | table/utils.py | table/utils.py | #!/usr/bin/env python
# coding: utf-8
class Accessor(str):
""" A string describing a path from one object to another via attribute/index
accesses. For convenience, the class has an alias `.A` to allow for more concise code.
Relations are separated by a "." character.
"""
SEPARATOR = '.'
... | mit | Python | |
935e9fc130657ac9bcfab00ed8103ff00a06bb93 | Update my-calendar-i.py | tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode | Python/my-calendar-i.py | Python/my-calendar-i.py | # Time: O(nlogn) on average, O(n^2) on worst case
# Space: O(n)
# Implement a MyCalendar class to store your events.
# A new event can be added if adding the event will not cause a double booking.
#
# Your class will have the method, book(int start, int end).
# Formally, this represents a booking on the half open int... | # Time: O(n^2)
# Space: O(n)
# Implement a MyCalendar class to store your events.
# A new event can be added if adding the event will not cause a double booking.
#
# Your class will have the method, book(int start, int end).
# Formally, this represents a booking on the half open interval [start, end),
# the range of ... | mit | Python |
82006858808a0a3b46e7f1ce7bb9a22303b60258 | implement tfagent testing behaviour | xzhang2016/tfagent | test/__init__.py | test/__init__.py | bsd-2-clause | Python | ||
fdf578d3285513d41694bd5f4df21f5cf2785570 | add models to admin | texastribune/the-dp,texastribune/the-dp,texastribune/the-dp,texastribune/the-dp | thedp/admin.py | thedp/admin.py | from django.contrib import admin
from .models import Institution, System
class InstitutionAdmin(admin.ModelAdmin):
list_display = ('name', 'ipeds_id', 'ope_id')
list_filter = ('institution_type',)
list_editable = ('ipeds_id', 'ope_id')
admin.site.register(Institution, InstitutionAdmin)
admin.site.registe... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.