commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
e6f7c6657485b33760e2522afb6b25ba5ed405fd | pyramid_zipkin/zipkin.py | pyramid_zipkin/zipkin.py | # -*- coding: utf-8 -*-
from py_zipkin.zipkin import create_http_headers_for_new_span \
as create_headers_for_new_span # pragma: no cover
| # -*- coding: utf-8 -*-
from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover
# Backwards compatibility for places where pyramid_zipkin is unpinned
create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
| Split import into 2 lines to make flake8 happy | Split import into 2 lines to make flake8 happy
| Python | apache-2.0 | bplotnick/pyramid_zipkin,Yelp/pyramid_zipkin |
53bed4837805fa304153622689abb7c4c581ec73 | registration/__init__.py | registration/__init__.py | from django.utils.version import get_version as django_get_version
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
return django_get_version(VERSION) # pragma: no cover
| VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems. | Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
| Python | bsd-3-clause | Geffersonvivan/django-registration,ei-grad/django-registration,nikolas/django-registration,kinsights/django-registration,alawnchen/django-registration,Geffersonvivan/django-registration,wda-hb/test,arpitremarkable/django-registration,yorkedork/django-registration,maitho/django-registration,percipient/django-registratio... |
ce3fb7643e5c75a1f5fdae77a6667df407cb55b1 | interface.py | interface.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 13:53:47 2016
@author: mela
"""
| # -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 13:53:47 2016
@author: mela
"""
print(adfadsfad);
| Test commit on new branch, change to username and email. | Test commit on new branch, change to username and email.
| Python | mit | akmelkonian/city-in-purple |
69fc2eccaa88189fd0de86d11206fa24d1508819 | tools/np_suppressions.py | tools/np_suppressions.py | suppressions = [
[ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be superceded by
# __New_PyArray_Std, which is exercised by the test framework.
[ ".*/multiarray/calculation\.", "PyArray_Std" ],
# PyCapsule_Check is declared in a header, an... | suppressions = [
# This one cannot be covered by any Python language test because there is
# no code pathway to it. But it is part of the C API, so must not be
# excised from the code.
[ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be sup... | Add documentation on one assertion, convert RE's to raw strings. | Add documentation on one assertion, convert RE's to raw strings.
| Python | bsd-3-clause | teoliphant/numpy-refactor,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor |
e3312c773e9e3ac9b939bc3e0ca6a872dae5cdef | pre_commit_hooks/trailing_whitespace_fixer.py | pre_commit_hooks/trailing_whitespace_fixer.py | from __future__ import print_function
import argparse
import sys
from plumbum import local
from pre_commit_hooks.util import entry
@entry
def fix_trailing_whitespace(argv):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
args = parser.parse_args(ar... | from __future__ import print_function
import argparse
import fileinput
import sys
from plumbum import local
from pre_commit_hooks.util import entry
def _fix_file(filename):
for line in fileinput.input([filename], inplace=True):
print(line.rstrip())
@entry
def fix_trailing_whitespace(argv):
parser ... | Use fileinput instead of sed. | Use fileinput instead of sed.
| Python | mit | Coverfox/pre-commit-hooks,Harwood/pre-commit-hooks,bgschiller/pre-commit-hooks,pre-commit/pre-commit-hooks,jordant/pre-commit-hooks,jordant/pre-commit-hooks,chriskuehl/pre-commit-hooks,dupuy/pre-commit-hooks,arahayrabedian/pre-commit-hooks |
32951dda5a46487a485c949a07f457ae537f07f2 | src/encoded/upgrade/bismark_quality_metric.py | src/encoded/upgrade/bismark_quality_metric.py | from contentbase import (
ROOT,
upgrade_step,
)
@upgrade_step('bismark_quality_metric', '1', '2')
def bismark_quality_metric_1_2(value, system):
# http://redmine.encodedcc.org/issues/3114
root = system['registry'][ROOT]
step_run = root.get_by_uuid(value['step_run'])
value['quality_metric_of'] =... | from contentbase import (
CONNECTION,
upgrade_step,
)
@upgrade_step('bismark_quality_metric', '1', '2')
def bismark_quality_metric_1_2(value, system):
# http://redmine.encodedcc.org/issues/3114
conn = system['registry'][CONNECTION]
step_run = conn.get_by_uuid(value['step_run'])
output_files = ... | Change upgrade step to not use rev link. | Change upgrade step to not use rev link.
| Python | mit | 4dn-dcic/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,T2DREAM/t2dream-portal,hms-dbmi/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,ENCODE-DCC/encoded,hms-dbmi/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/snovault,E... |
b6a66fa8ecdfbdd196c1d2a776c85ed9b3c1c06d | test/test_configuration.py | test/test_configuration.py | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | FIX test for Windows platform. | FIX test for Windows platform.
| Python | bsd-2-clause | hugeinc/behave-parallel |
8c7de9c87412725c325f849f995df3010f36d5b2 | openmm/run_test.py | openmm/run_test.py | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.ver... | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.ver... | Update openmm test script to check appropriate version numbers for beta | Update openmm test script to check appropriate version numbers for beta
| Python | mit | peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,peastman/conda-recipes,swails/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,jchodera/conda-recipes,p... |
4026ee18f512d445a57413b65b7a29f965ededf4 | domino/utils/jupyter.py | domino/utils/jupyter.py | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init():
"""
Assuming a project is built ... | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init(path=os.path.pardir):
"""
Assuming ... | Add path parameter to notebook_init() | Add path parameter to notebook_init()
| Python | mit | aparafita/domino |
8a4897fc9cb0192ed91f4e63dbe2da37f4d3ec69 | xerox/__init__.py | xerox/__init__.py | from .core import *
import sys
def main():
""" Entry point for cli. """
if sys.argv[1:]: # called with input arguments
copy(' '.join(sys.argv[1:]))
elif not sys.stdin.isatty(): # piped in input
copy('\n'.join(sys.stdin.readlines()))
else: # paste output
print(paste())
| from .core import *
import sys
import os
def main():
""" Entry point for cli. """
if sys.argv[1:]: # called with input arguments
copy(' '.join(sys.argv[1:]))
elif not sys.stdin.isatty(): # piped in input
copy(''.join(sys.stdin.readlines()).rstrip(os.linesep))
else: # paste output
... | Join lines without newline and remove trailing newline | Join lines without newline and remove trailing newline
| Python | mit | kennethreitz/xerox |
61f06da13bef77f576a0c2dea77febf0d2d4b6fb | subl.py | subl.py | from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
... | from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
... | Allow autocomplete on non-persisted swift files | Allow autocomplete on non-persisted swift files
| Python | mit | Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl |
8178bf161d39976405690d68d9ffe6c4dfd9d705 | web/view_athena/views.py | web/view_athena/views.py | from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
... | from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
... | Update 'search_term' functon. Add 'match_phrase' function. | Update 'search_term' functon. Add 'match_phrase' function.
| Python | mit | pattyvader/athena,pattyvader/athena,pattyvader/athena |
82954f3df7e3b8f0a4cb921e40f351938451221d | cd/lambdas/pipeline-fail-notification/lambda_function.py | cd/lambdas/pipeline-fail-notification/lambda_function.py | # Invoked by: CloudWatch Events
# Returns: Error or status message
#
# Triggered periodically to check if the CD CodePipeline has failed, and
# publishes a notification
import boto3
import traceback
import json
import os
from datetime import datetime, timedelta
code_pipeline = boto3.client('codepipeline')
sns = boto3... | # Invoked by: CloudWatch Events
# Returns: Error or status message
#
# Triggered periodically to check if the CD CodePipeline has failed, and
# publishes a notification
import boto3
import traceback
import json
import os
from datetime import datetime, timedelta
code_pipeline = boto3.client('codepipeline')
sns = boto3... | Fix CD fail lambda python | Fix CD fail lambda python
| Python | mit | PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure |
3c603b177713e8266eb4881d5d325c148d3fb6c1 | __init__.py | __init__.py | # -*- coding: utf-8 -*-
__about__ = """
This project comes with the bare minimum set of applications and templates
to get you started. It includes no extra tabs, only the profile and notices
tabs are included by default. From here you can add any extra functionality
and applications that you would like.
"""
| # -*- coding: utf-8 -*-
__about__ = """
Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects.
"""
| Update to be about Django, not 2010-era Pinax. | Update to be about Django, not 2010-era Pinax. | Python | mit | pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages |
db078d7332acf3032346b6642061c6f72c5dce1b | wooey/migrations/0028_add_script_subparser.py | wooey/migrations/0028_add_script_subparser.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
def createParsers(apps, schema_editor):
ScriptParameter = apps.get_model('wooey', 'ScriptParameter')... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
... | Remove runpython to create subparers in 0028 | Remove runpython to create subparers in 0028
| Python | bsd-3-clause | wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey |
a9059f075bc1bb48422a3aba564a38071b1acf9f | selectable/forms/base.py | selectable/forms/base.py | from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
... | from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
... | Move page cleaning logic to the form. | Move page cleaning logic to the form.
--HG--
branch : result-refactor
| Python | bsd-2-clause | mlavin/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable |
e4509d98e1aeb8a053bb4589eb6806d3e554af5e | topics/lemmatize_folder.py | topics/lemmatize_folder.py | import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
... | import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
... | Add possibility to lemmatize a folder or a file | Add possibility to lemmatize a folder or a file
| Python | mit | HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015 |
793dd2c1ec3d503b8d4325d44bd34b121273144c | jesusmtnez/python/koans/koans/triangle.py | jesusmtnez/python/koans/koans/triangle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | Complete 'About Triangle Project' koans | [Python] Complete 'About Triangle Project' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
31b70c6b08eedc1773d4993e9d9d420d84197b49 | corehq/apps/domain/__init__.py | corehq/apps/domain/__init__.py | from django.conf import settings
from corehq.preindex import ExtraPreindexPlugin
ExtraPreindexPlugin.register('domain', __file__, (
settings.NEW_DOMAINS_DB,
settings.NEW_USERS_GROUPS_DB,
settings.NEW_FIXTURES_DB,
'meta',
))
SHARED_DOMAIN = "<shared>"
UNKNOWN_DOMAIN = "<unknown>"
| SHARED_DOMAIN = "<shared>"
UNKNOWN_DOMAIN = "<unknown>"
| Remove domain design doc from irrelevant couch dbs | Remove domain design doc from irrelevant couch dbs
It used to contain views that were relevant to users, fixtures, and meta dbs,
but these have since been removed. Currently all views in the domain design doc
emit absolutely nothing in those domains
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
b8594bbe5375e20503d641dde8c4c0ef2cd85d3e | spec_cleaner/fileutils.py | spec_cleaner/fileutils.py | # vim: set ts=4 sw=4 et: coding=UTF-8
import os
from .rpmexception import RpmException
class FileUtils(object):
"""
Class working with file operations.
Read/write..
"""
# file variable
f = None
def open_datafile(self, name):
"""
Function to open data files.
Use... | # vim: set ts=4 sw=4 et: coding=UTF-8
import os
from .rpmexception import RpmException
class FileUtils(object):
"""
Class working with file operations.
Read/write..
"""
# file variable
f = None
def open_datafile(self, name):
"""
Function to open data files.
Use... | Check an extra possible data dir when installing in a venv | Check an extra possible data dir when installing in a venv
When installing spec-cleaner in a virtual env, the data files
(i.e. "excludes-bracketing.txt") are available in a different
directory. Also check this directory.
Fixes #128
| Python | bsd-3-clause | plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner |
e0707619ca9192544a912b91993f0de5c507d7d7 | stutuz/__init__.py | stutuz/__init__.py | #-*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flask... | #-*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flask... | Make a default empty users list | Make a default empty users list
| Python | bsd-2-clause | dag/stutuz |
295285a0a13207dac276da6e3b41e2057a7efee8 | test/tests/constant_damper_test/constant_damper_test.py | test/tests/constant_damper_test/constant_damper_test.py | import tools
def testdirichlet(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
| import tools
def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
# Make sure the damping causes 8 NL steps
def testverifydamping(dofs=0, np=0, n_threads=0):
tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')... | Verify additional steps in damping problem | Verify additional steps in damping problem
r4199
| Python | lgpl-2.1 | jinmm1992/moose,stimpsonsg/moose,andrsd/moose,mellis13/moose,jinmm1992/moose,permcody/moose,liuwenf/moose,harterj/moose,jhbradley/moose,nuclear-wizard/moose,jhbradley/moose,adamLange/moose,roystgnr/moose,SudiptaBiswas/moose,katyhuff/moose,harterj/moose,roystgnr/moose,zzyfisherman/moose,roystgnr/moose,jasondhales/moose,... |
dab9d4e071bef5e0a771fa5a0eb7be81819bb68c | user_profile/urls.py | user_profile/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.ViewView.as_view(), name='profile_own_view'),
url(r'^edit/', views.EditView.as_view(), name='profile_edit'),
url(r'^view/', views.ViewView.as_view(), name='profile_own_view'),
... | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.ViewView.as_view(), name='profile_own_view'),
url(r'^edit/', views.EditView.as_view(), name='profile_edit'),
url(r'^view/', views.ViewView.as_view(), name='profile_own_view'),
... | Fix user name url pattern | Fix user name url pattern
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys |
bb2249998637c8c56cb8b7cd119c1d8d132e522e | viewer_examples/plugins/canny_simple.py | viewer_examples/plugins/canny_simple.py | from skimage import data
from skimage.filter import canny
from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.overlayplugin import OverlayPlugin
image = data.camera()
# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = Image... | from skimage import data
from skimage.filter import canny
from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.widgets.history import SaveButtons
from skimage.viewer.plugins.overlayplugin import OverlayPlugin
image = data.camera()
# You can create a UI for a filter ju... | Add save buttons to viewer example. | Add save buttons to viewer example.
| Python | bsd-3-clause | jwiggins/scikit-image,WarrenWeckesser/scikits-image,rjeli/scikit-image,almarklein/scikit-image,michaelaye/scikit-image,newville/scikit-image,Britefury/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,chintak/scikit-image,almark... |
7cf867e9ee7a3764b3168cd9671f6de0d0b1b090 | numpy/distutils/command/install_clib.py | numpy/distutils/command/install_clib.py | import os
from distutils.core import Command
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
self.outfiles = []
def finalize_o... | import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
... | Move import at the top of module. | Move import at the top of module.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,illume... |
7ca3b7f294b954dcd95880c938709240b268766f | test_url_runner.py | test_url_runner.py | #!/usr/bin/env python
import unittest
# This line is important so flake8 must ignore this one
from app import views # flake8: noqa
from app import mulungwishi_app
class URLTest(unittest.TestCase):
def setUp(self):
self.client = mulungwishi_app.test_client()
self.client.testing = True
def te... | #!/usr/bin/env python
import unittest
# This line is important so flake8 must ignore this one
from app import views # flake8: noqa
from app import mulungwishi_app
class URLTest(unittest.TestCase):
def setUp(self):
self.client = mulungwishi_app.test_client()
self.client.testing = True
def te... | Add test for empty content string on query | Add test for empty content string on query
| Python | mit | engagespark/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/public-webhooks,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/mulungwishi-webhook |
fdc7f2c88e72af6e6493a70dad7673c9dbfcbde2 | opps/images/templatetags/images_tags.py | opps/images/templatetags/images_tags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | Remove halign and valign on image_obj | Remove halign and valign on image_obj
| Python | mit | opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps |
7aca9e8cb526e721b88958ddfeac492e667041c3 | breakpad.py | breakpad.py | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Add a check so non-google employee don't send crash dumps. | Add a check so non-google employee don't send crash dumps.
Add a warning message in case the check ever fail.
Review URL: http://codereview.chromium.org/460044
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | smikes/depot_tools,kromain/chromium-tools,coreos/depot_tools,Neozaru/depot_tools,G-P-S/depot_tools,fracting/depot_tools,kaiix/depot_tools,liaorubei/depot_tools,withtone/depot_tools,smikes/depot_tools,npe9/depot_tools,Neozaru/depot_tools,Phonebooth/depot_tools,cybertk/depot_tools,smikes/depot_tools,duanwujie/depot_tools... |
a37288cb47ea7b5d547c7ed6b7b5aa28a6d9b583 | workflowmax/api.py | workflowmax/api.py | from .endpoints import ENDPOINTS
from .managers import Manager
class WorkflowMax:
"""An ORM-like interface to the WorkflowMax API"""
def __init__(self, credentials):
self.credentials = credentials
for k, v in ENDPOINTS.items():
setattr(self, v['plural'], Manager(k, credentials))
... | from .credentials import Credentials
from .endpoints import ENDPOINTS
from .managers import Manager
class WorkflowMax:
"""An ORM-like interface to the WorkflowMax API"""
def __init__(self, credentials):
if not isinstance(credentials, Credentials):
raise TypeError(
'Expecte... | Check credentials; sort repr output | Check credentials; sort repr output
| Python | bsd-3-clause | ABASystems/pyworkflowmax |
190463fb4538654a62b440fc92041383f8b15957 | helusers/migrations/0001_add_ad_groups.py | helusers/migrations/0001_add_ad_groups.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
oper... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
oper... | Fix migration for model verbose name changes | Fix migration for model verbose name changes
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers |
083a8d4f301da2ad665a3fefd13a4381417b1205 | imageutils/normalization/tests/test_ui.py | imageutils/normalization/tests/test_ui.py | import numpy as np
from numpy.testing import assert_allclose
from ..ui import scale_image
DATA = np.array([0, 1., 2.])
DATASCL = 0.5 * DATA
class TestImageScaling(object):
def test_linear(self):
"""Test linear scaling."""
img = scale_image(DATA, scale='linear')
assert_allclose(img, ... | import numpy as np
from numpy.testing import assert_allclose
from ..ui import scale_image
DATA = np.array([0, 1., 2.])
DATASCL = 0.5 * DATA
class TestImageScaling(object):
def test_linear(self):
"""Test linear scaling."""
img = scale_image(DATA, scale='linear')
assert_allclose(img, DATA... | Add test for asinh in scale_image | Add test for asinh in scale_image
| Python | bsd-3-clause | mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,astropy/astropy,tbabej/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy,stargaser/astropy,dhomeier/astropy,dhomeier/astropy,MSeifert04/astropy,kelle/astropy,saimn/astropy,lpsinger/astropy,DougBurke/astropy,DougBurke/astropy,kelle/astropy,mhvk/a... |
e94ab19902cebff55c2aead9697423c9c94e478f | scripts/indices.py | scripts/indices.py | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['nodelog'].create_index([
('__backrefs.logged.node.logs', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('us... | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),... | Remove index on field that no longer exists | Remove index on field that no longer exists
[skip ci]
| Python | apache-2.0 | samchrisinger/osf.io,Johnetordoff/osf.io,hmoco/osf.io,crcresearch/osf.io,wearpants/osf.io,Nesiehr/osf.io,SSJohns/osf.io,amyshi188/osf.io,erinspace/osf.io,acshi/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,doublebits/osf.io,hmoco/osf.io,chrisseto/osf.io,SSJohns/osf.io... |
4e7fb558ba6411a33e0e1a2feeffad4d8647e17d | scipy/fftpack/__init__.py | scipy/fftpack/__init__.py | #
# fftpack - Discrete Fourier Transform algorithms.
#
# Created: Pearu Peterson, August,September 2002
from info import __all__,__doc__
from fftpack_version import fftpack_version as __version__
from basic import *
from pseudo_diffs import *
from helper import *
from numpy.dual import register_func
for k in ['fft'... | #
# fftpack - Discrete Fourier Transform algorithms.
#
# Created: Pearu Peterson, August,September 2002
from info import __all__,__doc__
from fftpack_version import fftpack_version as __version__
from basic import *
from pseudo_diffs import *
from helper import *
from numpy.dual import register_func
for k in ['fft'... | Add dct and idct in scipy.fftpack namespace. | Add dct and idct in scipy.fftpack namespace.
| Python | bsd-3-clause | felipebetancur/scipy,piyush0609/scipy,mgaitan/scipy,Eric89GXL/scipy,vanpact/scipy,pschella/scipy,piyush0609/scipy,arokem/scipy,njwilson23/scipy,vberaudi/scipy,grlee77/scipy,minhlongdo/scipy,ales-erjavec/scipy,argriffing/scipy,rgommers/scipy,maniteja123/scipy,ilayn/scipy,endolith/scipy,endolith/scipy,petebachant/scipy,z... |
ad934e49a43a8340af9d52bbac86bede45d0e84d | aero/adapters/brew.py | aero/adapters/brew.py | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Err... | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Err... | Use aero info instead for caching info | Use aero info instead for caching info
Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.
| Python | bsd-3-clause | Aeronautics/aero |
42d1ac59a1e35d8efd4785939696adbdbf39e1d2 | alg_insertion_sort.py | alg_insertion_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
"""
gen = ((i, v) for i, v in enumerate(a_list) if i > 0)
for (i, v) in gen:
key = i
while... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
Although its complexity is bigger than the ones with O(n*logn),
one advantage is the sorting happens in plac... | Revise docstring by adding advantage | Revise docstring by adding advantage
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
2fdb78366fd8e785ec1c613fa4d2f87064217101 | organizer/views.py | organizer/views.py | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(c... | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(c... | Tag Detail: load and render template. | Ch05: Tag Detail: load and render template.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
b1242e9f84afb331f4a3426abeba8e5d27a563c7 | wafer/talks/admin.py | wafer/talks/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from wafer.talks.models import TalkType, Talk, TalkUrl
class ScheduleListFilter(admin.SimpleListFilter):
title = _('in schedule')
parameter_name = 'schedule'
def lookups(self, request, model_admin):
return (
... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from wafer.talks.models import TalkType, Talk, TalkUrl
class ScheduleListFilter(admin.SimpleListFilter):
title = _('in schedule')
parameter_name = 'schedule'
def lookups(self, request, model_admin):
return (
... | Fix logic error in schedule filter | Fix logic error in schedule filter
| Python | isc | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer |
40dc1250bf73b54dfcf04c7a82c452a731aa363c | tests/unit/blocks/test_two_column_layout_block.py | tests/unit/blocks/test_two_column_layout_block.py | import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumn... | import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumn... | Fix mock of request for block rendering | Fix mock of request for block rendering
| Python | bsd-3-clause | socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages |
c18bcd5af7e0b1506ca28cd33a3c939efee80d00 | openfisca_web_api/loader/entities.py | openfisca_web_api/loader/entities.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
re... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
re... | Make variable names more explicit | Make variable names more explicit
| Python | agpl-3.0 | openfisca/openfisca-core,openfisca/openfisca-core |
2c3c52a2ecdb4271cea4e8ec31410ef48be3c728 | admin/manage.py | admin/manage.py | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... | Add method to create a normal user | Add method to create a normal user
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io |
375c55a085dce451146a10b66b3c2d54a9919ed4 | pipelines/toast_example_dist.py | pipelines/toast_example_dist.py |
import toast
# Split COMM_WORLD into groups of 4 processes each
cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4)
# Create the distributed data object
dd = toast.Data(comm=cm)
# Each process group appends some observations.
# For this example, each observation is going to have the same
# number of samples, and the... |
import mpi4py.MPI as MPI
import toast
# Split COMM_WORLD into groups of 4 processes each
cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4)
# Create the distributed data object
dd = toast.Data(comm=cm)
# Each process group appends some observations.
# For this example, each observation is going to have the same
# ... | Fix typo, even though this example is not used for anything. | Fix typo, even though this example is not used for anything.
| Python | bsd-2-clause | tskisner/pytoast,tskisner/pytoast |
f5d07cbefa185d88cdc1bddc4338d6e0ef1e2648 | porick/lib/auth.py | porick/lib/auth.py | import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == us... | import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == us... | Clear cookies if someone's got dodgy cookie info | Clear cookies if someone's got dodgy cookie info
| Python | apache-2.0 | kopf/porick,kopf/porick,kopf/porick |
8ab4b4be97ca026946b30cba7fce64bb30edd28d | fskintra.py | fskintra.py | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... | Use config.log for print added in last commit | Use config.log for print added in last commit
| Python | bsd-2-clause | bennyslbs/fskintra |
e21ca71d5bf19ec0feaab9dbf8caf25173152aec | projects/models.py | projects/models.py | # -*- encoding:utf-8 -*-
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Р... | # -*- encoding:utf-8 -*-
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Р... | Rename the date field related to the project status | Rename the date field related to the project status
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
c9b97f6d1148378d1ba7189a1838ea03e240de40 | pycron/__init__.py | pycron/__init__.py | from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
... | from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
... | Add parsing for list of numbers. | Add parsing for list of numbers.
| Python | mit | kipe/pycron |
2c09716430f90f8bac00ff5a1490693578960495 | q_and_a/apps/questions/api/resources.py | q_and_a/apps/questions/api/resources.py | from tastypie.resources import ModelResource
from questions.models import Answer
class AnswerResource(ModelResource):
class Meta:
queryset = Answer.objects.all()
allowed_methods = ['get']
| import json
from tastypie.resources import ModelResource
from questions.models import Answer
from django.core.serializers.json import DjangoJSONEncoder
from tastypie.serializers import Serializer
# From the Tastypie Cookbook: Pretty-printed JSON Serialization
# http://django-tastypie.readthedocs.org/en/latest/cookbook... | Switch to pretty printing JSON for the API. | Switch to pretty printing JSON for the API.
| Python | bsd-3-clause | DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions |
02ab421105754e6ec258bc7c48b794bcb8ad95ec | HOME/.ipython/profile_default/ipython_config.py | HOME/.ipython/profile_default/ipython_config.py | c.TerminalIPythonApp.display_banner = False
c.TerminalInteractiveShell.confirm_exit = False
c.TerminalInteractiveShell.highlighting_style = "monokai"
c.TerminalInteractiveShell.term_title = False
| c.TerminalIPythonApp.display_banner = False
c.TerminalInteractiveShell.confirm_exit = False
c.TerminalInteractiveShell.highlighting_style = "monokai"
c.TerminalInteractiveShell.term_title = False
import logging
logging.getLogger('parso').level = logging.WARN
| Fix spammy logging during IPython tab complete | Fix spammy logging during IPython tab complete
https://github.com/ipython/ipython/issues/10946
| Python | mit | kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup |
770f1a5d83a8450e9a16942d1260483f7b1401cd | sauce/model/news.py | sauce/model/news.py | # -*- coding: utf-8 -*-
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import Declara... | # -*- coding: utf-8 -*-
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import Declara... | Add unicode repr to NewsItem | Add unicode repr to NewsItem
| Python | agpl-3.0 | moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE |
5db2ee20fbe8ecdf1d432fd23c21702233f1bba7 | recharges/tasks.py | recharges/tasks.py | from celery.task import Task
from celery.utils.log import get_task_logger
import requests
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = "gopherairtime.recharges.tasks.hotsocket_login"
def run(s... | import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = ... | Refactor the task for getting token to store it in DB | Refactor the task for getting token to store it in DB
| Python | bsd-3-clause | westerncapelabs/gopherairtime,westerncapelabs/gopherairtime |
4d1455614beea6b751715fbd0a0547bbe3dea018 | wagtailstartproject/project_template/tests/middleware.py | wagtailstartproject/project_template/tests/middleware.py | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | Update PageStatusMiddleware for use with Python 3 | Update PageStatusMiddleware for use with Python 3
| Python | mit | leukeleu/wagtail-startproject,leukeleu/wagtail-startproject |
32820375c4552a9648612ea0dddfbf524e672c0e | virtool/indexes/models.py | virtool/indexes/models.py | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... | Update IndexFile model to have 'index' column instead of 'reference' | Update IndexFile model to have 'index' column instead of 'reference'
| Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool |
a68f7ea6a9335a54762bfecf7b8f0a186bab8ed8 | detectron2/projects/__init__.py | detectron2/projects/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates.
import importlib
from pathlib import Path
_PROJECTS = {
"point_rend": "PointRend",
"deeplab": "DeepLab",
"panoptic_deeplab": "Panoptic-DeepLab",
}
_PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects"
if _PROJECT_ROOT.is_dir():
# This is tr... | # Copyright (c) Facebook, Inc. and its affiliates.
import importlib
from pathlib import Path
_PROJECTS = {
"point_rend": "PointRend",
"deeplab": "DeepLab",
"panoptic_deeplab": "Panoptic-DeepLab",
}
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects"
if _PROJECT_ROOT.is_dir():
# ... | Resolve path in case it involves a symlink | Resolve path in case it involves a symlink
Reviewed By: ppwwyyxx
Differential Revision: D27823003
fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
| Python | apache-2.0 | facebookresearch/detectron2,facebookresearch/detectron2,facebookresearch/detectron2 |
f1eb55a147c4cc160decbfbcde190b7e8a2d3be6 | clot/torrent/backbone.py | clot/torrent/backbone.py | """This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone: # pylint: disable=too-few-public-methods
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
... | """This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytost... | Remove no longer needed pylint pragma | Remove no longer needed pylint pragma
| Python | mit | elliptical/bencode |
d5c59c018ba7558a9d21370d7eb58ab590779cf1 | plugins/autojoin/plugin_tests/autojoin_test.py | plugins/autojoin/plugin_tests/autojoin_test.py | from tests import base
def setUpModule():
base.enabledPlugins.append('autojoin')
base.startServer()
def tearDownModule():
base.stopServer()
class AutoJoinTest(base.TestCase):
def setUp(self):
base.TestCase.setUp(self)
| from girder.constants import AccessType
from tests import base
import json
def setUpModule():
base.enabledPlugins.append('autojoin')
base.startServer()
def tearDownModule():
base.stopServer()
class AutoJoinTest(base.TestCase):
def setUp(self):
base.TestCase.setUp(self)
self.users... | Add server tests for auto join plugin | Add server tests for auto join plugin
| Python | apache-2.0 | kotfic/girder,kotfic/girder,adsorensen/girder,jbeezley/girder,data-exp-lab/girder,girder/girder,sutartmelson/girder,Kitware/girder,girder/girder,sutartmelson/girder,jbeezley/girder,RafaelPalomar/girder,girder/girder,adsorensen/girder,RafaelPalomar/girder,manthey/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/g... |
6ba29917003ea2f4a91434de57751762898dddce | tests/test_main.py | tests/test_main.py | import unittest
import time
from Arduino import Arduino
"""
A collection of some basic tests for the Arduino library.
Extensive coverage is a bit difficult, since a positive test involves actually
connecting and issuing commands to a live Arduino, hosting any hardware
required to test a particular function. But a cor... | import unittest
import time
"""
A collection of some basic tests for the Arduino library.
Extensive coverage is a bit difficult, since a positive test involves actually
connecting and issuing commands to a live Arduino, hosting any hardware
required to test a particular function. But a core of basic communication tes... | Add another test to explicitly connect to a serial port. | Add another test to explicitly connect to a serial port.
| Python | mit | bopo/Python-Arduino-Command-API,thearn/Python-Arduino-Command-API,ianjosephwilson/Python-Arduino-Command-API |
2eb07ae9b98c36dc94e143003a7c44c7fbfb54f7 | stronghold/middleware.py | stronghold/middleware.py | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | Refactor away unnecessary multiple return None | Refactor away unnecessary multiple return None
| Python | mit | SunilMohanAdapa/django-stronghold,SunilMohanAdapa/django-stronghold,mgrouchy/django-stronghold |
e81aeb401f7a9eacb31bed364594ffe3fb21dfcc | conftest.py | conftest.py | from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].updat... | from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].updat... | Improve test performance by using the md5 hasher for tests. | Improve test performance by using the md5 hasher for tests.
| Python | bsd-3-clause | gg7/sentry,mvaled/sentry,felixbuenemann/sentry,NickPresta/sentry,Kryz/sentry,imankulov/sentry,argonemyth/sentry,kevinastone/sentry,fuziontech/sentry,BuildingLink/sentry,Kryz/sentry,fotinakis/sentry,llonchj/sentry,korealerts1/sentry,camilonova/sentry,BuildingLink/sentry,zenefits/sentry,beni55/sentry,kevinlondon/sentry,p... |
aaaab6f87fef26feb29ddf8188e6410e7be55376 | falcom/test/test_logtree.py | falcom/test/test_logtree.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to_false
from ..logtree import Tree
class TreeTest (unittest.TestCase... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to_false
from ..logtree import Tree
class GivenEmptyTree (unittest.Te... | Refactor tests to use setup | Refactor tests to use setup
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
245d0b91a778d6c0015e04bf369bc59304588cb9 | block_disposable_email.py | block_disposable_email.py | #!/usr/bin/env python
import re
import sys
def chunk(l,n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def is_disposable_email(email):
emails = [line.strip() for line in open('domain-list.txt')]
"""
Chunk it!
Regex parser doesn't deal with hundreds of groups
"""
for email_group ... | from django.conf import settings
import re
import sys
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(l,n):
retu... | Convert for use with Django | Convert for use with Django
| Python | bsd-3-clause | aaronbassett/DisposableEmailChecker |
22800562830d11cf8287656f098e163d7cedf2d3 | test/test_scraping.py | test/test_scraping.py | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
assert type(time) is date... | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
self.assertIs(type(time),... | Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs). | Fix for assertIn method not being present in Python 2.6.
Undo prior erroneous commit (assertIn is missing, not assertIs).
| Python | mit | alanmcintyre/btce-api,CodeReclaimers/btce-api,lromanov/tidex-api |
8a39404dc2b6e3acc0324d9c11619640e44f6bd5 | tests/test_threads.py | tests/test_threads.py | from guv.green import threading, time
def f1():
"""A simple function
"""
print('Hello, world!')
def f2():
"""A simple function that sleeps for a short period of time
"""
time.sleep(0.1)
class TestThread:
def test_thread_create(self):
t = threading.Thread(target=f1)
asse... | from guv.green import threading, time
def f1():
"""A simple function
"""
print('Hello, world!')
def f2():
"""A simple function that sleeps for a short period of time
"""
time.sleep(0.1)
class TestThread:
def test_thread_create(self):
t = threading.Thread(target=f1)
asse... | Check to ensure that we're dealing with "green" threads | Check to ensure that we're dealing with "green" threads
| Python | mit | veegee/guv,veegee/guv |
d565fdab9cefc080ff3127f036c19e95cba73f6e | tests/test_udacity.py | tests/test_udacity.py | import unittest
from mooc_aggregator_restful_api import udacity
class UdacityTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.udacity_test_object = udacity.UdacityAPI()
def test_udacity_api_response(self):
self.assertEqual(self.udacity_te... | import unittest
from mooc_aggregator_restful_api import udacity
class UdacityTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.udacity_test_object = udacity.UdacityAPI()
def test_udacity_api_response(self):
self.assertEqual(self.udacity_te... | Add unit test for mongofy_courses of udacity module | Add unit test for mongofy_courses of udacity module
| Python | mit | ueg1990/mooc_aggregator_restful_api |
badbe38249297372c14cde1c58501854ccda413a | uncertainty/lib/nlp/__init__.py | uncertainty/lib/nlp/__init__.py | import os
VERBS_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'verbs.txt'
)
| from pkg_resources import resource_filename
VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
| Use pkg_resources to resolve file paths | Use pkg_resources to resolve file paths
| Python | mit | meyersbs/uncertainty |
42f9c3ae74073fd55702e3ffccd5b4b820d86c22 | bpython/test/test_keys.py | bpython/test/test_keys.py | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_map(self):
"""Verify KeyMap.map being a dictionary with the correct length."""
self.assertEqual(len(keys.key_dispatch.map), 43)
def test_keymap_setitem(self):
"""Verify ... | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_getitem(self):
"""Verify keys.KeyMap correctly looking up items."""
self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^['))
self.assertEqual(keys.key_dispatch['F11'], ('K... | Add __delitem__, and dict length checking to tests for keys | Add __delitem__, and dict length checking to tests for keys
| Python | mit | 5monkeys/bpython |
91951e85caf1b928224dba1ecc33a59957187dff | tkp/tests/__init__.py | tkp/tests/__init__.py | import unittest
testfiles = [
'tkp.tests.accessors',
'tkp.tests.classification',
'tkp.tests.config',
'tkp.tests.coordinates',
'tkp.tests.database',
'tkp.tests.dataset',
'tkp.tests.FDR',
'tkp.tests.feature_extraction',
'tkp.tests.gaussian',
'tkp.tests.L15_12h_const',
'tkp.tes... | import unittest
testfiles = [
'tkp.tests.accessors',
'tkp.tests.classification',
'tkp.tests.config',
'tkp.tests.coordinates',
'tkp.tests.database',
'tkp.tests.dataset',
'tkp.tests.FDR',
'tkp.tests.feature_extraction',
'tkp.tests.gaussian',
'tkp.tests.L15_12h_const',
'tkp.tes... | Remove special-casing of aipsppimage test | Remove special-casing of aipsppimage test
We have other dependencies on pyrap too...
git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6
| Python | bsd-2-clause | bartscheers/tkp,mkuiack/tkp,transientskp/tkp,transientskp/tkp,mkuiack/tkp,bartscheers/tkp |
68b2536c53426d9b624527f7ef0eb5b22c68986e | helusers/models.py | helusers/models.py | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True,... | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField()
department_name = models.CharField(max_length=50, null=True, blank=True)
... | Make UUID a non-pk to work around problems in 3rd party apps | Make UUID a non-pk to work around problems in 3rd party apps
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers |
fd55ae5927801e27e3a8642da2e00667509e8dc8 | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | Simplify Flickr's scope handling a bit | Simplify Flickr's scope handling a bit
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
6d8461181a889c639cc497e35b38dee77ecb2941 | celery/patch.py | celery/patch.py | import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware... | import logging
import sys
def _check_logger_class():
"""Make sure process name is recorded when loggers are used."""
from multiprocessing.process import current_process
logging._acquireLock()
try:
OldLoggerClass = logging.getLoggerClass()
if not getattr(OldLoggerClass, '_process_aware... | Make sure the logger class is process aware even when running Python >= 2.6 | Make sure the logger class is process aware even when running Python >= 2.6
| Python | bsd-3-clause | frac/celery,WoLpH/celery,ask/celery,ask/celery,cbrepo/celery,WoLpH/celery,cbrepo/celery,mitsuhiko/celery,frac/celery,mitsuhiko/celery |
5f11dba9339c91cb615a934d3f4a8e13cee7d3f5 | bin/link_venv.py | bin/link_venv.py | #!/usr/bin/python
#-*- coding:utf-8 -*-
"""
Executes the methos in utils.py
This file should be running under the original python,
not an env one
"""
import sys
from venv_dependencies.venv_dep_utils import *
def main(modules):
venv = get_active_venv()
if not venv:
print "No virtual envs"
#rais... | #!/usr/bin/python
#-*- coding:utf-8 -*-
"""
Executes the methos in utils.py
This file should be running under the original python,
not an env one
"""
import sys
from venv_dependencies.venv_dep_utils import *
def main(modules):
venv = get_active_venv()
if not venv:
raise SystemExit("No virtual envs")
... | Raise SystemExit if not in virtualenv. | Raise SystemExit if not in virtualenv.
| Python | mit | arruda/venv-dependencies |
b8e479e799539be2e413de8052bf0af084e63c8e | osgtest/tests/test_25_voms_admin.py | osgtest/tests/test_25_voms_admin.py | import os
import unittest
import osgtest.library.core as core
import osgtest.library.osgunittest as osgunittest
class TestSetupVomsAdmin(osgunittest.OSGTestCase):
def test_01_wait_for_voms_admin(self):
core.state['voms.started-webapp'] = False
core.skip_ok_unless_installed('voms-admin-server')
... | import os
import unittest
import osgtest.library.core as core
import osgtest.library.osgunittest as osgunittest
class TestSetupVomsAdmin(osgunittest.OSGTestCase):
def test_01_wait_for_voms_admin(self):
core.state['voms.started-webapp'] = False
core.skip_ok_unless_installed('voms-admin-server')
... | Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host. | Increase the timeout value for the VOMS Admin start-up from 60s to 120s.
Primarily, this is driven by occasional timeouts in the VMU tests, which
can run slowly on a heavily loaded host.
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@18485 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
b0bb270f1995271ea84c4ec428ade91b1550b36e | domotica/views.py | domotica/views.py | from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
def index(request):
s7conn = s7.S7Comm("10.0.3.9")
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return render(request, "light... | from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse, Http404
import s7
import light
PLC_IP = "10.0.3.9"
def index(request):
s7conn = s7.S7Comm(PLC_IP)
lights = light.loadAll(s7conn)
context = { 'lights' : lights }
return rende... | Move IP address to a constant at least | Move IP address to a constant at least
Perhaps we need to move it to the 'configuration' file later.
| Python | bsd-2-clause | kprovost/domotica,kprovost/domotica |
a5f34a8011718ba31dc3d70d761bc4583112f133 | common/morse_parse.py | common/morse_parse.py | f = open("morse_table.txt")
morse_table = f.read()
morse_table = dict([(morse[0:1], morse[2:len(morse)]) for morse in morse_table.split("\n")])
f.close()
| import inspect, os
common_dir = os.path.dirname(inspect.getfile(inspect.currentframe())) # script directory
f = open(os.path.join(common_dir, "morse_table.txt"))
morse_table = f.read()
morse_table = dict([(morse[0:1], morse[2:len(morse)]) for morse in morse_table.split("\n")])
f.close()
| Make morse parser not assume that the current working directory is common/ | Make morse parser not assume that the current working directory is common/
| Python | mit | nickodell/morse-code |
0a2c2a32ceb19503816a9ef35d3de5468097f364 | gui_app/utils/StringUtil.py | gui_app/utils/StringUtil.py | import ast
def isEmpty(value):
if value:
return False
else:
return True
def isNotEmpty(value):
if not value:
return False
else:
return True
def stringToDict(param):
if isNotEmpty(param) or param != '':
return ast.literal_eval(param)
def stringToDictLis... | import ast
def isEmpty(value):
if value:
return False
else:
return True
def isNotEmpty(value):
if not value:
return False
else:
return True
def stringToDict(param):
if isNotEmpty(param) or param != '':
return ast.literal_eval(param)
def stringToDictLis... | Support to request null string | Support to request null string
| Python | apache-2.0 | cloudconductor/cloud_conductor_gui,cloudconductor/cloud_conductor_gui,cloudconductor/cloud_conductor_gui |
c9d33ef9a7f98798aec521e7f9e25e1db07bd077 | ursgal/__init__.py | ursgal/__init__.py | #!/usr/bin/env python
# encoding: utf-8
"""
"""
from __future__ import absolute_import
import sys
import os
import ursgal.uparams
# this is for unorthodox queries of the params.
# please use the unode functions or UParamsMapper
# to access params since they are translated,
# grouped and so on ...
base_dir = os.path... | #!/usr/bin/env python
# encoding: utf-8
"""
"""
from __future__ import absolute_import
import sys
import os
from packaging.version import parse as parse_version
import ursgal.uparams
# this is for unorthodox queries of the params.
# please use the unode functions or UParamsMapper
# to access params since they are tr... | Use `packaging.version.parser` for version parsing | Use `packaging.version.parser` for version parsing | Python | mit | ursgal/ursgal,ursgal/ursgal |
bb808bfe43154afa5b11265e4b5651183c7f87f0 | armstrong/hatband/sites.py | armstrong/hatband/sites.py | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjango... | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjango... | Make sure __setitem__ is available for site.register() | Make sure __setitem__ is available for site.register()
| Python | apache-2.0 | armstrong/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband |
5b18131069f860b712d8e54611541a8729496867 | suorganizer/urls.py | suorganizer/urls.py | """suorganizer 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... | """suorganizer 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... | Create URL pattern for Tag Detail. | Ch05: Create URL pattern for Tag Detail.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
113fe8c84d7aff1577a9fadf8fa4650a31ea9307 | src/dataIO.py | src/dataIO.py | import numpy as np
def testOFFReader():
path = '../sample-data/chair.off'
raw_data = tuple(open(path, 'r'))
header = raw_data.strip(' ')[:-1]
n_vertices, n_faces = header[0], header[1]
if __name__ == '__main__':
a = testOFFReader()
print a
| import trimesh
import sys
import scipy.ndimage as nd
import numpy as np
import matplotlib.pyplot as plt
from stl import mesh
from mpl_toolkits import mplot3d
def getVerticesFaces(path):
raw_data = tuple(open(path, 'r'))
header = raw_data[1].split()
n_vertices = int(header[0])
n_faces = int(header[1]... | Add off file reader with 3d resampling | Add off file reader with 3d resampling
| Python | mit | meetshah1995/tf-3dgan |
fb792452d27be4c6015f417520c600a4b902b721 | learning_journal/tests/test_views.py | learning_journal/tests/test_views.py | # -*- coding: utf-8 -*-
from pyramid.testing import DummyRequest
from learning_journal.models import Entry, DBSession
import pytest
from learning_journal import main
import webtest
from learning_journal.views import (
list_view,
detail_view,
add_view,
edit_view
)
@pytest.fixture()
def app():
setti... | # -*- coding: utf-8 -*-
from pyramid.testing import DummyRequest
from learning_journal.models import Entry, DBSession
import pytest
from learning_journal import main
import webtest
from learning_journal.views import (
list_view,
detail_view,
add_view,
edit_view
)
@pytest.fixture()
def app():
setti... | Add test to assert no access to app | Add test to assert no access to app
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal |
473c8748c4f8b33e51da2f4890cfe50a5aef3f29 | tests/test_variations.py | tests/test_variations.py | from nose import tools
import numpy as np
from trials.variations import *
class TestBernoulli:
def setup(self):
self.x = BernoulliVariation(1, 1)
def test_update(self):
self.x.update(100, 20)
def test_sample(self):
s1 = self.x.sample(10)
tools.assert_equals(len(s1), 10)... | from nose import tools
import numpy as np
from trials.variations import *
class TestBernoulli:
def setup(self):
self.x = BernoulliVariation(1, 1)
def test_update(self):
self.x.update(100, 20)
self.x.update(200, 10)
tools.assert_true(self.x.alpha == 301)
tools.assert_... | Add a test for update correctness | Add a test for update correctness
| Python | mit | bogdan-kulynych/trials |
c52dc9e5e9ca7f492f89f1db1bde52fdddd7136a | twistedchecker/functionaltests/trailingspace.py | twistedchecker/functionaltests/trailingspace.py | # enable: W9010,W9011
# A line with trailing space.
print "this line has trailing space"
# next blank line contains a whitespace
| # enable: W9010,W9011
# A line with trailing space.
print "this line has trailing space"
# next blank line contains a whitespace
# end of file
| Fix trailing space functional test. | Fix trailing space functional test.
| Python | mit | twisted/twistedchecker |
ee4d08b4795ed0818a48d97f5635c7ec2ba163fb | shopify_auth/backends.py | shopify_auth/backends.py | from django.contrib.auth.backends import RemoteUserBackend
class ShopUserBackend(RemoteUserBackend):
def authenticate(self, request=None, myshopify_domain=None, token=None, **kwargs):
if not myshopify_domain or not token or not request:
return
user = super(ShopUserBackend, self).auth... | from django.contrib.auth.backends import RemoteUserBackend
class ShopUserBackend(RemoteUserBackend):
def authenticate(self, request=None, myshopify_domain=None, token=None, **kwargs):
if not myshopify_domain or not token or not request:
return
try:
user = super(ShopUserBac... | Add regression fix for Django < 1.11 | Add regression fix for Django < 1.11
| Python | mit | discolabs/django-shopify-auth,discolabs/django-shopify-auth |
b39ca27dabcc9d949ed66be9fab2a6e4ed842fdb | iterator.py | iterator.py | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
for key, line in enumerate(contents):
src = re.sear... | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
if re.search('podcast', filename):
if re.s... | Add default images for podcasts if necessary | Add default images for podcasts if necessary
| Python | mit | jericson/stack-blog,StackExchange/stack-blog,dgrtwo/stack-blog,Zizouz212/stack-blog,moretti/stack-blog,NaeemShaikh/stack-blog.github.io,selfcommit/stack-blog,modulexcite/stack-blog,NaeemShaikh/stack-blog.github.io,jericson/stack-blog,modulexcite/stack-blog,Zizouz212/stack-blog,bjb568/stack-blog,hungvandinh/hungvandinh.... |
490b5b72e758eab32860c1be4d562debf1f3bd90 | migration_scripts/0.3/crypto_util.py | migration_scripts/0.3/crypto_util.py | # -*- coding: utf-8 -*-
# Minimal set of functions and variables from 0.2.1's crypto_util.py needed to
# regenerate journalist designations from soure's filesystem id's.
import random as badrandom
nouns = file("nouns.txt").read().split('\n')
adjectives = file("adjectives.txt").read().split('\n')
def displayid(n):
... | # -*- coding: utf-8 -*-
# Minimal set of functions and variables from 0.2.1's crypto_util.py needed to
# regenerate journalist designations from soure's filesystem id's.
import os
import random as badrandom
# Find the absolute path relative to this file so this script can be run anywhere
SRC_DIR = os.path.dirname(os.p... | Load files from absolute paths so this can be run from anywhere | Load files from absolute paths so this can be run from anywhere
| Python | agpl-3.0 | harlo/securedrop,jaseg/securedrop,jeann2013/securedrop,conorsch/securedrop,micahflee/securedrop,micahflee/securedrop,kelcecil/securedrop,ageis/securedrop,heartsucker/securedrop,jrosco/securedrop,chadmiller/securedrop,GabeIsman/securedrop,kelcecil/securedrop,jaseg/securedrop,jaseg/securedrop,ageis/securedrop,ageis/secur... |
47bf5160010d0975297d39b200492270a5279e81 | common/lib/xmodule/xmodule/discussion_module.py | common/lib/xmodule/xmodule/discussion_module.py | from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import comment_client
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_templat... | from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussi... | Remove unnecessary import that was failing a test | Remove unnecessary import that was failing a test
| Python | agpl-3.0 | franosincic/edx-platform,shabab12/edx-platform,motion2015/edx-platform,rue89-tech/edx-platform,nanolearning/edx-platform,J861449197/edx-platform,mcgachey/edx-platform,halvertoluke/edx-platform,cyanna/edx-platform,jruiperezv/ANALYSE,jbassen/edx-platform,abdoosh00/edraak,LearnEra/LearnEraPlaftform,doganov/edx-platform,al... |
e2e6e603ddcc317bdd56e3de3f69656b776030bf | avalanche/benchmarks/classic/ctrl.py | avalanche/benchmarks/classic/ctrl.py | import torch
from avalanche.benchmarks import GenericCLScenario, dataset_benchmark
from avalanche.benchmarks.utils import AvalancheTensorDataset
from torchvision import transforms
import ctrl
def CTrL(stream_name):
stream = ctrl.get_stream(stream_name)
exps = [[], [], []]
norms = []
for t in stream:... | import torch
from avalanche.benchmarks import GenericCLScenario, dataset_benchmark
from avalanche.benchmarks.utils import AvalancheTensorDataset
from torchvision import transforms
import ctrl
def CTrL(stream_name):
stream = ctrl.get_stream(stream_name)
# Train, val and test experiences
exps = [[], [], [... | Add normalization to each task | Add normalization to each task
| Python | mit | ContinualAI/avalanche,ContinualAI/avalanche |
82b4e19e4d12c9a44c4258afaa78a7e386e0f7de | wiblog/formatting.py | wiblog/formatting.py | from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
return mark_safe(CommonMark.commonmark(value))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
if firs... | import CommonMark
from images.models import Image
from django.utils.safestring import mark_safe
from django.core.exceptions import ObjectDoesNotExist
import re
def mdToHTML(value):
"""Convert a markdown string into HTML5, and prevent Django from escaping it
"""
tags = []
# Find all instance of the dy... | Add code to replace custom dynamic image tag with standard markdown image syntax | Add code to replace custom dynamic image tag with standard markdown image syntax
| Python | agpl-3.0 | lo-windigo/fragdev,lo-windigo/fragdev |
7a374b19cf89421a73ea55fdbcd1b16b52327568 | dm_control/composer/initializer.py | dm_control/composer/initializer.py | # Copyright 2018 The dm_control Authors.
#
# 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... | # Copyright 2018 The dm_control Authors.
#
# 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... | Rename `initialize_episode` --> `__call__` in `composer.Initializer` | Rename `initialize_episode` --> `__call__` in `composer.Initializer`
PiperOrigin-RevId: 234775654
| Python | apache-2.0 | deepmind/dm_control |
b2edf170e65248b97333d319ce31bc49969f9c2d | lmod/__init__.py | lmod/__init__.py | import os
import re
from collections import OrderedDict
from subprocess import Popen, PIPE
LMOD_CMD = os.environ['LMOD_CMD']
LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '')
def module(command, arguments=()):
cmd = [LMOD_CMD, 'python', '--terse', command]
cmd.extend(arguments)
result = Popen(cm... | import os
from subprocess import Popen, PIPE
LMOD_CMD = os.environ['LMOD_CMD']
LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '')
def module(command, arguments=()):
cmd = [LMOD_CMD, 'python', '--terse', command]
cmd.extend(arguments)
result = Popen(cmd, stdout=PIPE, stderr=PIPE)
if command in ... | Remove unused import in lmod | Remove unused import in lmod
| Python | mit | cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod |
74e41bf9b8ebf9f3693c6ff6979230fd3e855fa5 | test_stack.py | test_stack.py | # Test file for stack.py
# Authors Mark, Efrain, Henry
import pytest
import stack as st
def test_init():
"""Test stack constructor."""
a = st.Stack()
assert isinstance(a, st.Stack)
def test_push(populated_stack):
"""Test push function, with empty and populated stacks."""
@pytest.fixture(scope='fun... | # Test file for stack.py
# Authors Mark, Efrain, Henry
import pytest
import stack as st
def test_init():
"""Test stack constructor."""
a = st.Stack()
assert isinstance(a, st.Stack)
def test_push(empty_stack, populated_stack):
"""Test push function, with empty and populated stacks."""
empty_stack... | Add push and pop test. | Add push and pop test.
| Python | mit | efrainc/data_structures |
824d769b1b1f55a018b380f6631f11727339a018 | fpsd/run_tests.py | fpsd/run_tests.py | #!/usr/bin/env python3.5
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f",... | #!/usr/bin/env python3.5
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f",... | Add feature generation tests to test runner | Add feature generation tests to test runner
| Python | agpl-3.0 | freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/fingerprint-securedrop |
7e120f1d722259b2af91db27ff066549a8549765 | tim/models.py | tim/models.py | from django.db import models
from django.utils.translation import ugettext as _
from development.models import Project
class ModeratedProject(Project):
"""
Project awaiting moderation. Registered Users not belonging to
any group have their edits created using a ModeratedProject as
opposed to a Project.... | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from development.models import Project
class ModeratedProject(Project):
"""
Project awaiting moderation. Registered Users no... | Use ContentType for more abstract moderation | Use ContentType for more abstract moderation
| Python | bsd-3-clause | MAPC/developmentdatabase-python,MAPC/warren-st-development-database,MAPC/developmentdatabase-python,MAPC/warren-st-development-database |
e8537feff53310913047d06d95f4dd8e9dace1da | flow_workflow/historian/handler.py | flow_workflow/historian/handler.py | from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, Disconnection... | from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, Disconnection... | Add DatabaseError to list of errors that kill a historian | Add DatabaseError to list of errors that kill a historian
| Python | agpl-3.0 | genome/flow-workflow,genome/flow-workflow,genome/flow-workflow |
f727a71accdc8a12342fcb684c9ba718eedd8df2 | alexandria/traversal/__init__.py | alexandria/traversal/__init__.py | class Root(object):
"""
The main root object for any traversal
"""
__name__ = None
__parent__ = None
def __init__(self, request):
pass
def __getitem__(self, key):
next_ctx = None
if key == 'user':
next_ctx = User()
if key == 'domain':
... | class Root(object):
"""
The main root object for any traversal
"""
__name__ = None
__parent__ = None
def __init__(self, request):
pass
def __getitem__(self, key):
next_ctx = None
if key == 'user':
next_ctx = User()
if key == 'domain':
... | Set the __name__ on the traversal object | Set the __name__ on the traversal object
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria |
643f3d1f89f9c69ed519e753360fa15b23e9bb1d | ankieta/petition_custom/forms.py | ankieta/petition_custom/forms.py | from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
class SignatureForm(BaseSignatureForm):
def __init__(self, *args, **kwargs):
super(SignatureForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
... | from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper
Signature = swapper.load_model("petition", "Signature")
class SignatureForm(BaseSignatureForm):
def __init__(self, *args, **kwargs):
super(SignatureForm, sel... | Fix model definition in signature form | Fix model definition in signature form
| Python | bsd-3-clause | ad-m/petycja-faoo,ad-m/petycja-faoo,ad-m/petycja-faoo |
52cb99d09cd71efa0e4fc5f5554fc948410315a1 | txircd/modules/cmode_k.py | txircd/modules/cmode_k.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class PasswordMode(Mode):
def commandPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
channels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for index, chan in channels.enumerate():
if "k" in chan.mo... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class PasswordMode(Mode):
def checkUnset(self, user, target, param):
if param == target.mode["k"]:
return True
return False
def commandPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
channels = data["targetchan"]... | Check that the password parameter when unsetting mode k matches the password that is set | Check that the password parameter when unsetting mode k matches the password that is set
| Python | bsd-3-clause | ElementalAlchemist/txircd,DesertBus/txircd,Heufneutje/txircd |
9edaa9a843ab4e93deaf1e3b1c09d26e5eadf62d | tests/test_acceptance.py | tests/test_acceptance.py | import pytest
@pytest.mark.django_db
def test_homepage(client):
response = client.get('/')
assert response.status_code == 200
| import pytest
@pytest.mark.django_db
def test_homepage(client):
response = client.get('/')
assert response.status_code == 200
@pytest.mark.django_db
def test_resultspage_2012(client):
response = client.get('/results2012/')
assert response.status_code == 200
assert '2012: how it was' in response.... | Add acceptance tests for results pages (2012 and 2013) | Add acceptance tests for results pages (2012 and 2013)
| Python | unlicense | nott/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,nott/next.filmfest.by |
c6a161b5c0fa3d76b09b34dfab8f057e8b10bce2 | tests/test_extensions.py | tests/test_extensions.py | import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_functio... | import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_functio... | Add a test for importing a nonexistent extension | Add a test for importing a nonexistent extension
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel |
d62f04e11715d93a2281f2f69d3a9e3323a6d1c4 | timemodel/tempo_event.py | timemodel/tempo_event.py | """
File: tempo_event.py
Purpose: Defines a tempo as an Event
"""
from timemodel.event import Event
class TempoEvent(Event):
"""
Defines tempo as an Event, given a Tempo and a time position.
"""
def __init__(self, tempo, time):
"""
Constructor.
Args:
te... | """
File: tempo_event.py
Purpose: Defines a tempo as an Event
"""
from timemodel.event import Event
from timemodel.position import Position
class TempoEvent(Event):
"""
Defines tempo as an Event, given a Tempo and a time position.
"""
def __init__(self, tempo, time):
"""
Construc... | Check time argument as Position type. | Check time argument as Position type.
| Python | mit | dpazel/music_rep |
7f2acf1b27dadc33e83fd02d5023b2d03e54821d | pavement.py | pavement.py | import paver
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
updateProgressTables = True
try:
from runestone.server.chapternames import populateChapterInfob
except ImportError:
updateP... | import paver
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
updateProgressTables = True
try:
from runestone.server.chapternames import populateChapterInfob
except ImportError:
updateP... | Change project name to cljsbook. | Change project name to cljsbook.
| Python | apache-2.0 | jdeisenberg/icljs,jdeisenberg/icljs |
23e36b51e6b0af7376f489bd3a5b997d7ca545a3 | cura_app.py | cura_app.py | #!/usr/bin/env python3
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
import sys
def exceptHook(type, value, traceback):
import cura.CrashHandler
cura.CrashHandler.show(type, value, traceback)
sys.excepthook = exceptHook
import cura.CuraApplication
if sys.p... | #!/usr/bin/env python3
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
import sys
def exceptHook(type, value, traceback):
import cura.CrashHandler
cura.CrashHandler.show(type, value, traceback)
sys.excepthook = exceptHook
import cura.CuraApplication
if sys.p... | Fix stdout/stderr output location so we do not output to UM but to cura | Fix stdout/stderr output location so we do not output to UM but to cura
Fixes #452
| Python | agpl-3.0 | hmflash/Cura,ynotstartups/Wanhao,Curahelper/Cura,markwal/Cura,totalretribution/Cura,markwal/Cura,fieldOfView/Cura,fieldOfView/Cura,hmflash/Cura,senttech/Cura,bq/Ultimaker-Cura,ad1217/Cura,ad1217/Cura,Curahelper/Cura,bq/Ultimaker-Cura,totalretribution/Cura,senttech/Cura,ynotstartups/Wanhao |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.