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 |
|---|---|---|---|---|---|---|---|---|---|
9272fd30c70e946bfcc003a2936f57efdaa05bd7 | bindings/jupyroot/python/JupyROOT/__init__.py | bindings/jupyroot/python/JupyROOT/__init__.py | #-----------------------------------------------------------------------------
# Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
# Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN
#-----------------------------------------------------------------------------
############################################... | #-----------------------------------------------------------------------------
# Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
# Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN
#-----------------------------------------------------------------------------
############################################... | Update logic to check for IPython | [JupyROOT] Update logic to check for IPython
To sync it with what was already introduced in ROOT/__init__.py
| Python | lgpl-2.1 | olifre/root,olifre/root,root-mirror/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,olifre/root |
cee60151acf606a4e22a92c51066b7fb720f35a3 | application/models.py | application/models.py | """
Database Emulator for the teammetrics project
Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats
"""
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.n... | """
Database Emulator for the teammetrics project
Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats
"""
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.n... | Update the API to make it more semantic. | Update the API to make it more semantic.
| Python | mit | swvist/debmetrics,swvist/debmetrics |
5c6f6b63450651b2860e960a4fb16c787537d3ed | kcm.py | kcm.py | #!/usr/bin/env python
"""kcm.
Usage:
kcm (-h | --help)
kcm --version
kcm (init | describe | reconcile) [--conf-dir=<dir>]
kcm isolate [--conf-dir=<dir>] --pool=<pool> <command> [-- <args> ...]
Options:
-h --help Show this screen.
--version Show version.
--conf-dir=<dir> KCM configurat... | #!/usr/bin/env python
"""kcm.
Usage:
kcm (-h | --help)
kcm --version
kcm (init | describe | reconcile) [--conf-dir=<dir>]
kcm isolate [--conf-dir=<dir>] --pool=<pool> <command> [-- <args> ...]
Options:
-h --help Show this screen.
--version Show version.
--conf-dir=<dir> KCM configurat... | Fix pool names in KCM help. | Fix pool names in KCM help.
| Python | apache-2.0 | Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes |
5c7b33574550d37454b4362fa0896a4dad6e98d1 | aesthetic/output/gif.py | aesthetic/output/gif.py | from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = Im... | from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = Im... | Optimize GIF palette (too many colors right now), better GIF timing options. | Optimize GIF palette (too many colors right now), better GIF timing options.
| Python | apache-2.0 | gnoack/aesthetic |
cb0c7ba021a3896e7ad726178bc686775829de34 | appengine/components/components/machine_provider/utils.py | appengine/components/components/machine_provider/utils.py | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from components import net
from components import utils
MACHINE_PROVIDER... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from google.appengine.ext import ndb
from components import net
from comp... | Allow users of the Machine Provider to specify the dev instance for API calls | Allow users of the Machine Provider to specify the dev instance for API calls
BUG=489837
Review URL: https://codereview.chromium.org/1572793002
| Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py |
4fe55df3bb668a2eafdb65a3a31ad27ffa5dc3c2 | pytable.py | pytable.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from operator import itemgetter
import monoidal_tables as mt
from monoidal_tables import renderers
if __name__ == '__main__':
table = (mt.integer('X', itemgetter('x')) +
mt.integer('Y', itemgetter('y')) +
mt.align_center(mt... | # -*- coding: utf-8 -*-
from __future__ import print_function
from operator import itemgetter
import monoidal_tables as mt
from monoidal_tables import renderers
if __name__ == '__main__':
table = (mt.integer('X', itemgetter('x')) +
mt.set_class(mt.integer('Y', itemgetter('y')), 'col-y') +
... | Update example to show HTML class | Update example to show HTML class
| Python | bsd-3-clause | lubomir/monoidal-tables |
444e1951950e77f2b0e35d2921026bcadff6881b | backend/breach/forms.py | backend/breach/forms.py | from django.forms import ModelForm
from breach.models import Target
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | Add form validation for victim | Add form validation for victim
| Python | mit | dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esara... |
fe2ce4e21530daffacbd654790a161019dd2de83 | backend/breach/forms.py | backend/breach/forms.py | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | Add form for /attack with victim id | Add form for /attack with victim id
| Python | mit | dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dim... |
d4398d068d4fdf6364869cd01237f53438e2674c | blinkylib/blinkytape.py | blinkylib/blinkytape.py | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... | Fix the slow-mo gradient bug by flushing BlinkyTape response on updates | Fix the slow-mo gradient bug by flushing BlinkyTape response on updates
| Python | mit | jonspeicher/blinkyfun |
5723dbbf2dbebf349c61a00ee4ea665b4009bd18 | spur/io.py | spur/io.py | import threading
class IoHandler(object):
def __init__(self, in_out_pairs, read_all):
self._handlers = [
OutputHandler(file_in, file_out)
for file_in, file_out
in in_out_pairs
]
self._read_all = read_all
def wait(self):
handler_resul... | import threading
class IoHandler(object):
def __init__(self, in_out_pairs, read_all):
self._handlers = [
OutputHandler(file_in, file_out)
for file_in, file_out
in in_out_pairs
]
self._read_all = read_all
def wait(self):
handler_resul... | Remove references to stdout in OutputHandler | Remove references to stdout in OutputHandler
| Python | bsd-2-clause | mwilliamson/spur.py |
800ffecbed76f306806642546ed949153c8414c3 | astropy/vo/samp/tests/test_hub_proxy.py | astropy/vo/samp/tests/test_hub_proxy.py | from ..hub_proxy import SAMPHubProxy
from ..hub import SAMPHubServer
from ..client import SAMPClient
class TestHubProxy(object):
def setup_method(self, method):
self.hub = SAMPHubServer(web_profile=False)
self.hub.start()
self.proxy = SAMPHubProxy()
self.proxy.connect()
def... | import os
import tempfile
from ..hub_proxy import SAMPHubProxy
from ..hub import SAMPHubServer
from ..client import SAMPClient
class TestHubProxy(object):
def setup_method(self, method):
fileobj, self.lockfile = tempfile.mkstemp()
self.hub = SAMPHubServer(web_profile=False,
... | Use temporary SAMP lock file | Use temporary SAMP lock file
| Python | bsd-3-clause | saimn/astropy,DougBurke/astropy,joergdietrich/astropy,AustereCuriosity/astropy,lpsinger/astropy,lpsinger/astropy,tbabej/astropy,kelle/astropy,tbabej/astropy,mhvk/astropy,kelle/astropy,dhomeier/astropy,larrybradley/astropy,DougBurke/astropy,larrybradley/astropy,joergdietrich/astropy,dhomeier/astropy,stargaser/astropy,as... |
9a5aee262b5a89e5a22e9e1390e23898a5373627 | byceps/util/jobqueue.py | byceps/util/jobqueue.py | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from rq imp... | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from flask ... | Fix `get_queue` call in `enqueue` | Fix `get_queue` call in `enqueue`
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps |
8653f2c0e63fecd5617dfa063878c846ddafcf97 | tests/test_add_language/test_update_language_list.py | tests/test_add_language/test_update_language_list.py | # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_li... | # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_li... | Add additional checks to update_language_list test | Add additional checks to update_language_list test
Also make language variable names independent of their actual values.
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest |
13b387af53edcce78f95adc2ad96e87bb6df75e6 | beetle_preview/__init__.py | beetle_preview/__init__.py | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config['port']
self.builder = builder
def serve(self):
os.chdir(self.directory)
... | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config.get('port', 5000)
self.builder = builder
def serve(self):
os.chdir(self.director... | Set up a default port of 5000 so it won't fail if you forget to specify one in config.yaml | Set up a default port of 5000 so it won't fail if you forget to specify one in config.yaml
| Python | mit | cknv/beetle-preview |
a32270be3ef07fa4a8289374d779ec44f834834c | examples/chr12_plot.py | examples/chr12_plot.py | import tadtool.tad as tad
import tadtool.plot as tp
# load regions data set
regions = tad.HicRegionFileReader().regions("chr12_20-35Mb_regions.bed")
# load matrix
matrix = tad.HicMatrixFileReader().matrix("chr12_20-35Mb.matrix.txt")
# prepare plot
tad_plot = tp.TADtoolPlot(matrix, regions, norm='lin', max_dist=10000... | import tadtool.tad as tad
import tadtool.plot as tp
# load regions data set
regions = tad.HicRegionFileReader().regions("chr12_20-35Mb_regions.bed")
# load matrix
matrix = tad.HicMatrixFileReader().matrix("chr12_20-35Mb.matrix.txt")
# prepare plot
tad_plot = tp.TADtoolPlot(matrix, regions, norm='lin', max_dist=10000... | Make sure example also runs if executed as scipt | Make sure example also runs if executed as scipt
| Python | mit | vaquerizaslab/tadtool |
97645cf2d1dec9b59f30a460de7f142d1f6bc01b | bin/purge_database_json.py | bin/purge_database_json.py | from pymongo import MongoClient
import json
import sys
from emission.core.get_database import get_db, get_section_db
from emission.tests import common
def purgeData(userName):
Sections=get_section_db()
common.purgeData(Sections)
def purgeAllData():
db = get_db()
common.dropAllCollections(db)
if __name__ == '... | from pymongo import MongoClient
import json
import sys
from emission.core.get_database import get_db, get_section_db
import emission.tests.common as etc
def purgeAllData():
db = get_db()
etc.dropAllCollections(db)
if __name__ == '__main__':
if len(sys.argv) != 1:
print "USAGE: %s" % sys.argv[0]
exit(1)
... | Fix obsolete code + import | Fix obsolete code + import
I can now run this without anything crashing
```
C02KT61MFFT0:e-mission-server shankari$ ./e-mission-py.bash bin/purge_database_json.py localhost
USAGE: bin/purge_database_json.py
C02KT61MFFT0:e-mission-server shankari$ ./e-mission-py.bash bin/purge_database_json.py
C02KT61MFFT0:e-mission-s... | Python | bsd-3-clause | e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server |
3f62fb788beea1ac32d514d549fdaeaaae0f3292 | mesonbuild/scripts/__init__.py | mesonbuild/scripts/__init__.py | #!/usr/bin/env python3
# Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by appl... | # Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | Remove unneeded shebang line that was triggering some linters. | Remove unneeded shebang line that was triggering some linters.
| Python | apache-2.0 | ernestask/meson,aaronp24/meson,rhd/meson,mesonbuild/meson,centricular/meson,mesonbuild/meson,wberrier/meson,rhd/meson,mesonbuild/meson,fmuellner/meson,trhd/meson,mesonbuild/meson,MathieuDuponchelle/meson,centricular/meson,centricular/meson,QuLogic/meson,jeandet/meson,trhd/meson,MathieuDuponchelle/meson,thiblahute/meson... |
7805dbadd44c262223ae02d358aa251b4df5d0b0 | astropy/table/__init__.py | astropy/table/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .table import Column, Table, TableColumns, Row, MaskedColumn
from .np_utils import TableMergeError
from .operations import join, hstack, vstack
# Import routines that connect readers/writers to astropy.table
from ..io.ascii import connect
from ..io.f... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .table import Column, Table, TableColumns, Row, MaskedColumn, GroupedTable
from .np_utils import TableMergeError
from .operations import join, hstack, vstack
# Import routines that connect readers/writers to astropy.table
from ..io.ascii import conne... | Add GroupedTable to the top-level table classes | Add GroupedTable to the top-level table classes
| Python | bsd-3-clause | bsipocz/astropy,StuartLittlefair/astropy,joergdietrich/astropy,saimn/astropy,stargaser/astropy,larrybradley/astropy,lpsinger/astropy,pllim/astropy,funbaker/astropy,mhvk/astropy,joergdietrich/astropy,AustereCuriosity/astropy,funbaker/astropy,pllim/astropy,larrybradley/astropy,mhvk/astropy,AustereCuriosity/astropy,pllim/... |
357af01554cca6197d07a4a408c02921e70a14eb | cozify/multisensor.py | cozify/multisensor.py | import time
from influxdb import InfluxDBClient
from influxdb import SeriesHelper
from . import config
# expects Cozify devices type json data
def getMultisensorData(data):
out = []
for device in data:
state=data[device]['state']
devtype = state['type']
if devtype == 'STATE_MULTI_SEN... | import time
from . import config
# expects Cozify devices type json data
def getMultisensorData(data):
out = []
for device in data:
state=data[device]['state']
devtype = state['type']
if devtype == 'STATE_MULTI_SENSOR':
name=data[device]['name']
if 'lastSeen' i... | Remove outdated imports, oops sorry. | Remove outdated imports, oops sorry.
| Python | mit | Artanicus/python-cozify,Artanicus/python-cozify |
1fa57ad194735cc7f6b4170d2c296d9c8b3ce4c3 | website_analytics_piwik/__openerp__.py | website_analytics_piwik/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | Add Odoo Community Association (OCA) in authors | Add Odoo Community Association (OCA) in authors
| Python | agpl-3.0 | incaser/website,pedrobaeza/website,Benniphx/website,LasLabs/website,Antiun/website,acsone/website,open-synergy/website,hbrunn/website,BT-jmichaud/website,gfcapalbo/website,brain-tec/website,sergio-incaser/website,nicolas-petit/website,syci/website-odoo,xpansa/website,open-synergy/website,Yajo/website,nicolas-petit/webs... |
2f5095c7020a1b6906981e75491007ce72ec5aac | antimarkdown/handlers.py | antimarkdown/handlers.py | # -*- coding: utf-8 -*-
"""antimarkdown.handlers -- Element handlers for converting HTML Elements/subtrees to Markdown text.
"""
from collections import deque
from antimarkdown import nodes
def render(*domtrees):
if not domtrees:
return u''
root = nodes.Root()
for dom in domtrees:
build_... | # -*- coding: utf-8 -*-
"""antimarkdown.handlers -- Element handlers for converting HTML Elements/subtrees to Markdown text.
"""
from collections import deque
from antimarkdown import nodes
def render(*domtrees):
if not domtrees:
return u''
root = nodes.Root()
for dom in domtrees:
build_... | Handle case with empty block | Handle case with empty block
| Python | mit | Crossway/antimarkdown,Crossway/antimarkdown |
3d943c113c244f4b285c2493004de48b754fd8d8 | bin/bson2json.py | bin/bson2json.py | #!/usr/bin/env python
"""
Simple utility to display BSON files.
"""
import sys
import errno
from bson.json_util import dumps
import bson_lazy
usage = '''
Usage: %s FILE... [OPTIONS]
Options:
--pretty Pretty print JSON
--help Print this help message
'''.strip() % sys.argv[0]
def main():
args = sys.argv[1... | #!/usr/bin/env python
"""
Simple utility to display BSON files.
"""
import sys
import errno
from bson.json_util import dumps
import bson_lazy
usage = '''
Usage: %s FILE... [OPTIONS]
Options:
--pretty Pretty print JSON
--help Print this help message
'''.strip() % sys.argv[0]
def main():
args = sys.argv[1... | Hide stacktrace for keyboard interrupts | Hide stacktrace for keyboard interrupts
| Python | mit | ShinNoNoir/bson_lazy |
b191a78d847167616dc38756c9fb450e5eb95c70 | utils/database.py | utils/database.py | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | Add new-line at EOF, when dumping userdb | Add new-line at EOF, when dumping userdb
| Python | mit | wolfy1339/Python-IRC-Bot |
cb20f8d81832aafb2ec6f70f135b0a027b14dc91 | processors/fix_changeline_budget_titles.py | processors/fix_changeline_budget_titles.py | import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_json... | import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_json... | Fix bug in changeling title fix - it used to remove some lines on the way... | Fix bug in changeling title fix - it used to remove some lines on the way...
| Python | mit | omerbartal/open-budget-data,omerbartal/open-budget-data,OpenBudget/open-budget-data,OpenBudget/open-budget-data |
2d616924f7dc02458bf0b13a396f3f91b039d321 | hub/views.py | hub/views.py | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import FormBuilderPreference
from django.http import HttpResponseRedirect
from django.core.management import call_command
@api_view(['GET'])
def switch_builder(request):
'''
very un-restful, but for ease o... | from .models import FormBuilderPreference
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.contrib.auth.decorators import login_required
@login_required
def switch_builder(request):
'''
very un-restful, but for ease of testing, a quick 'GET' is hard to b... | Use `login_required` decorator on `switch_builder` view | Use `login_required` decorator on `switch_builder` view
| Python | agpl-3.0 | kobotoolbox/kpi,onaio/kpi,kobotoolbox/kpi,onaio/kpi,onaio/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi |
b5e6952841d19e75b308fb2ab16ca5b098d376a9 | django-tutorial/tutorial/polls/views.py | django-tutorial/tutorial/polls/views.py | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from polls.models import Question
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('pub_date')[:5]
context = {'latest_question_list': latest_question_list}
ret... | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Question
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('pub_date')[:5]
... | Update the view for the voting | Update the view for the voting
| Python | mit | domenicosolazzo/practice-django,domenicosolazzo/practice-django,domenicosolazzo/practice-django |
2fc45a6a0e2ba1efe06b4282234cf13c0ccd5b7d | dj_experiment/conf.py | dj_experiment/conf.py | from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix =... | import os
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'... | Add default base data dir for experiments | Add default base data dir for experiments
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment |
9473dec555f59a8f70bfd70bd6568bbcb8827f78 | glaive/glaive.py | glaive/glaive.py | import sklearn.cross_validation as cv
from sklearn import tree
import pandas as py
import numpy as np
| import sklearn.cross_validation as cv
from sklearn import tree
import pandas as pd
import numpy as np
import os.path
import pprint
def readData(maxReplayCount = 749):
"""reads the data from .arff files (Weka Attribute-Relation files)
maxReplayCount is <= 749
returns:
data - a list of datafra... | Add parsing to enable vectors | Add parsing to enable vectors
| Python | mit | peixian/Ultralisk,peixian/Ultralisk,peixian/Ultralisk |
ceea28b5f07d43644bbefacb39bd1f2b40297e36 | xero/constants.py | xero/constants.py | # Public/Private
XERO_BASE_URL = "https://api.xero.com"
REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % XERO_BASE_URL
AUTHORIZE_URL = "%s/oauth/Authorize" % XERO_BASE_URL
ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % XERO_BASE_URL
XERO_API_URL = "%s/api.xro/2.0" % XERO_BASE_URL
# Partner
PARTNER_XERO_BASE_URL = "https://a... | # Public/Private
XERO_BASE_URL = "https://api.xero.com"
REQUEST_TOKEN_URL = "%s/oauth/RequestToken" % XERO_BASE_URL
AUTHORIZE_URL = "%s/oauth/Authorize" % XERO_BASE_URL
ACCESS_TOKEN_URL = "%s/oauth/AccessToken" % XERO_BASE_URL
XERO_API_URL = "%s/api.xro/2.0" % XERO_BASE_URL
# Partner
PARTNER_XERO_BASE_URL = "https://a... | Update partner authorize URL to match changes by Xero | Update partner authorize URL to match changes by Xero | Python | bsd-3-clause | skillflip/pyxero |
3ebb80476553e8228c6709a3e6ff75ea42fff586 | properties/property.py | properties/property.py | """
Property class
"""
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self):
pass
| """
Property class
"""
class Property(object):
"""
a monopoly property that items on the
board can inherit from
"""
def __init__(self, name, price, baseRent, rentWithHouses, mortgageValue, owner=None, houseCost, hotelCost):
self.name = name
self.owner = owner
self.price = ... | Add some basic transactional methdos to properties | Add some basic transactional methdos to properties
| Python | mit | markthethomas/monopoly |
90f2c22a9243855546c8689c5773be837e05aa47 | core/views.py | core/views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainCon... | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainCon... | Move paginator settings to base list view | Move paginator settings to base list view
| Python | mit | sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa |
de70b1549f33484da87d6958d9f9714e7da50956 | git_upstream_diff.py | git_upstream_diff.py | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import sys
import subprocess2
from git_common import current_branch, get_or_create_merge_base, config_list
from git_c... | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import sys
import subprocess2
import git_common as git
def main(args):
default_args = git.config_list('depot-tools... | Make udiff print reasonable errors while not on a branch. | Make udiff print reasonable errors while not on a branch.
R=agable@chromium.org
BUG=
Review URL: https://codereview.chromium.org/212493002
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@259647 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | kromain/chromium-tools,cybertk/depot_tools,npe9/depot_tools,HackFisher/depot_tools,kromain/chromium-tools,duongbaoduy/gtools,Neozaru/depot_tools,eatbyte/depot_tools,kaiix/depot_tools,fracting/depot_tools,CoherentLabs/depot_tools,kromain/chromium-tools,Chilledheart/depot_tools,Chilledheart/depot_tools,kromain/chromium-t... |
1d6670165dd74084813b38032cfddb6d33cd9d7a | xdc-plugin/tests/compare_output_json.py | xdc-plugin/tests/compare_output_json.py | #!/usr/bin/env python3
"""
This script extracts the top module cells and their corresponding parameters
from json files produced by Yosys.
The return code of this script is used to check if the output is equivalent.
"""
import sys
import json
parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"]
def read_cells(js... | #!/usr/bin/env python3
"""
This script extracts the top module cells and their corresponding parameters
from json files produced by Yosys.
The return code of this script is used to check if the output is equivalent.
"""
import sys
import json
import argparse
parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"]
d... | Refactor test output comparison script | XDC: Refactor test output comparison script
Signed-off-by: Tomasz Michalak <a2fdaa543b4cc5e3d6cd8672ec412c0eb393b86e@antmicro.com>
| Python | apache-2.0 | SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins,chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins,chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plu... |
c58322ba39708ac7bb6d48eacbb5e1011c676b8f | bluebottle/utils/monkey_patch_parler.py | bluebottle/utils/monkey_patch_parler.py | import parler.appsettings
from parler.utils.conf import add_default_language_settings
from bluebottle.clients import properties
appsettings = parler.appsettings
class TenantAwareParlerAppsettings(object):
@property
def PARLER_DEFAULT_LANGUAGE_CODE(self):
return properties.LANGUAGE_CODE
@propert... | import parler.appsettings
from parler.utils.conf import add_default_language_settings
from bluebottle.clients import properties
appsettings = parler.appsettings
class TenantAwareParlerAppsettings(object):
@property
def PARLER_DEFAULT_LANGUAGE_CODE(self):
return properties.LANGUAGE_CODE
@propert... | Add all languages to fallback languages | Add all languages to fallback languages
BB-12799 #resolve
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
2367a5454660ffec6b4bab11939edc52197be791 | guv/__init__.py | guv/__init__.py | version_info = (0, 20, 0)
__version__ = '.'.join(map(str, version_info))
try:
from . import greenthread
from . import greenpool
from . import queue
from . import timeout
from . import patcher
from . import server
from .hubs.trampoline import gyield
import greenlet
import pyuv_cffi ... | version_info = (0, 21, 0)
__version__ = '.'.join(map(str, version_info))
try:
from . import greenpool
from . import queue
from .hubs.trampoline import gyield
from .greenthread import sleep, spawn, spawn_n, spawn_after, kill
from .greenpool import GreenPool, GreenPile
from .timeout import Timeou... | Reorganize imports (and bump version) | Reorganize imports (and bump version)
| Python | mit | veegee/guv,veegee/guv |
26f08f0f3275c352351f27a36674b65c6e6d171f | messaging.py | messaging.py | import sms_generator
import sms_twilio
import db
import config
def broadcast_procedure(procedure, location, duration, doctor):
message = sms_generator.new_procedure_message(procedure, location, duration, doctor)
recipients = db.get_all_students()
print(recipients)
for recipient in recipients:
... | import sms_generator
import sms_twilio
import db
import config
list_of_opportunities = []
def get_friendly_ref(id):
if not list_of_opportunities:
new_ref = 1
new_opportunity = dict(id=str(id), ref=new_ref)
list_of_opportunities.append(new_opportunity)
print(str.format("New ref is ... | Add code for automatically assigning message_refs | Add code for automatically assigning message_refs
| Python | mit | nhshd-slot/SLOT,bsharif/SLOT,bsharif/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT,bsharif/SLOT |
c21bea6d80287d7c42b3634a7612e4e8cbc419be | plotnine/exceptions.py | plotnine/exceptions.py | from textwrap import dedent
import warnings
# Statsmodels is slow to fix upstream future warnings
# This module is imported before the stats module so
# so any FutureWarnings with the imports are suppressed
warnings.filterwarnings(
'ignore',
category=FutureWarning,
module='statsmodels')
warnings.filterwar... | from textwrap import dedent
import warnings
# Statsmodels is slow to fix upstream future warnings
# This module is imported before the stats module so
# so any FutureWarnings with the imports are suppressed
warnings.filterwarnings(
'ignore',
category=FutureWarning,
module='statsmodels')
warnings.filterwar... | Print warnings on one line & no code | ENH: Print warnings on one line & no code
| Python | mit | has2k1/plotnine,has2k1/plotnine |
9c396e6f75bac114068421740b7faedbe3915966 | hermes/views.py | hermes/views.py | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... | Allow slug to be passed directly into the view | Allow slug to be passed directly into the view | Python | mit | emilian/django-hermes |
70d7058e5a45699082dc5a834e462f70ebe30345 | h5py/tests/test_h5o.py | h5py/tests/test_h5o.py | import pytest
from .common import TestCase
from h5py import File
class TestException(Exception):
pass
def throwing(name, obj):
print(name, obj)
raise TestException("throwing exception")
class TestVisit(TestCase):
def test_visit(self):
fname = self.mktemp()
fid = File(fname, 'w')
... | import pytest
from .common import TestCase
from h5py import File
class SampleException(Exception):
pass
def throwing(name, obj):
print(name, obj)
raise SampleException("throwing exception")
class TestVisit(TestCase):
def test_visit(self):
fname = self.mktemp()
fid = File(fname, 'w')... | Rename exception to squash test warning | Rename exception to squash test warning
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py |
aa867937c1e9842bd58c4006d4497589132a5c92 | heat/objects/fields.py | heat/objects/fields.py | # Copyright 2014 Intel Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | # Copyright 2014 Intel Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Make JsonField actually do it's work | Make JsonField actually do it's work
This code will be used when objects are registered.
Change-Id: I2f1b3e2dd5584335e318b936984c227050bbe699
Partial-Bug: 1491258
| Python | apache-2.0 | cwolferh/heat-scratch,noironetworks/heat,openstack/heat,steveb/heat,steveb/heat,dims/heat,jasondunsmore/heat,jasondunsmore/heat,cwolferh/heat-scratch,openstack/heat,dims/heat,noironetworks/heat |
406abe34d82aeb7d72d7f4dc96d44d57807f928b | devilry/devilry_authenticate/urls.py | devilry/devilry_authenticate/urls.py | from devilry.devilry_authenticate.views import CustomLoginView
from django.conf.urls import url
from django_cradmin.apps.cradmin_authenticate.views import logout
urlpatterns = [
url(r'^login$', CustomLoginView.as_view(), name='cradmin-authenticate-login'),
url(r'^logout$', logout.cradmin_logoutview, name='cra... | from devilry.devilry_authenticate.views import CustomLoginView
from django.conf.urls import url
from django_cradmin.apps.cradmin_authenticate.views import logout
urlpatterns = [
url(r'^login$', CustomLoginView.as_view(), name='cradmin-authenticate-login'),
url(r'^logout$', logout.cradmin_logoutview, name='cra... | Add placeholder for feide oauth callback. | authenticate: Add placeholder for feide oauth callback.
| Python | bsd-3-clause | devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,devilry/devilry-django |
d39066a1de376e0c824510592c1e5e0c5edc46a3 | hitcounter.py | hitcounter.py | from flask import Flask
from redis import Redis
import os
hitcounter = Flask(__name__)
redis = Redis(host='redis', port=6379)
who = os.getenv('WHO', 'World')
@hitcounter.route('/')
def hello():
redis.incr('hits')
return 'Hello %s! I have been seen %s times.' % (who,redis.get('hits'))
if __name__ == "__main__... | from flask import Flask
from redis import Redis
import os
hitcounter = Flask(__name__)
redis = Redis(host='redis', port=6379)
who = os.getenv('WHO', 'World')
@hitcounter.route('/')
def hello():
redis.incr('hits')
return '<strong>Hello %s! I have been seen %s times.</strong>' % (who,redis.get('hits'))
if __na... | Change font style to <strong> | Change font style to <strong>
| Python | bsd-2-clause | kkonstan/hitcounter |
c7ac2b1805bd82bdeef3227fc34149431c161df7 | yesimeanit/showoff/newsletter_subscriptions/admin.py | yesimeanit/showoff/newsletter_subscriptions/admin.py | from django.contrib import admin
from .models import NewsletterSubscription
admin.site.register(NewsletterSubscription,
list_display=('email', 'is_active', 'confirmed_on', 'unsubscribed_on'),
list_filter=('is_active',),
)
| from django.contrib import admin
from .models import NewsletterSubscription
admin.site.register(NewsletterSubscription,
list_display=('email', 'is_active', 'confirmed_on', 'unsubscribed_on'),
list_filter=('is_active',),
search_fields=('code', 'email', 'first_name', 'last_name'),
)
| Add search fields for newsletter subscriptions | Add search fields for newsletter subscriptions
| Python | bsd-3-clause | guetux/django-yesimeanit |
d5e3d6c3ca285f1037f284cfb78e279c2d1032ec | dojopuzzles/core/urls.py | dojopuzzles/core/urls.py | from django.urls import path
from core import views
app_name = "core"
urlpatterns = [
path("home/", views.home, name="home"),
path("about/", views.about, name="about"),
]
| from core import views
from django.urls import path
app_name = "core"
urlpatterns = [
path("", views.home, name="home"),
path("about/", views.about, name="about"),
]
| Fix route for main page | Fix route for main page
| Python | mit | rennerocha/dojopuzzles |
326bebb58242981ec66f257525e5c5f58fae9196 | example/article/admin.py | example/article/admin.py | from django.contrib import admin
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget
from parler.admin import TranslatableAdmin
from .models import Article
from parler.forms import TranslatableModelForm, TranslatedField
class ArticleAdminForm(TranslatableModelForm):
"""
Example ... | from django.contrib import admin
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget
from parler.admin import TranslatableAdmin
from .models import Article
from parler.forms import TranslatableModelForm, TranslatedField
class ArticleAdminForm(TranslatableModelForm):
"""
Example ... | Add list_filter to example ArticleAdmin | Add list_filter to example ArticleAdmin
When using a list filter and then adding or editing an object the
language GET parameter goes missing causing the wrong translation to be
edited.
| Python | apache-2.0 | django-parler/django-parler,jrief/django-parler,edoburu/django-parler,HiddenData/django-parler,skirsdeda/django-parler,edoburu/django-parler,zhangguiyu/django-parler,jrief/django-parler,django-parler/django-parler,imposeren/django-parler,defivelo/django-parler,imposeren/django-parler,zhangguiyu/django-parler,defivelo/d... |
bda9c03e40315f4050477463b715fab038a96a1e | examples/pystray_icon.py | examples/pystray_icon.py | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
from multiprocessing import Process as Thread, Queue
else:
from threading import Thread
from queue import Queue
"""
Thi... | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
els... | Fix process spawn on Mac os, simplify logic | Fix process spawn on Mac os, simplify logic
| Python | bsd-3-clause | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview |
d879afb2ae12f4d217632fbe253f87c3db1673a7 | tests/test_gen_sql.py | tests/test_gen_sql.py | #!/usr/bin/env python
import sys
from io import StringIO
from pg_bawler import gen_sql
def test_simple_main(monkeypatch):
stdout = StringIO()
monkeypatch.setattr(sys, 'stdout', stdout)
class Args:
tablename = 'foo'
gen_sql.main(*[Args.tablename])
sql = stdout.getvalue()
assert gen_... | #!/usr/bin/env python
import sys
from io import StringIO
from pg_bawler import gen_sql
def test_simple_main(monkeypatch):
stdout = StringIO()
monkeypatch.setattr(sys, 'stdout', stdout)
class Args:
tablename = 'foo'
gen_sql.main(*[Args.tablename])
sql = stdout.getvalue()
assert gen_... | Add absolutely stupid test for only-drop gen_sql | Add absolutely stupid test for only-drop gen_sql
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler |
abefbbc99e7e62bed31db549519807feee7254f9 | tests/test_machine.py | tests/test_machine.py | import rml.machines
def test_machine_load_elements():
lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM')
assert len(lattice) == 173
| import rml.machines
def test_machine_load_elements():
lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM')
assert len(lattice) == 173
for element in lattice.get_elements():
assert element.get_pv_name('readback')
| Test to get different pv names for an element | Test to get different pv names for an element
| Python | apache-2.0 | razvanvasile/RML,willrogers/pml,willrogers/pml |
df4bd8201c7c3651fe045b69b1ef8772829b811d | kegweb/kegweb/forms.py | kegweb/kegweb/forms.py | from django import forms
from registration.models import RegistrationProfile
from registration.forms import RegistrationForm
from pykeg.core.models import UserProfile
class KegbotRegistrationForm(RegistrationForm):
gender = forms.CharField()
weight = forms.IntegerField()
def save(self, profile_callback=None):... | from django import forms
from registration.models import RegistrationProfile
from registration.forms import RegistrationForm
from pykeg.core.models import UserProfile
class KegbotRegistrationForm(RegistrationForm):
gender = forms.CharField()
weight = forms.IntegerField()
def save(self, profile_callback=None):... | Fix error on new user registration. | Fix error on new user registration.
| Python | mit | Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server |
aae16acb38649d2af6d80453b82b2e460e36efdd | form_utils_bootstrap3/tests/__init__.py | form_utils_bootstrap3/tests/__init__.py | import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default... | import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default... | Remove check for versions < 1.7 | Remove check for versions < 1.7
| Python | mit | federicobond/django-form-utils-bootstrap3 |
7e22cba69ddfcc523f4945c36470983b436faf3c | larvae/tests/test_bill.py | larvae/tests/test_bill.py | from ..bill import Bill
from validictory import ValidationError
def toy_bill():
b = Bill(bill_id="HB 2017",
session="2012A",
title="A bill for an act to raise the cookie budget by 200%",
type="bill")
b.add_source("http://uri.example.com/", note="foo")
b.validate()
... | from ..bill import Bill
from validictory import ValidationError
def toy_bill():
b = Bill(bill_id="HB 2017",
session="2012A",
title="A bill for an act to raise the cookie budget by 200%",
type="bill")
b.add_source("http://uri.example.com/", note="foo")
b.validate()
... | Add a related bill tester. | Add a related bill tester.
| Python | bsd-3-clause | AGarrow/larvae |
b8a90774ff48a94abd6671245ff3b3f0fbf95507 | transmute/__init__.py | transmute/__init__.py | import sys
minver = (3,3,0)
if sys.version_info[0:3] < minver:
raise ImportError("transmute requires Python version {} or newer.".format('.'.join(('{}'.format(v) for v in minver))))
##
# @brief The application version number.
version = (0, 0, '1a')
version_string = '.'.join(str(v) for v in version) | import sys
minver = (3,3,0)
if sys.version_info[0:3] < minver:
raise ImportError("transmute requires Python version {} or newer.".format('.'.join(('{}'.format(v) for v in minver))))
##
# @brief The application version number.
version = (0, 0, '1a')
##
# @brief The dot-separated version number in string format.
v... | Add doxygen comment for version_string | Add doxygen comment for version_string
Add a doxygen comment for version_string describing its nature.
| Python | mit | Rakankou/transmute |
334e794be7514c032e6db4c39761d67820c405ff | oscar/management/commands/oscar_update_product_ratings.py | oscar/management/commands/oscar_update_product_ratings.py | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
ProductReview = get_model('reviews', 'ProductReview')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instan... | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when chang... | Fix bug in management command for updating ratings | Fix bug in management command for updating ratings
| Python | bsd-3-clause | kapt/django-oscar,pasqualguerrero/django-oscar,jmt4/django-oscar,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,dongguangming/django-oscar,nickpack/django-oscar,WillisXChen/django-oscar,jmt4/django-oscar,manevant/django-oscar,jinnykoo/wuyisj,eddiep1101/django-oscar,pdonadeo/django-oscar,taedori81/django-oscar,mexeni... |
ad70a7ec6543d64ec185eb2d52ccfa291a1dfad6 | servicerating/views.py | servicerating/views.py | import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact... | import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact... | Remove FK's from CSV export for massive speed boost | Remove FK's from CSV export for massive speed boost
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control |
e9784ddaeea80311587ed7b255869d791008b29e | modder/gui/trayicon.py | modder/gui/trayicon.py | # coding: utf-8
import os.path
import platform
import wx
def create_menu_item(menu, label, func=None):
menu_item = wx.MenuItem(menu, -1, label)
if callable(func):
menu.Bind(wx.EVT_MENU, func, id=menu_item.GetId())
else:
menu_item.Enable(False)
menu.AppendItem(menu_item)
return me... | # coding: utf-8
import os.path
import platform
import wx
def create_menu_item(menu, label, func=None):
menu_item = wx.MenuItem(menu, -1, label)
if callable(func):
menu.Bind(wx.EVT_MENU, func, id=menu_item.GetId())
else:
menu_item.Enable(False)
menu.AppendItem(menu_item)
return me... | Add stub for mod manager GUI | Add stub for mod manager GUI
| Python | mit | JokerQyou/Modder2 |
6439182a1ed9efd6dd08aefce8cca44221bb9cef | sf/mmck/controllers.py | sf/mmck/controllers.py | from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
return self.module.controllers[self.name]
@property
def value(self):
return getattr(self.... | from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
c = self.module.controllers[self.name]
if hasattr(self.module, 'user_defined') and c.number >= 6:
... | Return specific user-defined control, not proxy | Return specific user-defined control, not proxy
| Python | mit | metrasynth/solar-flares |
9db378f028cf84d81165e7c50f62db794eb8fee2 | tests/query_test/test_chars.py | tests/query_test/test_chars.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'function... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'function... | Fix char test to only run on test/none. | Fix char test to only run on test/none.
Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
| Python | apache-2.0 | michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala |
c1429d70319b6f39412f1f34297f706b20d78b80 | members/urls.py | members/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
| Add url leading to student council archive | Add url leading to student council archive
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
d1aa094c9b0988c12100c8300aae4b390bb276f8 | zonetruck/__main__.py | zonetruck/__main__.py | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
def main(argv):
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = ZoneFilter(config['filter_rules']).filter
... | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
import sys
def main(argv=None):
argv = argv or sys.argv
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = Zo... | Make argv arguments optional, fixes pip installed script | Make argv arguments optional, fixes pip installed script
| Python | mit | pv2b/zonetruck |
6ac868c83dc3d6ad0733e5155c97c23414b06b06 | lupa/tests/__init__.py | lupa/tests/__init__.py | from __future__ import absolute_import
import unittest
import doctest
import os
import lupa
def suite():
test_dir = os.path.abspath(os.path.dirname(__file__))
tests = []
for filename in os.listdir(test_dir):
if filename.endswith('.py') and not filename.startswith('_'):
tests.append(... | from __future__ import absolute_import
import unittest
import doctest
import os
import os.path as os_path
import sys
import lupa
def suite():
test_dir = os.path.abspath(os.path.dirname(__file__))
tests = []
for filename in os.listdir(test_dir):
if filename.endswith('.py') and not filename.start... | Exclude platform specific doctests on appveyor. | Exclude platform specific doctests on appveyor.
| Python | mit | pombredanne/lupa,pombredanne/lupa |
8a1002dd7afd008ff85699f95ae11884b96f60ac | nanoservice/crypto.py | nanoservice/crypto.py | import hmac
import hashlib
from .error import AuthenticatorInvalidSignature
class Authenticator(object):
""" This object is used to authenticate messages """
def __init__(self, secret, digestmod=None):
assert secret
self.secret = secret.encode('utf-8')
self.digestmod = digestmod or h... | import hmac
import hashlib
from .error import AuthenticatorInvalidSignature
class Authenticator(object):
""" This object is used to authenticate messages """
def __init__(self, secret, digestmod=None):
assert secret
self.secret = secret.encode('utf-8')
self.digestmod = digestmod or h... | Put signature at the end to permit pub-sub to happen | Put signature at the end to permit pub-sub to happen
| Python | mit | walkr/nanoservice |
b9b03c1f736b38d122baafdd57bbd96657de17af | valuenetwork/api/types/apps.py | valuenetwork/api/types/apps.py | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
#import pdb; pdb.set_trace()
from valuenetwork.api.types.EconomicResource import EconomicResource... | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
""" Source of this hack:
https://stackoverflow.com/questions/37862725/django-1-9-how-to-import-in-init-py
... | Add a comment about the source of the hack | Add a comment about the source of the hack
| Python | agpl-3.0 | FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork |
5fc72fab36b3c29ccadc64aac3ffcb8d6bf56c48 | osf/models/subject.py | osf/models/subject.py | # -*- coding: utf-8 -*-
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
mod... | # -*- coding: utf-8 -*-
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
mod... | Add Subject.hierarchy to djangosf model | Add Subject.hierarchy to djangosf model
| Python | apache-2.0 | Johnetordoff/osf.io,mluo613/osf.io,acshi/osf.io,hmoco/osf.io,alexschiller/osf.io,adlius/osf.io,leb2dg/osf.io,adlius/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,baylee-d/osf.io,saradbowman/osf.io,aaxelb/osf.io,brianjgeiger/osf.... |
8235a217b50520093d549115fe09a8d4ff5e9191 | webmanager/default_settings.py | webmanager/default_settings.py | INSTALLED_APPS += (
'simplemenu',
'webmanager',
'bootstrapform',
'userenabootstrap',
'userena',
# 'social_auth',
'provider.oauth2',
)
TEMPLATE_CONTEXT_PROCESSORS += (
'django.contrib.auth.context_processors.auth',
)
AUTHENTICATION_BACKENDS += (
'userena.backends.UserenaAuthenticati... | INSTALLED_APPS += (
'provider',
'provider.oauth2',
'simplemenu',
'webmanager',
'bootstrapform',
'userenabootstrap',
'userena',
# 'social_auth',
)
TEMPLATE_CONTEXT_PROCESSORS += (
'django.contrib.auth.context_processors.auth',
)
AUTHENTICATION_BACKENDS += (
'userena.backends.Use... | Fix provider oauth2 warning by import provider before oauth2 as described in the manual | Fix provider oauth2 warning by import provider before oauth2 as described in the manual
| Python | bsd-3-clause | weijia/webmanager,weijia/webmanager,weijia/webmanager |
deef2f98deeeaf51bd9ddda4c5a200d082e16522 | arcutils/test/base.py | arcutils/test/base.py | import json
import django.test
from .user import UserMixin
class Client(django.test.Client):
def patch_json(self, path, data=None, **kwargs):
return self.patch(path, **self._json_kwargs(data, kwargs))
def post_json(self, path, data=None, **kwargs):
return self.post(path, **self._json_kwarg... | import json
import django.test
from .user import UserMixin
class Client(django.test.Client):
def patch_json(self, path, data=None, **kwargs):
return self.patch(path, **self._json_kwargs(data, kwargs))
def post_json(self, path, data=None, **kwargs):
return self.post(path, **self._json_kwarg... | Add patch_json method to our test Client | Add patch_json method to our test Client
| Python | mit | wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,PSU-OIT-ARC/django-arcutils |
fa4cf8c6c7a89a60c0067be53c6b0f29d3d3cde3 | biosensorsdb/admin.py | biosensorsdb/admin.py | import biosensorsdb.models
from django.contrib import admin
class ProjectAdmin(admin.ModelAdmin):
search_fields = ['team__name', 'year', 'title', 'abstract', 'inputs__name', 'outputs__name', 'tags__name']
admin.site.register(biosensorsdb.models.Team)
admin.site.register(biosensorsdb.models.SensorInput)
admin.site.r... | import biosensorsdb.models
from django.contrib import admin
class ProjectAdmin(admin.ModelAdmin):
search_fields = [
'team__name',
'year',
'title',
'abstract',
'track__name',
'inputs__name',
'outputs__name',
'application__name',
'results__result',
'tags__name',
]
admin.site.register(bi... | Make all project fields searchable. | Make all project fields searchable.
| Python | mit | jwintersinger/igembiosensors,jwintersinger/igembiosensors |
d6a205e7c97c3355fbf0678c5a439d14d834bb45 | kokki/cookbooks/munin/recipes/master.py | kokki/cookbooks/munin/recipes/master.py |
from kokki import *
Package("munin")
File("/etc/munin/munin.conf",
owner = "root",
group = "root",
mode = 0644,
content = Template("munin/munin.conf.j2"))
|
from kokki import *
Package("munin")
Directory(env.config.munin.dbdir,
owner = "munin",
group = "munin",
mode = 0755)
File("/etc/munin/munin.conf",
owner = "root",
group = "root",
mode = 0644,
content = Template("munin/munin.conf.j2"))
| Make sure the munin dir exists and is owned by the right user | Make sure the munin dir exists and is owned by the right user
| Python | bsd-3-clause | samuel/kokki |
a016b2a4158a3412d3db14d9180994b7c49041ab | preferences/views.py | preferences/views.py | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import Per... | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from bills.utils import get_all_subjects, get_all_locations
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.view... | Update view to grab subjects and locations | Update view to grab subjects and locations
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
d47da024519f3e6d61ac05c8379c617a3e334706 | configs/test/SysPaths.py | configs/test/SysPaths.py | from m5 import *
import os.path
import sys
# Edit the following list to include the possible paths to the binary
# and disk image directories. The first directory on the list that
# exists will be selected.
SYSTEMDIR_PATH = ['/n/poolfs/z/dist/m5/system']
SYSTEMDIR = None
for d in SYSTEMDIR_PATH:
if os.path.exis... | import os, sys
from os.path import isdir, join as joinpath
from os import environ as env
systemdir = None
bindir = None
diskdir = None
scriptdir = None
def load_defaults():
global systemdir, bindir, diskdir, scriptdir
if not systemdir:
try:
path = env['M5_PATH'].split(':')
exce... | Make the system paths more configurable | Make the system paths more configurable
configs/test/SysPaths.py:
Make the paths more configurable
| Python | bsd-3-clause | LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,LingxiaoJIA/gem5,andrewfu0325/gem5-aladdin,LingxiaoJIA/gem5,andrewfu0325/gem5-aladdin,LingxiaoJIA/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,haowu4682/gem5,andrewfu0325/gem5-aladdin,Ling... |
5864ee86593a71aac1cca17bc351dcbcfebf5337 | bottery/exceptions.py | bottery/exceptions.py | """Exception classes for Bottery"""
class ImproperlyConfigured(Exception):
"""Bottery is somehow improperly configured"""
pass
| """Exception classes for Bottery"""
class BotteryException(Exception):
"""A base class for all Bottery exceptions for easier catching."""
pass
class ImproperlyConfigured(BotteryException):
"""Bottery is somehow improperly configured"""
pass
| Add BotteryException base class from which ImproperlyConfigured derives. | Add BotteryException base class from which ImproperlyConfigured derives.
Fixes #40
| Python | mit | rougeth/bottery |
3ed19b2672738a59fc8676e0403ee90fe57273a1 | django/website/logframe/tests/test_admin.py | django/website/logframe/tests/test_admin.py | from mock import Mock
from ..admin import SubIndicatorAdmin
from ..models import SubIndicator
def test_sub_indicator_admin_rsult_returns_indicator_result():
sub_indicator = Mock(indicator=Mock(result='result'))
admin = SubIndicatorAdmin(SubIndicator, None)
assert sub_indicator.indicator.result == admin.... | from mock import Mock
from ..admin import RatingAdmin, SubIndicatorAdmin
from ..models import colors, Rating, SubIndicator
def test_sub_indicator_admin_rsult_returns_indicator_result():
sub_indicator = Mock(indicator=Mock(result='result'))
admin = SubIndicatorAdmin(SubIndicator, None)
assert sub_indicat... | Add test for RatingAdmin colored_name | Add test for RatingAdmin colored_name | Python | agpl-3.0 | aptivate/alfie,daniell/kashana,aptivate/kashana,aptivate/alfie,daniell/kashana,aptivate/kashana,aptivate/alfie,daniell/kashana,aptivate/alfie,aptivate/kashana,aptivate/kashana,daniell/kashana |
8f13e1f3705f7cbe6b5e797a78c70292aabaf5f8 | neuroshare/NeuralEntity.py | neuroshare/NeuralEntity.py | from Entity import *
class NeuralEntity(Entity):
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
return self._info['SourceEntityID']
... | from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(s... | Add basic doc to Neural entities | doc: Add basic doc to Neural entities
| Python | lgpl-2.1 | abhay447/python-neuroshare,G-Node/python-neuroshare,G-Node/python-neuroshare,abhay447/python-neuroshare |
ae7bda13946c2fff5760cdefc3c06cd932dcd070 | crits/config/handlers.py | crits/config/handlers.py | from django.conf import settings
from crits.config.config import CRITsConfig
def modify_configuration(forms, analyst):
"""
Modify the configuration with the submitted changes.
:param config_form: The form data.
:type config_form: dict
:param analyst: The user making the modifications.
:type a... | from django.conf import settings
from crits.config.config import CRITsConfig
def modify_configuration(forms, analyst):
"""
Modify the configuration with the submitted changes.
:param config_form: The form data.
:type config_form: dict
:param analyst: The user making the modifications.
:type a... | Remove code prototype code where the settings variables were being modified, this code works in single threaded servers but might not work on multithreaded servers. | Remove code prototype code where the settings variables were being modified, this code works in single threaded servers but might not work on multithreaded servers.
| Python | mit | cfossace/crits,jhuapl-marti/marti,jhuapl-marti/marti,Magicked/crits,jinverar/crits,cdorer/crits,davidhdz/crits,DukeOfHazard/crits,blaquee/crits,DukeOfHazard/crits,Magicked/crits,jinverar/crits,seanthegeek/crits,Lambdanaut/crits,davidhdz/crits,dreardon/crits,kaoscoach/crits,cdorer/crits,davidhdz/crits,ckane/crits,ckane/... |
daa686e350e6cbdc3bdb51a869e37f0a72df45dd | profile_collection/startup/50-scans.py | profile_collection/startup/50-scans.py | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | Add ssa2, zp to baseline | Add ssa2, zp to baseline
| Python | bsd-2-clause | NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd |
653cc71521636e7324b057a30506b3196b47461b | coding202-parsing-json/activity-parse-1.py | coding202-parsing-json/activity-parse-1.py | from urllib.request import Request, urlopen
import json
req = Request('http://jsonplaceholder.typicode.com/users')
response = urlopen(req)
response_string = response.read().decode("utf-8")
json_object = json.loads(response_string)
print(json_object)
#print(json.dumps(json_object, sort_keys=True, indent=4))
#print(js... | from urllib.request import Request, urlopen
import json
req = Request('http://jsonplaceholder.typicode.com/users', headers={'User-Agent': 'Mozilla/5.0'})
response = urlopen(req)
response_string = response.read().decode("utf-8")
json_object = json.loads(response_string)
print(json_object)
#print(json.dumps(json_objec... | Fix for Spider Bot Defense | Fix for Spider Bot Defense
Updated user-agent to defeat a known defense against Python urllib-based http Spider Bot requests. | Python | apache-2.0 | CiscoDevNet/coding-skills-sample-code,CiscoDevNet/coding-skills-sample-code,CiscoDevNet/coding-skills-sample-code,CiscoDevNet/coding-skills-sample-code |
198f070f15a234aee75a89a8fbc6ed1c712a9d6b | probfit/py23_compat.py | probfit/py23_compat.py | """
Python 2 / 3 compatibility helpers.
"""
import sys
py_ver = sys.version_info
PY2 = False
PY3 = False
if py_ver[0] == 2:
PY2 = True
else: # just in case PY4
PY3 = True
if PY2:
range = xrange
else:
range = range
| """
Python 2 / 3 compatibility helpers.
"""
import sys
py_ver = sys.version_info
PY2 = False
PY3 = False
if py_ver[0] == 2:
PY2 = True
else: # just in case PY4
PY3 = True
if PY2:
range = xrange # pylint: disable=undefined-variable
else:
range = range
| Disable pylint warning for xrange. | Disable pylint warning for xrange.
Pylint complains that xrange is an undefined variable when its run under
Python 3. This is true, which is why the offending line is wrapped with
an 'if PY3' clause.
| Python | mit | iminuit/probfit,iminuit/probfit |
219589c8498e2d0bd156bd9863d4ef23f4963111 | code/dataplot.py | code/dataplot.py | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline... | Read binary data file location from commandline | Read binary data file location from commandline
| Python | mit | TAdeJong/plasma-analysis,TAdeJong/plasma-analysis |
c1dbb7ef6b9176b4ec09da5446a082fd88abc37a | numba_wrapper.py | numba_wrapper.py | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
## Allow the code to function without numba, but discourage it
try:
from numba import njit, jit, vectorize, int64, float64,... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
## Allow the code to function without numba, but discourage it
try:
from numba import njit, jit, vectorize, int64, float64,... | Handle removal of IS_PY3 from numba | Handle removal of IS_PY3 from numba
Closes #133 | Python | mit | moble/quaternion,moble/quaternion |
6f8b370222b6f842b3ea89bb854b4883d145dfe0 | nuts/__init__.py | nuts/__init__.py | # The main message class that the AuthChannel operate on
class AuthenticatedMessage(object):
def __init__(self, sender, msg, session=None):
self.sender = sender
self.msg = msg
self.session = session
def __str__(self):
return self.msg
class NutsError(Exception):
""" General... | # The main message class that the AuthChannel operate on
class AuthenticatedMessage(object):
def __init__(self, sender, msg, session=None):
self.sender = sender
self.msg = msg
self.session = session
def __str__(self):
return self.msg
def __int__(self):
return int(s... | Allow int(msg) and float(msg) calls | Allow int(msg) and float(msg) calls
| Python | mit | thusoy/nuts-auth,thusoy/nuts-auth |
cb161eb1cc66c520a81026798112fb13d0cd0e50 | community/__init__.py | community/__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This package implements community detection.
Package name is community but refer to python-louvain on pypi
"""
from .community_louvain import (
partition_at_level,
modularity,
best_partition,
generate_dendrogram,
induced_graph,
load_binary,
)
__a... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This package implements community detection.
Package name is community but refer to python-louvain on pypi
"""
from .community_louvain import (
partition_at_level,
modularity,
best_partition,
generate_dendrogram,
induced_graph,
load_binary,
)
__ve... | Add version information to package | Add version information to package
| Python | bsd-3-clause | taynaud/python-louvain |
7d54decec5f005ee7bcd8b16d75225a60f7cbdfe | post-to-slack.py | post-to-slack.py | """
Author: Ashish Gaikwad <ash.gkwd@gmail.com>
Copyright (c) 2015 Ashish Gaikwad
Description: This script will post a message on your slack channel
Please configure your `/etc/brainy-beats.cfg` file first.
Example brainy-beats.cfg
[slack]
url=https://hooks.slack.com/services/XxXxXxXxXx
channel=botwa
icon_emoji=ghos... | """
Author: Ashish Gaikwad <ash.gkwd@gmail.com>
Copyright (c) 2015 Ashish Gaikwad
Description: This script will post a message on your slack channel
Please configure your `/etc/brainy-beats.cfg` file first.
Example brainy-beats.cfg
[slack]
url=https://hooks.slack.com/services/XxXxXxXxXx
channel=botwa
icon_emoji=ghos... | FIX - path of .cfg file corrected | FIX - path of .cfg file corrected
| Python | mit | ashgkwd/brainy-beats,ashgkwd/brainy-beats |
b03dff0d6964d886f122936d097c3d4acc0582db | proper_parens.py | proper_parens.py | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
def safe_input(prompt):
"""Return user input after catching KeyboardInterrupt and EOFError"""
try:
reply = raw_input(prompt)
except (EOFError, KeyboardInterrupt):
quit()
else:
re... | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
def safe_input(prompt):
"""Return user input after catching KeyboardInterrupt and EOFError"""
try:
reply = raw_input(prompt)
except (EOFError, KeyboardInterrupt):
quit()
else:
re... | Add function for broken and groundwork for other objectives | Add function for broken and groundwork for other objectives
| Python | mit | constanthatz/data-structures |
8cb685ac92cd2fcc628ad96feaed67fc1af48ed6 | falafel/mappers/dmesg.py | falafel/mappers/dmesg.py | from .. import LogFileOutput, mapper
class DmesgLineList(LogFileOutput):
def has_startswith(self, prefix):
"""
Returns a boolean array which is `True` where there is one line in
dmesg starts with `prefix`, otherwise `False`.
"""
return any(line.startswith(prefix) for line i... | from .. import LogFileOutput, mapper
@mapper('dmesg')
class DmesgLineList(LogFileOutput):
def has_startswith(self, prefix):
"""
Returns a boolean array which is `True` where there is one line in
dmesg starts with `prefix`, otherwise `False`.
"""
return any(line.startswith(p... | Add mapper decorator to DmesgLineList mapper | Add mapper decorator to DmesgLineList mapper
* Add @mapper decorator to the DmesgLineList shared mapper to allow use
directly by plugins.
| Python | apache-2.0 | RedHatInsights/insights-core,RedHatInsights/insights-core |
79b145f9c73deb9116b4d51e29952b63e4d63cc8 | install/setup_pi_box.py | install/setup_pi_box.py | import os
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f... | import os
import sys
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Dropbox token file (dropbox.txt) not found.')
print('Go here to authorize Pi-Box and obtain the token file: blah, blah, blah')
print('Save the file in: /opt/Pi-Box')
print('Run the installation script again: ./install.sh')
sys.exit()
... | Check for token file before installing | Check for token file before installing
| Python | mit | projectweekend/Pi-Box,projectweekend/Pi-Box |
0a5e272a1828be1eb93975e3b673ba67ca800635 | playserver/trackchecker.py | playserver/trackchecker.py | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self._generator = self._checkSongGenerator()
self.timer = None
def _checkSongGenerator(self):
while True:
currentSong = ""
curre... | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | Remove use of generator completely | Remove use of generator completely
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver |
e4297691f20ec4185ed4491ab41553df14a05a91 | pycc/pycompat.py | pycc/pycompat.py | """Compatibility helpers for Py2 and Py3."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import sys
class VERSION(object):
"""Stand in for sys.version_info.
The values from sys only have named parameter... | """Compatibility helpers for Py2 and Py3."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import sys
class VERSION(object):
"""Stand in for sys.version_info.
The values from sys only have named parameter... | Add a long type backfill for PY3 compat | Add a long type backfill for PY3 compat
PY3 combined the long and int types which makes some compiler
operations difficult. Adding a backfill to help with PY2/PY3
compat.
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
| Python | apache-2.0 | kevinconway/pycc,kevinconway/pycc |
287719c22d28d404c7944b2abecc8644bf348f49 | tests/test_subclasshook.py | tests/test_subclasshook.py | """
Test that if foreign code provides a class that conforms to
BidirectionalMapping's interface, it is automatically a subclass.
"""
from bidict import BidirectionalMapping
class DumbBidirectionalMapping(dict):
def __inverted__(self):
for (key, val) in self.items():
yield (val, key)
@pro... | """
Test that if foreign code provides a class that conforms to
BidirectionalMapping's interface, it is automatically a subclass.
"""
from bidict import BidirectionalMapping
class DumbBidirectionalMapping(dict):
def __inverted__(self):
for (key, val) in self.items():
yield (val, key)
@pro... | Add test for oldstyle class handling | Add test for oldstyle class handling
| Python | mpl-2.0 | jab/bidict,jab/bidict |
135b7baaf8f4378488af2b1e0fb4abf63522f0ab | test/tests/python-imports/container.py | test/tests/python-imports/container.py | import zlib
import bz2
assert(zlib.decompress(zlib.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
assert(bz2.decompress(bz2.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
| import curses
import zlib
assert(zlib.decompress(zlib.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
import bz2
assert(bz2.decompress(bz2.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
| Reorganize python-imports to include "curses" | Reorganize python-imports to include "curses"
| Python | apache-2.0 | thresheek/official-images,davidl-zend/official-images,nodejs-docker-bot/official-images,infosiftr/stackbrew,infosiftr/stackbrew,pesho/docker-official-images,dinogun/official-images,mattrobenolt/official-images,thresheek/official-images,jperrin/official-images,dinogun/official-images,thresheek/official-images,neo-techno... |
edc830bcd8fb594406e314b5c93062b0ec347bba | cref/structure/__init__.py | cref/structure/__init__.py | from peptide import PeptideBuilder
import Bio.PDB
def write_pdb(aa_sequence, fragment_angles, gap_length, filepath):
"""
Generate pdb file with results
:param aa_sequence: Amino acid sequence
:param fragment_angles: Backbone torsion angles
:param gap_length: Length of the gap at the sequence star... | from peptide import PeptideBuilder
import Bio.PDB
def write_pdb(aa_sequence, fragment_angles, gap_length, filepath):
"""
Generate pdb file with results
:param aa_sequence: Amino acid sequence
:param fragment_angles: Backbone torsion angles
:param gap_length: Length of the gap at the sequence star... | Fix wrong pdb parser invocation | Fix wrong pdb parser invocation
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 |
f498eba42dd3d35e9ff0b5240f44fe8df25332ed | law/contrib/cms/tasks.py | law/contrib/cms/tasks.py | # -*- coding: utf-8 -*-
"""
CMS-related tasks.
https://home.cern/about/experiments/cms
"""
__all__ = ["BundleCMSSW"]
import os
import luigi
from law import Task, LocalFileTarget, NO_STR
from law.decorator import log
from law.util import rel_path, interruptable_popen
class BundleCMSSW(Task):
task_namespac... | # -*- coding: utf-8 -*-
"""
CMS-related tasks.
https://home.cern/about/experiments/cms
"""
__all__ = ["BundleCMSSW"]
import os
import luigi
from law import Task, LocalFileTarget, NO_STR
from law.decorator import log
from law.util import rel_path, interruptable_popen
class BundleCMSSW(Task):
task_namespac... | Rename path parameter in contrib.cms.BundleCMSSW. | Rename path parameter in contrib.cms.BundleCMSSW.
| Python | bsd-3-clause | riga/law,riga/law |
ff02f0e8a7b62d5afdc88730129a5e0811fb5a82 | monitor/monitor_test.py | monitor/monitor_test.py | #!/usr/bin/python
import unittest
import monitor
class TestMonitor(unittest.TestCase):
def test_attr(self):
mon = monitor.Monitor()
assert mon.pvprefix == "MON-CONTROL:"
assert mon.monitorname == "PI1"
def test_testimage(self):
mon = monitor.Monitor()
image = mon.testimage()
assert len(image) != 0
# ... | #!/usr/bin/python
import unittest
from mock import patch, MagicMock, PropertyMock
from monitor import Monitor
class MonitorUpdateTest(unittest.TestCase):
def setUp(self):
with patch('monitor.pv.PV'):
mock_plotter = MagicMock()
self.monitor = Monitor("MYNAME", mock_plotter)
... | Rewrite monitortests. Add tests for update_image | Rewrite monitortests. Add tests for update_image
| Python | apache-2.0 | nickbattam/picamon,nickbattam/picamon,nickbattam/picamon,nickbattam/picamon |
14f5842a6ae598253f30a711983985ce60c17e04 | localore/search/views.py | localore/search/views.py | from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.models import Query
def search(request):
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# S... | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.shortcuts import render
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.models import Query
def search(request):
json = request.GET.get('json', False)
search_query ... | Add support for returning search results as JSON. | Add support for returning search results as JSON.
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore |
6741f6746fe24c91b791ed35048e750d9c52d5ce | scripts/utils.py | scripts/utils.py | # -*- coding: utf-8 -*-
import os
import logging
import datetime
from website import settings
def format_now():
return datetime.datetime.now().isoformat()
def add_file_logger(logger, script_name, suffix=None):
_, name = os.path.split(script_name)
if suffix is not None:
name = '{0}-{1}'.format(... | # -*- coding: utf-8 -*-
import os
import logging
import datetime
from website import settings
def format_now():
return datetime.datetime.now().isoformat()
def add_file_logger(logger, script_name, suffix=None):
_, name = os.path.split(script_name)
name = name.rstrip('c')
if suffix is not None:
... | Make script log file names more consistent | Make script log file names more consistent
...by stripping c's of filenames, so that we get
script_name.py-timestamp rather than script_name.pyc-timestamp
| Python | apache-2.0 | caneruguz/osf.io,kch8qx/osf.io,cwisecarver/osf.io,rdhyee/osf.io,crcresearch/osf.io,abought/osf.io,TomBaxter/osf.io,kwierman/osf.io,mluke93/osf.io,alexschiller/osf.io,laurenrevere/osf.io,DanielSBrown/osf.io,mluo613/osf.io,alexschiller/osf.io,crcresearch/osf.io,Nesiehr/osf.io,cslzchen/osf.io,leb2dg/osf.io,caseyrollins/os... |
462acba741c929ae79d5c2e6f6fc98307f556ec9 | shopping_list.py | shopping_list.py | shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
| shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
def show_list():
prin... | Implement method to show contents of the list. | Implement method to show contents of the list.
| Python | mit | adityatrivedi/shopping-list |
2f77a49d4a8393b1de14aac29b41204e8006876e | project/members/rest.py | project/members/rest.py | from rest_framework import viewsets, serializers
from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication
class MemberTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MemberType
class MemberTypeViewSet(viewsets.ModelViewSet):
serializer_class =... | from rest_framework import viewsets, serializers
from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication
class MemberTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MemberType
class MemberTypeViewSet(viewsets.ModelViewSet):
serializer_class =... | Add credit property to member REST API response | Add credit property to member REST API response
| Python | mit | jautero/asylum,HelsinkiHacklab/asylum,rambo/asylum,ojousima/asylum,rambo/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,ojousima/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,jautero/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,ojousima/asylum,ojousima/asylum,rambo/as... |
3f5bd92a11ed69592e21888838088f8baa0d6575 | makefiles_plain_python.py | makefiles_plain_python.py | #!/usr/bin/python3
def make_a_file(i):
f = "out_python/{:05d}".format(i)
try:
with open(f, "w") as fp:
fp.write("hello")
# print("wrote", f)
except:
print("failed on", f)
def make_a_lot_of_files(how_many):
for i in range(how_many):
make_a_file(i)
return... | #!/usr/bin/python3
import asyncio
@asyncio.coroutine
def make_a_file(i):
f = "out_python/{:05d}".format(i)
try:
with open(f, "w") as fp:
fp.write("hello")
# print("wrote", f)
except:
print("failed on", f)
def make_a_lot_of_files(how_many):
loop = asyncio.get_event... | Use asyncio in plain python example. | Use asyncio in plain python example.
| Python | mit | reedwade/python-golang-linking,reedwade/python-golang-linking |
fc9970e97575af85384fedc58cdc1ff9800628cc | neo/test/rawiotest/test_alphaomegarawio.py | neo/test/rawiotest/test_alphaomegarawio.py | """
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded I... | """
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded I... | Use correct test data path | Use correct test data path
| Python | bsd-3-clause | samuelgarcia/python-neo,apdavison/python-neo,JuliaSprenger/python-neo,INM-6/python-neo,NeuralEnsemble/python-neo |
a9330038b2dc56e34ccc5ecdfb297adfc50ec005 | nlpipe/modules/corefnl.py | nlpipe/modules/corefnl.py | """
Wrapper around antske/coref_draft.
Input should be NAF files parsed by alpino (e.g. alpinonerc)
"""
from KafNafParserPy import KafNafParser
from multisieve_coreference import process_coreference
from io import BytesIO
import logging
from nlpipe.module import Module
log = logging.getLogger(__name__)
class CorefN... | """
Wrapper around antske/coref_draft.
Input should be NAF files parsed by alpino (e.g. alpinonerc)
"""
import logging
from nlpipe.module import Module
import subprocess
import os
log = logging.getLogger(__name__)
class CorefNL(Module):
name = "corefnl"
def check_status(self):
if 'COREF_HOME' not i... | Change coref to external call | Change coref to external call
| Python | mit | vanatteveldt/nlpipe,vanatteveldt/nlpipe,vanatteveldt/nlpipe |
d0a907706b8f21e63818375a669c6a8fbe398a5f | project_closing/__openerp__.py | project_closing/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Camtpcaomp
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Camtpcaomp
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | Add OCA as author of OCA addons | Add OCA as author of OCA addons
In order to get visibility on https://www.odoo.com/apps the OCA board has
decided to add the OCA as author of all the addons maintained as part of the
association.
| Python | agpl-3.0 | Endika/project,acsone/project-service,yelizariev/project-service,dreispt/project,OCA/project-service,Antiun/project,dreispt/project-service,ddico/project,eezee-it/project-service,incaser/project,sergiocorato/project-service,raycarnes/project,Antiun/project-service,NeovaHealth/project-service,xpansa/project-service,acso... |
495ea3347eec9d1a902779de8dd07ba91aa48f60 | server/validator.py | server/validator.py | from girder.api import access
from girder.api.rest import Resource
from girder.api.describe import Description
class Validator(Resource):
def __init__(self, celeryApp):
self.resourceName = 'romanesco_validator'
self.route('GET', (), self.find)
self.celeryApp = celeryApp
@access.public... | from girder.api import access
from girder.api.rest import Resource
from girder.api.describe import Description
class Validator(Resource):
def __init__(self, celeryApp):
super(Validator, self).__init__()
self.resourceName = 'romanesco_validator'
self.route('GET', (), self.find)
self... | Call Resource constructor from Validator, fixing a Girder warning | Call Resource constructor from Validator, fixing a Girder warning
| Python | apache-2.0 | Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.