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 |
|---|---|---|---|---|---|---|---|---|---|
8b5f3576ee30c1f50b3d3c5bd477b85ba4ec760e | plinth/modules/sso/__init__.py | plinth/modules/sso/__init__.py | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Make ttf-bitstream-vera a managed package | captcha: Make ttf-bitstream-vera a managed package
Signed-off-by: Joseph Nuthalpati <f3045f1a422c023fc6364ff0e3a18c260c53336e@thoughtworks.com>
Reviewed-by: James Valleroy <46e3063862880873c8617774e45d63de6172aab0@mailbox.org>
| Python | agpl-3.0 | harry-7/Plinth,harry-7/Plinth,harry-7/Plinth,harry-7/Plinth,harry-7/Plinth |
3f065d3e6b54912b2d78a70b5fda98d0476c3f09 | tlsep/__main__.py | tlsep/__main__.py | # -*- test-case-name: tlsep.test.test_scripts -*-
# Copyright (c) Hynek Schlawack, Richard Wall
# See LICENSE for details.
"""
eg tlsep full.cert.getdnsapi.net 443 tcp
"""
import sys
from twisted.internet import task, threads
from tlsep import _dane
def main():
if len(sys.argv) != 4:
print "Usage: {0} ... | # -*- test-case-name: tlsep.test.test_scripts -*-
# Copyright (c) Hynek Schlawack, Richard Wall
# See LICENSE for details.
"""
eg tlsep full.cert.getdnsapi.net 443 tcp
"""
import sys
from twisted.internet import task, threads, defer
from tlsep import _dane, _tls
def printResult(res):
tlsaRecord, serverCertifi... | Check the server cert using matchesCertificate | Check the server cert using matchesCertificate
| Python | mit | hynek/tnw |
7ace27a6a114e381a30ac9760880b68277a868fc | python_scripts/mc_config.py | python_scripts/mc_config.py | #!/usr/bin/python
import yaml
def read_config():
yml_file = open('/home/dlarochelle/git_dev/mediacloud/mediawords.yml', 'rb')
config_file = yaml.load( yml_file )
return config_file
| #!/usr/bin/python
import yaml
import os.path
_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))
def read_config():
yml_file = open(_config_file_name, 'rb')
config_file = yaml.load( yml_file )
return config_file
| Use relative path location for mediawords.yml. | Use relative path location for mediawords.yml.
| Python | agpl-3.0 | berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter... |
0652ab317db79ad7859aafba505c016cd6d58614 | modules/combined/tests/catch_release/catch_release_test.py | modules/combined/tests/catch_release/catch_release_test.py | from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e']}
| from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e'],
SKIP : 'temp'
}
| Test passes on my machine, dies on others. Skipping for now. | Test passes on my machine, dies on others. Skipping for now.
r8830
| Python | lgpl-2.1 | WilkAndy/moose,jinmm1992/moose,zzyfisherman/moose,tonkmr/moose,yipenggao/moose,tonkmr/moose,raghavaggarwal/moose,lindsayad/moose,SudiptaBiswas/moose,zzyfisherman/moose,YaqiWang/moose,permcody/moose,raghavaggarwal/moose,laagesen/moose,nuclear-wizard/moose,jasondhales/moose,idaholab/moose,harterj/moose,raghavaggarwal/moo... |
3b4d135556e2aca65050af3d6a7dc0975cd0b53b | amgut/handlers/FAQ.py | amgut/handlers/FAQ.py | from amgut.handlers.base_handlers import BaseHandler
class FAQHandler(BaseHandler):
def get(self):
self.render('FAQ.html')
| from amgut.handlers.base_handlers import BaseHandler
class FAQHandler(BaseHandler):
def get(self):
self.render('FAQ.html', loginerror='')
| Add loginerror blank to render call | Add loginerror blank to render call
| Python | bsd-3-clause | wasade/american-gut-web,mortonjt/american-gut-web,ElDeveloper/american-gut-web,josenavas/american-gut-web,PersonalGenomesOrg/american-gut-web,squirrelo/american-gut-web,squirrelo/american-gut-web,josenavas/american-gut-web,adamrp/american-gut-web,ElDeveloper/american-gut-web,biocore/american-gut-web,mortonjt/american-g... |
ba008f405a89d07e170d1b4c893246fb25ccba04 | benchmarks/benchmarks/bench_lib.py | benchmarks/benchmarks/bench_lib.py | """Benchmarks for `numpy.lib`."""
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Pad(Benchmark):
"""Benchmarks for `numpy.pad`."""
param_names = ["shape", "pad_width", "mode"]
params = [
[(1000,), (10, 100), (10, 10, 10)... | """Benchmarks for `numpy.lib`."""
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Pad(Benchmark):
"""Benchmarks for `numpy.pad`."""
param_names = ["shape", "pad_width", "mode"]
params = [
[(1000,),
(10, 100),
... | Make the pad benchmark pagefault in setup | BENCH: Make the pad benchmark pagefault in setup
| Python | bsd-3-clause | shoyer/numpy,grlee77/numpy,mhvk/numpy,pbrod/numpy,endolith/numpy,WarrenWeckesser/numpy,mhvk/numpy,pbrod/numpy,jakirkham/numpy,mattip/numpy,anntzer/numpy,abalkin/numpy,shoyer/numpy,WarrenWeckesser/numpy,madphysicist/numpy,MSeifert04/numpy,madphysicist/numpy,endolith/numpy,mhvk/numpy,mattip/numpy,pizzathief/numpy,seberg/... |
0701f7f4d03045a49190d8aac172daed467ebcd7 | python/xchainer/__init__.py | python/xchainer/__init__.py | from xchainer._core import * # NOQA
_global_context = Context()
set_global_default_context(_global_context)
set_default_device('native')
| from xchainer._core import * # NOQA
_global_context = Context()
set_global_default_context(_global_context)
| Remove line added by bad merge | Remove line added by bad merge
| Python | mit | niboshi/chainer,keisuke-umezawa/chainer,jnishi/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,tkerola/chainer,jnishi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,keisuke-umezawa/chainer,pfnet/chainer,ktnyt/chainer,ktnyt/chainer,niboshi/chainer... |
703a423f4a0aeda7cbeaa542e2f4e0581eee3bda | slot/utils.py | slot/utils.py | import datetime
def to_ticks(dt):
"""Converts a timestamp to ticks"""
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
def ticks_to_timestamp(ticks):
"""Converts ticks to a timestamp"""
converted = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=3700)
return converted
def... | import datetime
import pytz
this_timezone = pytz.timezone('Europe/London')
def timestamp_to_ticks(dt):
"""Converts a datetime to ticks (seconds since Epoch)"""
delta = (dt - datetime.datetime(1970, 1, 1))
ticks = int(delta.total_seconds())
return ticks
def ticks_to_timestamp(ticks):
"""Converts... | Add timezone support to timestamp helper methods | Add timezone support to timestamp helper methods
| Python | mit | nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT |
430da3ea616a1118af0b043952bc9d9554086c7f | tpdatasrc/co8fixes/scr/py00248tutorial_room_7.py | tpdatasrc/co8fixes/scr/py00248tutorial_room_7.py | from toee import *
from combat_standard_routines import *
from utilities import *
def san_heartbeat( attachee, triggerer ):
for obj in game.obj_list_vicinity(attachee.location,OLC_PC):
if (critter_is_unconscious(obj) == 0):
if attachee.distance_to( obj ) < 30:
if not game.tutorial_is_active():
game.tuto... | from toee import *
from utilities import *
def correct_zombie_factions():
for obj in game.obj_list_vicinity(location_from_axis(464, 487) ,OLC_NPC):
if obj in game.party:
continue
if obj.faction_has(7) == 0:
obj.faction_add(7)
return
def san_heartbeat( attachee, triggerer ):
for obj in game.obj_list_vici... | Fix tutorial zombie faction issue (co8) | Fix tutorial zombie faction issue (co8)
| Python | mit | GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus |
528c10b3988a93668c6a0d4c0b8a7de2667204b1 | frontend/ligscore/results_page.py | frontend/ligscore/results_page.py | from flask import request
import saliweb.frontend
import collections
Transform = collections.namedtuple('Transform', ['number', 'score'])
def show_results_page(job):
show_from = get_int('from', 1)
show_to = get_int('to', 20)
with open(job.get_path('input.txt')) as fh:
receptor, ligand, scoretype ... | from flask import request
import saliweb.frontend
import collections
Transform = collections.namedtuple('Transform', ['number', 'score'])
def show_results_page(job):
show_from = request.args.get('from', 1, type=int)
show_to = request.args.get('to', 20, type=int)
with open(job.get_path('input.txt')) as fh... | Drop our own get_int() function | Drop our own get_int() function
We don't need a custom function to get an int parameter;
flask/werkzeug already handles this.
| Python | lgpl-2.1 | salilab/ligscore,salilab/ligscore |
e11bc2ebc701dd947d3d5734339b4815bbd21fd1 | PythonScript/Helper/Dujing.py | PythonScript/Helper/Dujing.py | # This Python file uses the following encoding: utf-8
import sys
import getopt
import Convert
def usage():
print "Usage: to be done."
def main(argv):
try:
opts, args = getopt.getopt(argv, "hb:d", ["help", "book="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "-... | # This Python file uses the following encoding: utf-8
import sys
import argparse
import Convert
def main():
parser = argparse.ArgumentParser(description='Generate a classic book with the desired format.')
parser.add_argument('book', type=str, help='a book file')
args = parser.parse_args()
filePath = args.book
tr... | Use argparse (instead of getopt) to get the usage information | Use argparse (instead of getopt) to get the usage information
| Python | mit | fan-jiang/Dujing |
29e1c2e30d284e1992bae59fe522c31b4e627f0d | dataset/dataset/pipelines.py | dataset/dataset/pipelines.py | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class DatasetPipeline(object):
def process_item(self, item, spider):
return item
| import re
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class DatasetPipeline(object):
title_regex = re.compile('(((((\\(?[A-Za-z]{1}[-A-Za-z]+,?\\)?)|[-0-9]+)|-)|\\(?[A-Za-z0-9]+\\)?) *)+')
... | Convert item processing to pipeline module | Convert item processing to pipeline module
| Python | mit | MaxLikelihood/CODE |
80162fd636cea87b9d096d6df8b93c59887d8785 | scripts/crontab/gen-cron.py | scripts/crontab/gen-cron.py | #!/usr/bin/env python
import os
from optparse import OptionParser
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-z", "--zamboni",
help="Location of zamboni (required)")
parser.add_option("-u", "... | #!/usr/bin/env python
import os
from optparse import OptionParser
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-z", "--zamboni",
help="Location of zamboni (required)")
parser.add_option("-u", "... | Add DataDog monitoring to cron job runs | Add DataDog monitoring to cron job runs
| Python | bsd-3-clause | mozilla/addons-server,diox/olympia,mozilla/addons-server,kumar303/olympia,wagnerand/addons-server,atiqueahmedziad/addons-server,eviljeff/olympia,eviljeff/olympia,wagnerand/addons-server,kumar303/addons-server,wagnerand/addons-server,bqbn/addons-server,psiinon/addons-server,bqbn/addons-server,kumar303/olympia,diox/olymp... |
ae77f5d0050167e0ce137ab876d724658c961f3d | forms.py | forms.py | """
UK-specific Form helpers
"""
from django.forms.fields import Select
class IECountySelect(Select):
"""
A Select widget that uses a list of Irish Counties as its choices.
"""
def __init__(self, attrs=None):
from ie_counties import IE_COUNTY_CHOICES
super(IECountySelect, self).__init_... | """
UK-specific Form helpers
"""
from __future__ import absolute_import
from django.contrib.localflavor.ie.ie_counties import IE_COUNTY_CHOICES
from django.forms.fields import Select
class IECountySelect(Select):
"""
A Select widget that uses a list of Irish Counties as its choices.
"""
def __init__... | Remove all relative imports. We have always been at war with relative imports. | Remove all relative imports. We have always been at war with relative imports.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@17009 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | martinogden/django-localflavor-ie |
31961f9cbfd01955fe94d13cd9f6d9a9a84f3485 | server/proposal/__init__.py | server/proposal/__init__.py | from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
from . import event_tasks
| from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
from . import event_tasks
from . import image_tasks
| Load image processing tasks on startup | Load image processing tasks on startup
| Python | mit | cityofsomerville/citydash,codeforboston/cornerwise,cityofsomerville/cornerwise,codeforboston/cornerwise,cityofsomerville/cornerwise,cityofsomerville/citydash,codeforboston/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/cornerwise,cityofsomerville/citydash |
d409594c01e11e05a59f5614722dd3035855e399 | salt/returners/redis_return.py | salt/returners/redis_return.py | '''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(r... | '''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(r... | Change the redis returner to better use data structures | Change the redis returner to better use data structures
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
936bdadb9e949d29a7742b088e0279680afa6c4a | copy_from_find_in_files_command.py | copy_from_find_in_files_command.py | import sublime
import sublime_plugin
import re
class CopyFromFindInFilesCommand(sublime_plugin.TextCommand):
def run(self, edit, force=False):
self.view.run_command('copy')
if not self.in_find_results_view() and not force:
return
clipboard_contents = sublime.get_clipboard()
... | import sublime
import sublime_plugin
import re
class CopyFromFindInFilesCommand(sublime_plugin.TextCommand):
def run(self, edit, force=False):
self.view.run_command('copy')
if not self.in_find_results_view() and not force:
return
clipboard_contents = sublime.get_clipboard()
... | Make the regex work on Python2.x | Make the regex work on Python2.x
| Python | mit | kema221/sublime-copy-from-find-results,NicoSantangelo/sublime-copy-from-find-results,kema221/sublime-copy-from-find-results |
9c68a69eb5bf6e7ffab8b7538797c74b05a7c70b | src/zeit/content/article/edit/browser/tests/test_header.py | src/zeit/content/article/edit/browser/tests/test_header.py | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
# Select header that allows header module
s.click('css=#edit-form... | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
# Select header that allows header module
s.click('css=#edit-form... | Test needs to wait until the header values are updated after it changed the template | FIX: Test needs to wait until the header values are updated after it changed the template
I'm not sure how this previously has ever passed, to be honest.
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article |
d6a67a94cacab93463f2a15fc5d2a2fadae2ad83 | site/tests/test_unittest.py | site/tests/test_unittest.py | import unittest
class IntegerArithmenticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEqual((1 + 2), 3)
self.assertEqual(0 + 1, 1)
def testMultiply(self):
self.assertEqual((0 * 10), 0)
self.assertEqual((5 * 8), 40)
unittest.main(... | import unittest
class IntegerArithmeticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEqual((1 + 2), 3)
self.assertEqual(0 + 1, 1)
def testMultiply(self):
self.assertEqual((0 * 10), 0)
self.assertEqual((5 * 8), 40)
suite = unittes... | Change unittest test in test suite : it is not run in module __main__ | Change unittest test in test suite : it is not run in module __main__
| Python | bsd-3-clause | Hasimir/brython,olemis/brython,JohnDenker/brython,firmlyjin/brython,Isendir/brython,jonathanverner/brython,Mozhuowen/brython,olemis/brython,brython-dev/brython,Lh4cKg/brython,Isendir/brython,kevinmel2000/brython,amrdraz/brython,jonathanverner/brython,molebot/brython,Mozhuowen/brython,jonathanverner/brython,JohnDenker/b... |
14cfc8927b36a89947c1bd4cefc5be88ebbea1b5 | cheroot/test/conftest.py | cheroot/test/conftest.py | import threading
import time
import pytest
import cheroot.server
import cheroot.wsgi
config = {
'bind_addr': ('127.0.0.1', 54583),
'wsgi_app': None,
}
def cheroot_server(server_factory):
conf = config.copy()
httpserver = server_factory(**conf) # create it
threading.Thread(target=httpserver.s... | import threading
import time
import pytest
import cheroot.server
import cheroot.wsgi
EPHEMERAL_PORT = 0
config = {
'bind_addr': ('127.0.0.1', EPHEMERAL_PORT),
'wsgi_app': None,
}
def cheroot_server(server_factory):
conf = config.copy()
httpserver = server_factory(**conf) # create it
threadin... | Make HTTP server fixture bind to an ephemeral port | Make HTTP server fixture bind to an ephemeral port
| Python | bsd-3-clause | cherrypy/cheroot |
bd70ef56d95958b8f105bdff31b675d66c40bca8 | serfnode/handler/supervisor.py | serfnode/handler/supervisor.py | import os
import subprocess
import docker_utils
import jinja2
env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs'))
def supervisor_install(block, **kwargs):
"""Update supervisor with `block` config.
- `block` is the name to a .conf template file (in directory
`/programs`)
- `kwargs... | import os
import subprocess
import docker_utils
import docker
import jinja2
env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs'))
def supervisor_install(block, **kwargs):
"""Update supervisor with `block` config.
- `block` is the name to a .conf template file (in directory
`/programs`)... | Add convenience function to start docker | Add convenience function to start docker
Mainly to be used from supervisor. | Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode |
973669fce5fcc2360b4c72b3d1345d708e1ca0aa | examples/bench_randomizer.py | examples/bench_randomizer.py | import random
import hurdles
class BenchRandom(hurdles.BenchCase):
def bench_this(self):
return [random.randint(1, 100000) for x in [0] * 100000]
def bench_that(self):
return [random.randint(1, 10000) for y in [0] * 10000]
if __name__ == "__main__":
B = BenchRandom()
B.run()
| import random
import hurdles
from hurdles.tools import extra_setup
class BenchRandom(hurdles.BenchCase):
@extra_setup("""import random""")
def bench_this(self, *args, **kwargs):
return [random.randint(1, 100000) for x in [0] * 100000]
def bench_that(self, *args, **kwargs):
return [rando... | Update : don't forget *args, **kwargs in bench_case methods | Update : don't forget *args, **kwargs in bench_case methods
| Python | mit | oleiade/Hurdles |
c566236de3373aa73c271aaf412de60538c2abfb | common/renderers/excel_renderer.py | common/renderers/excel_renderer.py | import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'human.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row = ... | import xlsxwriter
import os
from django.conf import settings
from rest_framework import renderers
def _write_excel_file(data):
result = data.get('results')
work_book_name = 'download.xlsx'
workbook = xlsxwriter.Workbook(work_book_name)
worksheet = workbook.add_worksheet()
row... | Add support for nested lists in the excel renderer | Add support for nested lists in the excel renderer
| Python | mit | MasterFacilityList/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,urandu/mfl_api,urandu/mfl_api |
7e3b0ab5366756018e3bcaa50843e7d28ab7643c | codemood/common/views.py | codemood/common/views.py | from django.views.generic import TemplateView
from commits.forms import RepositoryForm
from commits.models import Repository, Commit
from social.models import Post
class Index(TemplateView):
def get_template_names(self):
if self.request.user.is_authenticated():
return 'index/authorized.html'
... | from django.views.generic import TemplateView
from commits.forms import RepositoryForm
from commits.models import Repository, Commit
from social.models import Post
class Index(TemplateView):
"""
Return different view to authenticated and not.
"""
def dispatch(self, request, *args, **kwargs):
i... | Split Index view to AuthenticatedIndex view and NotAuthenticatedIndex view. | Split Index view to AuthenticatedIndex view and NotAuthenticatedIndex view.
| Python | mit | mindinpanic/codingmood,pavlenko-volodymyr/codingmood,mindinpanic/codingmood,pavlenko-volodymyr/codingmood |
a260020f10b4d993635e579c8b130e754c49f7aa | dogebuild/dogefile_loader.py | dogebuild/dogefile_loader.py | from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHolder.create()
exec(code)
return ContextHolder.clear_and_get()
| import os
from pathlib import Path
from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
dir = Path(filename).resolve().parent
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHolder.create()
cwd =... | Add cirectoy switch on loading | Add cirectoy switch on loading
| Python | mit | dogebuild/dogebuild |
06d2bb81d19ba3089bddeb77e7e85482b5f0596b | cms/djangoapps/contentstore/management/commands/export_all_courses.py | cms/djangoapps/contentstore/management/commands/export_all_courses.py | """
Script for exporting all courseware from Mongo to a directory
"""
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
class Command(BaseC... | """
Script for exporting all courseware from Mongo to a directory
"""
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
class Command(BaseC... | Fix course id separator at export all courses command | Fix course id separator at export all courses command
| Python | agpl-3.0 | morenopc/edx-platform,morenopc/edx-platform,morenopc/edx-platform,morenopc/edx-platform,morenopc/edx-platform |
c4068d47da3b98f8fcc38bde6ab477174ab92a3f | djlint/analyzers/context.py | djlint/analyzers/context.py | class ContextPopException(Exception):
pass
class Context(object):
def __init__(self):
self.dicts = [{}]
def push(self):
d = {}
self.dicts.append(d)
return d
def pop(self):
if len(self.dicts) == 1:
raise ContextPopException
return self.dict... | """Inspired by django.template.Context"""
class ContextPopException(Exception):
"""pop() has been called more times than push()"""
class Context(object):
"""A stack container for imports and assignments."""
def __init__(self):
self.dicts = [{}]
def push(self):
d = {}
self.d... | Remove Context.get method and add docstrings | Remove Context.get method and add docstrings
| Python | isc | alfredhq/djlint |
73614f076e93794dde784b6fc376ca85fbb5bc21 | FileWatcher.py | FileWatcher.py | from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import time
class MyEventHandler(FileSystemEventHandler):
def __init__(self, filePath, callback):
super(MyEventHandler, self).__init__()
self.filePath = filePath
self.callback = callback
... | import sys
# FSEvents observer in watchdog cannot have multiple watchers of the same path
# use kqueue instead
if sys.platform == 'darwin':
from watchdog.observers.kqueue import KqueueObserver as Observer
else:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os... | Work around for watchdog problem on OS X. | Work around for watchdog problem on OS X.
| Python | apache-2.0 | rmcgurrin/PyQLab,calebjordan/PyQLab,Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab |
5fe4dab51c8b7c725b49bd6352fbf531003ead4e | openpnm/topotools/generators/__init__.py | openpnm/topotools/generators/__init__.py | from .cubic import cubic
from .delaunay import delaunay
from .gabriel import gabriel
from .voronoi import voronoi
from .voronoi_delaunay_dual import voronoi_delaunay_dual
from .template import cubic_template
from .fcc import fcc
from .bcc import bcc
| r"""
================================================
Generators (:mod:`openpnm.topotools.generators`)
================================================
This module contains a selection of functions that deal specifically with
generating sufficient information that can be turned into an openpnm network.
.. currentmodu... | Add docstrings to generators' init file | Add docstrings to generators' init file
| Python | mit | PMEAL/OpenPNM |
2ae4fb0dfa4c53e8dc80f3997cb3f9f8d9ad962a | src/ansible/models.py | src/ansible/models.py | from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=200)
playbook_path = models.CharField(max_length=200, default="~/")
ansible_config_path = models.CharField(max_length=200, default="~/")
default_inventory = models.CharField(max_length=200, default="hos... | from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=200)
playbook_path = models.CharField(max_length=200, default="~/")
ansible_config_path = models.CharField(max_length=200, default="~/")
default_inventory = models.CharField(max_length=200, default="hos... | Fix plural form of Registry | Fix plural form of Registry
TIL how to use meta class
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
4e3351486b88a8cec60279ff3182565921caec0d | website_portal_v10/__openerp__.py | website_portal_v10/__openerp__.py | {
'name': 'Website Portal',
'category': 'Website',
'summary': 'Account Management Frontend for your Customers',
'version': '1.0',
'description': """
Allows your customers to manage their account from a beautiful web interface.
""",
'website': 'https://www.odoo.com/',
'depends': [
... | {
'name': 'Website Portal',
'category': 'Website',
'summary': 'Account Management Frontend for your Customers',
'version': '1.0',
'description': """
Allows your customers to manage their account from a beautiful web interface.
""",
'depends': [
'website',
],
'data': [
... | Remove 'author' and 'website' on odoo modules' manisfest | [IMP] Remove 'author' and 'website' on odoo modules' manisfest
And use the default values :
- author : 'Odoo S.A.'
- website: https://www.odoo.com/
| Python | agpl-3.0 | Tecnativa/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,JayVora-SerpentCS/website,JayVora-SerpentCS/website,nicolas-petit/website,RoelAdriaans-B-informed/website,khaeusler/website,khaeusler/website,Tecnativa/website,RoelAdriaans-B-informed/website,nicolas-petit/website,khaeusler/website,nicolas-peti... |
b14e605c83f95e6e1a3c70f148c32bbdc0ca12b1 | zeus/api/resources/build_index.py | zeus/api/resources/build_index.py | from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of bu... | from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of bu... | Add pagination to build index | feat: Add pagination to build index
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
04a7de877c50bc84428e7bb7d30b1c6cac00a59f | ipywidgets/widgets/tests/test_widget_selection.py | ipywidgets/widgets/tests/test_widget_selection.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import warnings
from unittest import TestCase
from ipywidgets import Dropdown
class TestDropdown(TestCase):
def test_construction(self):
Dropdown()
def test_deprecation_warning_mapping_options(sel... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import warnings
from unittest import TestCase
from ipywidgets import Dropdown
class TestDropdown(TestCase):
def test_construction(self):
Dropdown()
def test_deprecation_warning_mapping_options(sel... | Use simplefilter('always') for testing the warning | Use simplefilter('always') for testing the warning
* Use `warnings.simplefilter('always')` for DeprecationWarning
* More specific test on warning message
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets |
81978240e48dbaac2567054b33617a1acabbb695 | corehq/apps/app_manager/tasks.py | corehq/apps/app_manager/tasks.py | from celery.task import task
from corehq.apps.users.models import CommCareUser
@task
def create_user_cases(domain_name):
from corehq.apps.callcenter.utils import sync_usercase
for user in CommCareUser.by_domain(domain_name):
sync_usercase(user)
| from celery.task import task
from corehq.apps.users.models import CommCareUser
@task(queue='background_queue')
def create_user_cases(domain_name):
from corehq.apps.callcenter.utils import sync_usercase
for user in CommCareUser.by_domain(domain_name):
sync_usercase(user)
| Use background queue for creating user cases | Use background queue for creating user cases
| Python | bsd-3-clause | qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq |
c5001c6f6dab2639fdeb5735f4d4f6f7b8d35395 | pamqp/body.py | pamqp/body.py | # -*- encoding: utf-8 -*-
"""
The pamqp.body module contains the Body class which is used when
unmarshaling body frames. When dealing with content frames, the message body
will be returned from the library as an instance of the body class.
"""
class ContentBody(object):
"""ContentBody carries the value for an AM... | # -*- encoding: utf-8 -*-
"""
The pamqp.body module contains the Body class which is used when
unmarshaling body frames. When dealing with content frames, the message body
will be returned from the library as an instance of the body class.
"""
import typing
class ContentBody:
"""ContentBody carries the value for... | Update to include typing, cleanup docstrings and code | Update to include typing, cleanup docstrings and code
| Python | bsd-3-clause | gmr/pamqp |
f9698eb96ca0c69a9d41a2d19a56af83e74da949 | examples/advanced/extend_python.py | examples/advanced/extend_python.py | """
Extend the Python Grammar
==============================
This example demonstrates how to use the `%extend` statement,
to add new syntax to the example Python grammar.
"""
from lark.lark import Lark
from python_parser import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, ... | """
Extend the Python Grammar
==============================
This example demonstrates how to use the `%extend` statement,
to add new syntax to the example Python grammar.
"""
from lark.lark import Lark
from lark.indenter import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, ... | Fix confusing import (no change in functionality) | Fix confusing import (no change in functionality) | Python | mit | lark-parser/lark |
bed65ca5a3af883a90cdc869dbfdaf08ac4ba40e | company/configurations_api.py | company/configurations_api.py | from ..cw_controller import CWController
# Class for /company/configurations
from connectpyse.company import configuration
class ConfigurationsAPI(CWController):
def __init__(self):
self.module_url = 'company'
self.module = 'configurations'
self._class = configuration.Configuratio... | from ..cw_controller import CWController
# Class for /company/configurations
from . import configuration
class ConfigurationsAPI(CWController):
def __init__(self):
self.module_url = 'company'
self.module = 'configurations'
self._class = configuration.Configuration
super()... | Fix config api class again | Fix config api class again
| Python | mit | joshuamsmith/ConnectPyse |
391c1681eaeabfdbe65a64a1bb8b05beca30141e | wqflask/utility/db_tools.py | wqflask/utility/db_tools.py | from MySQLdb import escape_string as escape
def create_in_clause(items):
"""Create an in clause for mysql"""
in_clause = ', '.join("'{}'".format(x) for x in mescape(*items))
in_clause = '( {} )'.format(in_clause)
return in_clause
def mescape(*items):
"""Multiple escape"""
escaped = [escape(str... | from MySQLdb import escape_string as escape_
def create_in_clause(items):
"""Create an in clause for mysql"""
in_clause = ', '.join("'{}'".format(x) for x in mescape(*items))
in_clause = '( {} )'.format(in_clause)
return in_clause
def mescape(*items):
"""Multiple escape"""
return [escape_(st... | Add global method to convert binary string to plain string | Add global method to convert binary string to plain string
* wqflask/utility/db_tools.py: escape_string returns a binary string which
introduces a bug when composing sql query string. The escaped strings have to be
converted to plain text.
| Python | agpl-3.0 | pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2 |
d4a7a69654e9e055c309762340e7aa4a722ca1f1 | mass_mailing_switzerland/models/crm_event_compassion.py | mass_mailing_switzerland/models/crm_event_compassion.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#########... | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#########... | FIX bug in event creation | FIX bug in event creation
| Python | agpl-3.0 | eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland |
00f83dad3a0cec2bccb4de878b477bbcf850e52d | core/datatypes/url.py | core/datatypes/url.py | import re
from mongoengine import *
import urlnorm
from core.datatypes import Element
from core.helpers import is_url
class Url(Element):
def clean(self):
"""Ensures that URLs are canonized before saving"""
try:
if not is_url(self.value):
raise ValidationError("Invali... | import re
from mongoengine import *
import urlnorm
from core.datatypes import Element
from core.helpers import is_url
class Url(Element):
def clean(self):
"""Ensures that URLs are canonized before saving"""
try:
if re.match("[a-zA-Z]+://", self.value) is None:
self.va... | Raise exception on invalid URL | Raise exception on invalid URL
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
9ad5f279c33339ab00b1fcf90975c085afe0ab43 | mysite/extra_translations.py | mysite/extra_translations.py | # This module exists just to list strings for translation to be picked
# up by makemessages.
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for r... | # -*- coding: utf-8 -*-
# This module exists just to list strings for translation to be picked
# up by makemessages.
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important ... | Add some more text used in migrations which need translation | Add some more text used in migrations which need translation
| Python | agpl-3.0 | mysociety/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli... |
6ce72c5b0726fc2e3ae78c6f0a22e4f03f26a2ca | erpnext/patches/v5_4/update_purchase_cost_against_project.py | erpnext/patches/v5_4/update_purchase_cost_against_project.py | # Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
for p in frappe.get_all("Project"):
project = frappe.get_doc("Project", p.name)
project.update_purchase_costing()
... | # Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
for p in frappe.get_all("Project", filters={"docstatus": 0}):
project = frappe.get_doc("Project", p.name)
project.... | Update project cost for draft project only | [fix] Update project cost for draft project only
| Python | agpl-3.0 | mbauskar/helpdesk-erpnext,hernad/erpnext,gangadharkadam/saloon_erp_install,mbauskar/omnitech-demo-erpnext,indictranstech/trufil-erpnext,mbauskar/helpdesk-erpnext,susuchina/ERPNEXT,njmube/erpnext,aruizramon/alec_erpnext,ShashaQin/erpnext,anandpdoshi/erpnext,pombredanne/erpnext,aruizramon/alec_erpnext,mahabuber/erpnext,g... |
64336620b0b2c279293e921ba0a7cdd15a573d85 | intelmq/bots/parsers/cznic/parser_proki.py | intelmq/bots/parsers/cznic/parser_proki.py | # -*- coding: utf-8 -*-
import json
from intelmq.lib import utils
from intelmq.lib.bot import ParserBot
class CZNICProkiParserBot(ParserBot):
recover_line = ParserBot.recover_line_json
def parse(self, report):
raw_report = utils.base64_decode(report.get("raw"))
report = json.loads(raw_repor... | # -*- coding: utf-8 -*-
import json
from intelmq.lib import utils
from intelmq.lib.bot import ParserBot
class CZNICProkiParserBot(ParserBot):
recover_line = ParserBot.recover_line_json
def parse(self, report):
raw_report = utils.base64_decode(report.get("raw"))
report = json.loads(raw_repor... | Allow loading events from dump | Allow loading events from dump
| Python | agpl-3.0 | aaronkaplan/intelmq,certtools/intelmq,certtools/intelmq,aaronkaplan/intelmq,certtools/intelmq,aaronkaplan/intelmq |
c6d4a0e34a0e1ef1ea330734477aac434322ff01 | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | Update extensions and GameController subclass | Update extensions and GameController subclass
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
087fd390c5c19d0187102cc2dbe1ac9ac8c4fb03 | perfrunner/workloads/n1ql.py | perfrunner/workloads/n1ql.py | INDEX_STATEMENTS = {
'basic': (
'CREATE INDEX by_city ON {}(city.f.f)',
'CREATE INDEX by_county ON {}(county.f.f)',
'CREATE INDEX by_realm ON {}(realm.f)',
),
'range': (
'CREATE INDEX by_coins ON {}(coins.f)',
'CREATE INDEX by_achievement ON {}(achievements)',
... | INDEX_STATEMENTS = {
'basic': (
'CREATE INDEX by_city ON `{}` (city.f.f)',
'CREATE INDEX by_county ON `{}` (county.f.f)',
'CREATE INDEX by_realm ON `{}` (`realm.f`)',
),
'range': (
'CREATE INDEX by_coins ON `{}` (coins.f)',
'CREATE INDEX by_achievement ON `{}` (achiev... | Correct syntax while creating indexes | Correct syntax while creating indexes
Change-Id: I90625647d8723531dbc7498d5d25e84ef1a3ed2b
Reviewed-on: http://review.couchbase.org/50007
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Michael Wiederhold <a17fed27eaa842282862ff7c1b9c8395a26ac320@couchbase.com>
| Python | apache-2.0 | dkao-cb/perfrunner,couchbase/perfrunner,EricACooper/perfrunner,pavel-paulau/perfrunner,mikewied/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,EricACooper/perfrunner,pavel-paulau/perfrunner,dkao-cb/perfrunner,vmx/perfrunner,thomas-couchbase/perfrunner,hsharsha/perfrunner,vmx/perfrunner,couchbase/perfrunner,tho... |
7d6c9ac443dd34784f00fd4d7bc0cbee904ed98f | src/python/cargo/temporal.py | src/python/cargo/temporal.py | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import timedelta
return timedelta(0)
def tznam... | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
from datetime import tzinfo
class UTC(tzinfo):
"""
The one true time zone.
"""
def utcoffset(self, dt):
"""
Return the offset to UTC.
"""
from datetime import timedelta
return timedelta(0)
def tznam... | Fix comment after dropping the pytz dependency. | Fix comment after dropping the pytz dependency.
| Python | mit | borg-project/cargo,borg-project/cargo |
3f454b3d66cb2cb19936ca591b7d873683eb1da5 | autoapi/base.py | autoapi/base.py | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.la... | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.lan... | Make context output behavior overridable | Make context output behavior overridable
| Python | mit | rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi |
85ffe172eb00c25d35990bab313be7a0194dddb1 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
... | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this... | Add version number to reflect orderedict bug | Add version number to reflect orderedict bug
| Python | mit | andychase/pipeless |
727cda368514f15ec53ef195ffcd6161d0796521 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
... | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
... | Add PermissionsLogging for log files. | Add PermissionsLogging for log files.
| Python | apache-2.0 | uw-it-aca/spacescout_web,uw-it-aca/spacescout_web,uw-it-aca/spacescout_web |
54b3663206d80aa2dbe4f93c6f8ce9fc45424bf3 | src/rf/apps/home/urls.py | src/rf/apps/home/urls.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSe... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSe... | Add URLs to redirect to home_page | Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404.
| Python | apache-2.0 | azavea/raster-foundry,aaronxsu/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,kdeloach/raster-foundry,kdeloach/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundr... |
f9b3670732d6b211e69873b098dd6f0f3de2f0cb | call_subprocess.py | call_subprocess.py | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = ca... | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(ca... | Add call subprocess and print output | Add call subprocess and print output
| Python | mit | MattMS/Python_3_examples |
4c1237d2969d735cfcf9f3c10cf27cb801996e32 | tests/test_integration.py | tests/test_integration.py | """Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Res... | """Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
... | Use Sauce Labs for selenium testing when available | Use Sauce Labs for selenium testing when available
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal |
c7beb58c8f5d6f0efd0f7abeb608f9de27a3ac28 | src/waldur_mastermind/marketplace_rancher/processors.py | src/waldur_mastermind/marketplace_rancher/processors.py | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
... | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
... | Allow to pass security_groups from marketplace to Rancher plugin. | Allow to pass security_groups from marketplace to Rancher plugin.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur |
9148b45f05fbc7697864967d343b0b63d91fa33b | temba/msgs/migrations/0037_backfill_recipient_counts.py | temba/msgs/migrations/0037_backfill_recipient_counts.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadc... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadc... | Add migration to backfill recipient counts | Add migration to backfill recipient counts
| Python | agpl-3.0 | reyrodrigues/EU-SMS,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,reyrodrigues/EU-SMS,pulilab/rapidpro,tsotetsi/textily-web,reyrodrigues/EU-SMS,ewheeler/rapidpro,tsotetsi/textily-web,ewheeler/rapidpr... |
3a2daf3c5acc9489705de13ffac8efce5c81c736 | pyrpl/test/test_redpitaya.py | pyrpl/test/test_redpitaya.py | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
... | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
... | Update test_connect to read password from env. variable | Update test_connect to read password from env. variable
| Python | mit | lneuhaus/pyrpl,lneuhaus/pyrpl,lneuhaus/pyrpl,lneuhaus/pyrpl |
55af5785d1aedff028f85229af691d5f59ba434a | python_cowbull_server/__init__.py | python_cowbull_server/__init__.py | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
f... | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import... | Remove parameter support (due to unittest module) and modify to print parameters on each run. | Remove parameter support (due to unittest module) and modify to print parameters on each run.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
82178af68dde7754cade01e9d5f092c9889ab957 | tomorrow_corrector/bot.py | tomorrow_corrector/bot.py | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them... | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_b... | Check if comment body contains misspelling, reply if so | Check if comment body contains misspelling, reply if so
| Python | mit | kshvmdn/reddit-bots |
f2a1dba207d870ebd287ebdf71f721b348c2ea36 | tests/test_redis_storage.py | tests/test_redis_storage.py | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
... | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
... | Remove hiro timeline context in redis test | Remove hiro timeline context in redis test
| Python | mit | alisaifee/sifr,alisaifee/sifr |
b6663ab3ee1791d9b1fd3aee24bf0509a4cebe84 | tests/test_youtube_cache.py | tests/test_youtube_cache.py | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path... | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Inco... | Add test for YouTube playlist | Add test for YouTube playlist
| Python | mit | learningequality/ricecooker,learningequality/ricecooker,learningequality/ricecooker,learningequality/ricecooker |
1f74b7ea4fdbcae6166477e56d1a6ccc81f6a5c8 | valohai_cli/exceptions.py | valohai_cli/exceptions.py | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_m... | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_m... | Make ConfigurationError also a ClickException | Make ConfigurationError also a ClickException
| Python | mit | valohai/valohai-cli |
273c7b89f02469ef1a6c53b6287412cd48881428 | matador/commands/deployment/deployment.py | matador/commands/deployment/deployment.py | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_te... | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_te... | Add splitlines method to substitute_keywords | Add splitlines method to substitute_keywords
| Python | mit | Empiria/matador |
5a27b1ff443db49a9c70cb6980653f615cca1b33 | meetup_facebook_bot/messenger/message_validators.py | meetup_facebook_bot/messenger/message_validators.py | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk... | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk... | Fix bug in like validator | Fix bug in like validator
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot |
fdfeb16f0ae6cdad7eaf223cf6b6dbd7586e63ec | tc_purger/handlers/purger.py | tc_purger/handlers/purger.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
... | Purge should always be attempted | Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77
| Python | mit | wikimedia/thumbor-purger |
b78a79da5753f2c379501daa921fc47d26350dc5 | datapackage_pipelines_fiscal/processors/update_model_in_registry.py | datapackage_pipelines_fiscal/processors/update_model_in_registry.py | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url... | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url... | Change where we're saving the datapackage | Change where we're saving the datapackage
| Python | mit | openspending/datapackage-pipelines-fiscal |
b4e92b84c275568041a4a9771a03ee0b9bb3fc48 | visram/tests/test_visram.py | visram/tests/test_visram.py | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(c... | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assert... | Fix test to properly compare chart types | Fix test to properly compare chart types
A variable was being compared to itself
| Python | mit | Spferical/visram |
4903afcec3d22d046c39a5b565366dc13472c6fd | zosimus/chartchemy/utils.py | zosimus/chartchemy/utils.py | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to ma... | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to ma... | Fix unicode error in series | Fix unicode error in series | Python | bsd-2-clause | pgollakota/zosimus,pgollakota/zosimus |
f1bdcde329b5b03e453f193720066914c908d46d | api/schemas.py | api/schemas.py | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
... | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allo... | Allow story location and section to be null | Allow story location and section to be null
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline |
4e4262f3d9cde4394d08681c517fcec4e2e9a336 | shellpython/tests/test_helpers.py | shellpython/tests/test_helpers.py | import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd(... | import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_... | Fix directory tests, __file__ may return relative path and now it is taken into consideration | Fix directory tests, __file__ may return relative path and now it is
taken into consideration
| Python | bsd-3-clause | lamerman/shellpy |
f1266219af530d1cc65019e7b7d40367c3daa024 | observatory/emaillist/methods.py | observatory/emaillist/methods.py | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsu... | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email ... | Update format to produce a valid link | Update format to produce a valid link
| Python | isc | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory |
049ec8a07aeb2344b7617ab5eb039c61f52fec45 | Pig-Latin/pig_latin.py | Pig-Latin/pig_latin.py | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
... | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").... | Add user functionality to Pig Latin class | Add user functionality to Pig Latin class
| Python | mit | Bigless27/Python-Projects |
50de60d8c1fe196ea18369d95ab328f9ef709159 | tools/pdtools/pdtools/devices/camera.py | tools/pdtools/pdtools/devices/camera.py | import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
... | import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)... | Use six.BytesIO for Python3 compatibility | Use six.BytesIO for Python3 compatibility
| Python | apache-2.0 | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop |
c2792efbb7c3b74c18ffede21b53adc42d887423 | social_website_django_angular/social_website_django_angular/urls.py | social_website_django_angular/social_website_django_angular/urls.py | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | Add login endpoint to URLs | Add login endpoint to URLs
| Python | mit | tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular |
9616ba8659aab6b60d95ea7e07699e258fb436e6 | openprovider/modules/__init__.py | openprovider/modules/__init__.py | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules impo... | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', N... | Implement an Optional Element function | Implement an Optional Element function
| Python | mit | AntagonistHQ/openprovider.py |
3b5094b86414a70460a54600d1cf7959fffea240 | nisl/io/tests/test_nifti_masker.py | nisl/io/tests/test_nifti_masker.py | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = N... | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
i... | Add test for NaN input values | Add test for NaN input values
| Python | bsd-3-clause | abenicho/isvr |
a9796c68c24c3e8a059c54aad6eee2d0b61a9041 | test/psyco.py | test/psyco.py | import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if fu... | import _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = ... | Use c-version of the selective compilation | Use c-version of the selective compilation
| Python | mit | tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni |
a9f9fc75411aededcb768adf32cc26efd64fe976 | sevenbridges/models/compound/tasks/__init__.py | sevenbridges/models/compound/tasks/__init__.py | from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in ... | from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):... | Add support for cwl1 task outputs so the name is preloaded. Add preloaded file type for task outputs. | Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs.
| Python | apache-2.0 | sbg/sevenbridges-python |
72382916560d275a0bb456ab4d5bd0e63e95cff4 | css_updater/git/webhook/handler.py | css_updater/git/webhook/handler.py | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for ... | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for ... | Add function to return URL | Add function to return URL
| Python | mit | neoliberal/css-updater |
e3c413e9642a026dba20c91ae8865c4e193ada5b | tests/create_service_test.py | tests/create_service_test.py | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file... | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.Sr... | Remove an aborted test and add a docstring explaining why this test-less testcase is still here. | Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
| Python | apache-2.0 | Yelp/paasta,Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta |
a0eaad7d4d4426c9d497409a6699929c71afeea7 | opps/views/generic/detail.py | opps/views/generic/detail.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class Detail... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_name... | Fix opps template engine (name list) on DetailView | Fix opps template engine (name list) on DetailView
| Python | mit | jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps |
9f69c886a1b5d75444e2efcfa29ce636d000b0a0 | microbower/__init__.py | microbower/__init__.py |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
... |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
... | Make the destination directory if it does not exist | Make the destination directory if it does not exist
| Python | isc | zenhack/microbower |
28afd50b0243cedf0796b57600bfbb5845623843 | warehouse/database/mixins.py | warehouse/database/mixins.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.... | Make the FetchedValue marked as for_update | Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631
| Python | bsd-2-clause | davidfischer/warehouse |
059125f04430dd525205fe9b4331ac87c5556d8c | thumbor_cloud_storage/loaders/cloud_storage_loader.py | thumbor_cloud_storage/loaders/cloud_storage_loader.py | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
b... | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
b... | Return None on missing object | Return None on missing object
| Python | mit | Superbalist/thumbor-cloud-storage |
0d261edf436fac06d8a8bd35fba34e1773aee460 | alexandria/__init__.py | alexandria/__init__.py | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(b... | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI applic... | Check for some required settings | Check for some required settings
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria |
1265221d0300ff214cef12dc244f745c7f2ec316 | tests/core/ast_transforms/test_basic_sanity.py | tests/core/ast_transforms/test_basic_sanity.py |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
r... |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_chil... | Add a failing, coverage-increasing test | Add a failing, coverage-increasing test
| Python | mit | dwillmer/fastats,fastats/fastats |
b22b292ec2b839d611738928f41c79723146ea15 | readthedocs/core/migrations/0005_migrate-old-passwords.py | readthedocs/core/migrations/0005_migrate-old-passwords.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database does... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
... | Migrate old passwords without "set_unusable_password" | Migrate old passwords without "set_unusable_password"
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org |
d70360601669f9e58072cd121de79896690471fd | buildlet/datastore/tests/test_inmemory.py | buildlet/datastore/tests/test_inmemory.py | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
... | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixIn... | Fix and add tests for datastore.inmemory | Fix and add tests for datastore.inmemory
| Python | bsd-3-clause | tkf/buildlet |
eba8a0796242d18807e1cace97bd476386ade0aa | functions.py | functions.py | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
... | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
... | Put in a try for shares function | Put in a try for shares function
| Python | mit | miklevin/pipulate,miklevin/pipulate,whofman/my-pipulate,whofman/my-pipulate,miklevin/pipulate,whofman/my-pipulate |
2cfe6e6c9284dfffba2943a8562e38844b6ba089 | temba/campaigns/migrations/0015_campaignevent_message_new.py | temba/campaigns/migrations/0015_campaignevent_message_new.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = ap... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = ap... | Fix migration to work with flows with no base_language | Fix migration to work with flows with no base_language
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro |
53de65c29fe4bc3961258bb160210c32ddfaeae4 | django/website/contacts/tests/test_validators.py | django/website/contacts/tests/test_validators.py | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now... | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now... | Add test for year_to_now with non-integer values | Add test for year_to_now with non-integer values | Python | agpl-3.0 | aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana,daniell/kashana,daniell/kashana,daniell/kashana,aptivate/kashana,daniell/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana |
43ca79dbd2067ba9733bf43f81b43aa048bbd900 | seaweb_project/jobs/serializers.py | seaweb_project/jobs/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source=... | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source=... | Implement validation for structure and topology files. | Implement validation for structure and topology
files. | Python | mit | grollins/sea-web-django |
cf7e1c52a0242814cf9e621a62414252110765a2 | feincms/content/rss/models.py | feincms/content/rss/models.py | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre... | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_co... | Add last_updated field to RSSContent | Add last_updated field to RSSContent
| Python | bsd-3-clause | joshuajonah/feincms,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,feincms/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,feincms/feincms,pjdelport/feincms,hgrimelid/feincms,mjl/feincms,joshuajonah/feincms,mjl/feincms,hgrimelid/feincms,michaelkuty/feincms... |
df9dd41cfd7140a266f41296024c4e6ba59f25ec | server/plugins/cryptstatus/cryptstatus.py | server/plugins/cryptstatus/cryptstatus.py | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'F... | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Stat... | Fix missed plugin code update. | Fix missed plugin code update.
This `Meta` business is from an earlier draft.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal |
7a5161739b9348e577f484143e56a37f327104c6 | src/gramcore/transformations/geometric.py | src/gramcore/transformations/geometric.py | """
"""
def resize(parameters):
pass
def rotate(parameters):
pass
| """Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters... | Add initial resize and rotate, no tests yet | Add initial resize and rotate, no tests yet
| Python | mit | cpsaltis/pythogram-core |
8433fe04ad1230329de2c209a8625cd4b36b63f8 | src/sentry/api/serializers/models/grouptagvalue.py | src/sentry/api/serializers/models/grouptagvalue.py | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.valu... | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
... | Implement labels on group tag values | Implement labels on group tag values
| Python | bsd-3-clause | gencer/sentry,drcapulet/sentry,vperron/sentry,pauloschilling/sentry,kevinlondon/sentry,ifduyue/sentry,zenefits/sentry,JamesMura/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,ngonzalvez/sentry,gg7/sentry,mvaled/sentry,JTCunning/sentry,alexm92/sentry,hongliang5623/sentry,Kryz/sentry,JackDanger/sentry,gg7/sentry,TedaL... |
a222d268ec1c12466db48bbfcd58d8ecf2907805 | echo_server.py | echo_server.py | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
... | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
... | Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests | Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests
| Python | mit | jefrailey/network_tools |
67c291b6acf0943a55626be8d40e7134012f9271 | entity/hero.py | entity/hero.py | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_d... | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_d... | Modify Hero :: Life + 2 | Modify Hero :: Life + 2
| Python | unlicense | Bobbyshow/Avoid |
d1bae39247a1184f7d61fa015897103af2069703 | pinax/notifications/urls.py | pinax/notifications/urls.py | from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
| from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
| Make compatible with Django 1.9 | Make compatible with Django 1.9
| Python | mit | pinax/pinax-notifications,pinax/pinax-notifications |
bf343f88ee1eb16bb1268bc70ecb03f25ab338cf | Sketches/RJL/Util/DataSource.py | Sketches/RJL/Util/DataSource.py | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
... | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
... | Work around a minor bug in ConsoleEchoer - yield before sending a complete message. | Work around a minor bug in ConsoleEchoer - yield before sending a
complete message.
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia |
dc140f6c7bc6fe03ec60a5b1029d7bc7463d2a0e | pydarkstar/scrubbing/scrubber.py | pydarkstar/scrubbing/scrubber.py | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
... | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBro... | Add support for absolute URL in request | Add support for absolute URL in request
| Python | mit | AdamGagorik/pydarkstar |
fbd49474eb9d0d80874048964ca08295e8c040cb | webwatcher/fetcher/simple.py | webwatcher/fetcher/simple.py | import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
| import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
| Sort keys in JSON fetcher for consistent results | Sort keys in JSON fetcher for consistent results | Python | mit | kibitzr/kibitzr,kibitzr/kibitzr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.