commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
851579b14a34b8acc1977b2f4d2c991d8e5f5f2c | ledlight.py | ledlight.py | #!/usr/bin/env python
import RPi.GPIO as GPIO
from time import sleep
pin_switch = 12
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin_switch, GPIO.IN)
period = 0.1
duration = 4
samples = int(duration / float(period))
freq = 1.0 / period
series = []
print "inputting", samples, "samples,", "at", freq, "Hz"
for i in range(samp... | #!/usr/bin/env python
import RPi.GPIO as GPIO
from time import sleep
pin_switch = 12
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin_switch, GPIO.IN)
period = 0.25
duration = 30
samples = int(duration / float(period))
freq = 1.0 / period
series = []
print "inputting", samples, "samples,", "at", freq, "Hz"
for i in range(sa... | Print out 0/1 values as we sense them real-time. | Print out 0/1 values as we sense them real-time.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie | ---
+++
@@ -7,8 +7,8 @@
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin_switch, GPIO.IN)
-period = 0.1
-duration = 4
+period = 0.25
+duration = 30
samples = int(duration / float(period))
freq = 1.0 / period
@@ -17,11 +17,9 @@
print "inputting", samples, "samples,", "at", freq, "Hz"
for i in range(samples):
- ser... |
d2e52377f90c81365bd0ff62c8bea95207b44328 | indra/sources/sofia/api.py | indra/sources/sofia/api.py | import openpyxl
from .processor import SofiaProcessor
def process_table(fname):
"""Return processor by processing a given sheet of a spreadsheet file.
Parameters
----------
fname : str
The name of the Excel file (typically .xlsx extension) to process
Returns
-------
sp : indra.sou... | import openpyxl
from .processor import SofiaProcessor
def process_table(fname):
"""Return processor by processing a given sheet of a spreadsheet file.
Parameters
----------
fname : str
The name of the Excel file (typically .xlsx extension) to process
Returns
-------
sp : indra.so... | Handle Causal and Relations worksheets | Handle Causal and Relations worksheets
| Python | bsd-2-clause | pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra,johnbachman/belpy,bgyori/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra | ---
+++
@@ -1,5 +1,6 @@
import openpyxl
from .processor import SofiaProcessor
+
def process_table(fname):
"""Return processor by processing a given sheet of a spreadsheet file.
@@ -16,7 +17,10 @@
Statements as its statements attribute
"""
book = openpyxl.load_workbook(fname, read_only=Tru... |
e2cad9831c3d3658e096c05ba45a9285744549dd | tnm/urls.py | tnm/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.contrib.gis import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()
urlpatterns = patterns('')
urlpatterns += patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
(r'^n... | from django.conf.urls.defaults import patterns, include, url
from django.contrib.gis import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()
urlpatterns = patterns('')
urlpatterns += patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
(r'^$... | Move code to / from /nearby. Move to tnm.com. | Move code to / from /nearby. Move to tnm.com.
| Python | mit | chosak/TransitNearMe,MobilityLab/TransitNearMe,chosak/TransitNearMe,MobilityLab/TransitNearMe,chosak/TransitNearMe | ---
+++
@@ -11,6 +11,6 @@
)
urlpatterns += patterns('',
- (r'^nearby/$', direct_to_template, {'template': 'leaflet.html'}),
+ (r'^$', direct_to_template, {'template': 'leaflet.html'}),
(r'^api/', include('api.urls')),
) |
a555737e2d594a67078a15be9d5eb3c8524d0698 | app/models.py | app/models.py | from . import db
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
age = db.Column(db.Date())
def __repr__(self):
return '<User {} {}>'.format(self.id,... | from . import db
from werkzeug.security import generate_password_hash, check_password_hash
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
password_hash = db.Column... | Add password hash to Monkey model | Add password hash to Monkey model
| Python | mit | timzdevz/fm-flask-app | ---
+++
@@ -1,4 +1,5 @@
from . import db
+from werkzeug.security import generate_password_hash, check_password_hash
class Monkey(db.Model):
__tablename__ = 'monkeys'
@@ -6,7 +7,19 @@
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), u... |
f333f29d4170527c985bc695cd7b8331041769d5 | eva/layers/out_channels.py | eva/layers/out_channels.py | from keras.layers import Convolution2D, Reshape, Lambda, Activation
from eva.layers.masked_convolution2d import MaskedConvolution2D
class OutChannels(object):
def __init__(self, height, width, channels, masked=False, palette=256):
self.height = height
self.width = width
self.channels = cha... | from keras.layers import Convolution2D, Reshape, Lambda, Activation
from eva.layers.masked_convolution2d import MaskedConvolution2D
class OutChannels(object):
def __init__(self, height, width, channels, masked=False, palette=256):
self.height = height
self.width = width
self.channels = cha... | Make mono channel output activation more readable | Make mono channel output activation more readable
| Python | apache-2.0 | israelg99/eva | ---
+++
@@ -12,7 +12,8 @@
def __call__(self, model):
if self.channels == 1:
- outs = Convolution2D(1, 1, 1, activation='sigmoid', border_mode='valid')(model)
+ outs = Convolution2D(1, 1, 1, border_mode='valid')(model)
+ outs = Activation('sigmoid')(outs)
else:... |
a21d484cc1131b56d793e75fbb6ab1531205dae6 | joueur/base_game_object.py | joueur/base_game_object.py | from joueur.delta_mergeable import DeltaMergeable
# the base class that every game object within a game inherit from for Python
# manipulation that would be redundant via Creer
class BaseGameObject(DeltaMergeable):
def __init__(self):
DeltaMergeable.__init__(self)
def __str__(self):
return "{... | from joueur.delta_mergeable import DeltaMergeable
# the base class that every game object within a game inherit from for Python
# manipulation that would be redundant via Creer
class BaseGameObject(DeltaMergeable):
def __init__(self):
DeltaMergeable.__init__(self)
def __str__(self):
return "{... | Update BaseGameObject to be hashable | Update BaseGameObject to be hashable
| Python | mit | JacobFischer/Joueur.py,siggame/Joueur.py,siggame/Joueur.py,JacobFischer/Joueur.py | ---
+++
@@ -12,3 +12,8 @@
def __repr__(self):
return str(self)
+
+ def __hash__(self):
+ # id will always be unique server side anyways,
+ # so it should be safe to hash on
+ return hash(self.id) |
aa9cb1bc1a04de4e4a4a787881123e2a60aaeb4e | docs/apps.py | docs/apps.py | import certifi
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from elasticsearch_dsl.connections import connections
class DocsConfig(AppConfig):
name = 'docs'
verbose_name = _('Documentation')
def ready(self):
super(DocsC... | import certifi
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from elasticsearch_dsl.connections import connections
class DocsConfig(AppConfig):
name = 'docs'
verbose_name = _('Documentation')
def ready(self):
super(DocsC... | Increase the ES timeout to 1 minute. | Increase the ES timeout to 1 minute.
| Python | bsd-3-clause | rmoorman/djangoproject.com,hassanabidpk/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,hassanabidpk/djangoproject.com,gnarf/djangoproject.com,vxvinh1511/djangoproject.com,xavierdutreilh/djangoproject.com,hassanabidpk/djangoproject.com,django/d... | ---
+++
@@ -17,5 +17,6 @@
'hosts': settings.ES_HOST,
'verify_certs': True,
'ca_certs': certifi.where(),
+ 'timeout': 60.0,
},
) |
2a2b11f78ee64cd54cdfb8d105606215c42dcaa5 | bot.py | bot.py |
import tweepy
from secrets import *
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
| Update 0.0.1 - Added imports - Added standards for accessing Twitter API | Update 0.0.1
- Added imports
- Added standards for accessing Twitter API
| Python | mit | FXelix/space_facts_bot | ---
+++
@@ -1 +1,8 @@
+import tweepy
+from secrets import *
+
+# standard for accessing Twitter API
+auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
+auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
+api = tweepy.API(auth) | |
9efa42ae172e240c01be9caed5bb942bc0459494 | tools/perf/benchmarks/session_restore.py | tools/perf/benchmarks/session_restore.py | # Copyright 2013 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.
from measurements import session_restore
from telemetry import test
# crbug.com/325479: Disabling this test for now since it never ran before.
@test.Disabl... | # Copyright 2013 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.
from measurements import session_restore
from telemetry import test
@test.Disabled('android') # crbug.com/325479
class SessionRestoreColdTypical25(test.Te... | Enable session restore benchmark on linux. | [Telemetry] Enable session restore benchmark on linux.
I believe it was disabled because the clear_system_cache binary wasn't checked
into cloud storage yet. It is now.
BUG=325479
Review URL: https://codereview.chromium.org/311053006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@275163 0039d316-1c4b-4281-b95... | Python | bsd-3-clause | dushu1203/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crossw... | ---
+++
@@ -6,8 +6,7 @@
from telemetry import test
-# crbug.com/325479: Disabling this test for now since it never ran before.
-@test.Disabled('android', 'linux')
+@test.Disabled('android') # crbug.com/325479
class SessionRestoreColdTypical25(test.Test):
tag = 'cold'
test = session_restore.SessionRestore |
763d9f8ef45aff357e318d73cfd10512228d85f3 | src/zeit/content/article/edit/browser/tests/test_preview.py | src/zeit/content/article/edit/browser/tests/test_preview.py | # Copyright (c) 2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.content.article.testing
class Preview(zeit.content.article.testing.SeleniumTestCase):
def test_selected_tab_is_stored_across_reload(self):
self.open('/repository/online/2007/01/Somalia')
s = self.selenium
select... | # Copyright (c) 2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.content.article.testing
class Preview(zeit.content.article.testing.SeleniumTestCase):
def test_selected_tab_is_stored_across_reload(self):
self.open('/repository/online/2007/01/Somalia')
s = self.selenium
select... | Update test to work with current jquery-ui | Update test to work with current jquery-ui
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article | ---
+++
@@ -9,12 +9,12 @@
def test_selected_tab_is_stored_across_reload(self):
self.open('/repository/online/2007/01/Somalia')
s = self.selenium
- selected_tab = 'css=#preview-tabs .ui-tabs-selected'
+ selected_tab = 'css=#preview-tabs .ui-tabs-active'
s.waitForElementPre... |
23ceddaff1752797fe775df950f6e62769b285a6 | foyer/tests/test_plugin.py | foyer/tests/test_plugin.py | import pytest
import foyer
def test_basic_import():
assert 'forcefields' in dir(foyer)
@pytest.mark.parametrize('ff_name', ['OPLSAA', 'TRAPPE_UA'])
def test_forcefields_exist(ff_name):
ff_name in dir(foyer.forcefields)
def test_load_forcefield():
OPLSAA = foyer.forcefields.get_forcefield(name='oplsaa'... | import pytest
import foyer
def test_basic_import():
assert 'forcefields' in dir(foyer)
@pytest.mark.parametrize('ff_loader', ['load_OPLSAA', 'load_TRAPPE_UA'])
def test_forcefields_exist(ff_loader):
assert ff_loader in dir(foyer.forcefields)
def test_load_forcefield():
OPLSAA = foyer.forcefields.get_f... | Update test to properly assert loaders | Update test to properly assert loaders
| Python | mit | iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer | ---
+++
@@ -6,9 +6,9 @@
assert 'forcefields' in dir(foyer)
-@pytest.mark.parametrize('ff_name', ['OPLSAA', 'TRAPPE_UA'])
-def test_forcefields_exist(ff_name):
- ff_name in dir(foyer.forcefields)
+@pytest.mark.parametrize('ff_loader', ['load_OPLSAA', 'load_TRAPPE_UA'])
+def test_forcefields_exist(ff_loader... |
183aacf12405eec38ba8b2193f8f89904d415c4a | yagocd/resources/base.py | yagocd/resources/base.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 Grigory Chernyshev
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation file... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 Grigory Chernyshev
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation file... | Return internal data for string representation. | Return internal data for string representation.
| Python | isc | grundic/yagocd,grundic/yagocd | ---
+++
@@ -40,6 +40,12 @@
def data(self):
return self._data
+ def __str__(self):
+ return self.data.__str__()
+
+ def __repr__(self):
+ return self.data.__repr__()
+
if __name__ == '__main__':
pass |
77fd12a850fbca0b3308e964e457f234d12d7c11 | src/wad.blog/wad/blog/utils.py | src/wad.blog/wad/blog/utils.py | from zope.component import getUtility, getMultiAdapter, ComponentLookupError
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
context = context.... | from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
def find_assignment_con... | Fix portlet assignment context utility | Fix portlet assignment context utility
| Python | mit | potzenheimer/buildout.wad,potzenheimer/buildout.wad | ---
+++
@@ -1,25 +1,30 @@
-from zope.component import getUtility, getMultiAdapter, ComponentLookupError
+from Acquisition import aq_inner
+from Acquisition import aq_parent
+from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortlet... |
eea0a6bc56d69377519e5441074f32f5eb9fb01e | examples/storage/ext_flash_fatfs/example_test.py | examples/storage/ext_flash_fatfs/example_test.py | from __future__ import print_function
import os
import sys
try:
import IDF
except ImportError:
test_fw_path = os.getenv('TEST_FW_PATH')
if test_fw_path and test_fw_path not in sys.path:
sys.path.insert(0, test_fw_path)
import IDF
@IDF.idf_example_test(env_tag='Example_ExtFlash')
def test_exam... | from __future__ import print_function
import os
import sys
try:
import IDF
except ImportError:
test_fw_path = os.getenv('TEST_FW_PATH')
if test_fw_path and test_fw_path not in sys.path:
sys.path.insert(0, test_fw_path)
import IDF
from IDF.IDFDUT import ESP32DUT
@IDF.idf_example_test(env_tag=... | Add ESP32 DUT class to ext_flash_fatfs example test | examples: Add ESP32 DUT class to ext_flash_fatfs example test
| Python | apache-2.0 | espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf | ---
+++
@@ -10,10 +10,12 @@
sys.path.insert(0, test_fw_path)
import IDF
+from IDF.IDFDUT import ESP32DUT
+
@IDF.idf_example_test(env_tag='Example_ExtFlash')
def test_examples_storage_ext_flash_fatfs(env, extra_data):
- dut = env.get_dut('ext_flash_fatfs', 'examples/storage/ext_flash_fatfs')
+ ... |
5a310285c6e528555136a95221b628827d04cb81 | l10n_br_base/__init__.py | l10n_br_base/__init__.py | # Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import models
from . import tests
| # Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import models
from . import tests
from odoo.addons import account
from odoo import api, SUPERUSER_ID
# Install Simple Chart of Account Template for Brazilian Companies
_auto_install_l10n_original = ac... | Define l10n_br_simple as default COA for brazilian companies | Define l10n_br_simple as default COA for brazilian companies
| Python | agpl-3.0 | akretion/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil | ---
+++
@@ -3,3 +3,24 @@
from . import models
from . import tests
+
+from odoo.addons import account
+from odoo import api, SUPERUSER_ID
+
+# Install Simple Chart of Account Template for Brazilian Companies
+_auto_install_l10n_original = account._auto_install_l10n
+
+
+def _auto_install_l10n_br_simple(cr, registr... |
08797de13a88bc742d905f2067df533a1a319c83 | yawf/revision/models.py | yawf/revision/models.py | from django.db import models
from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
versions = generic.GenericR... | from django.db import models
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
def save(self, *args, **kwargs):
self.revision += 1
super(R... | Remove generic relation to reversion.Version from RevisionModelMixin | Remove generic relation to reversion.Version from RevisionModelMixin
| Python | mit | freevoid/yawf | ---
+++
@@ -1,5 +1,4 @@
from django.db import models
-from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
@@ -12,8 +11,6 @@
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
- versions = generic.GenericRelation('reversion.Vers... |
adb33e7240029bf842213ab8157ae872fe2298fd | subiquity/models/installpath.py | subiquity/models/installpath.py | # Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | # Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Fix dynamic translation of install_path labels. | Fix dynamic translation of install_path labels.
| Python | agpl-3.0 | CanonicalLtd/subiquity,CanonicalLtd/subiquity | ---
+++
@@ -26,14 +26,16 @@
('UI Text seen by user', <signal name>, <callback function string>)
"""
- # TODO: Re-enable once available
- install_paths = [
- (_('Install Ubuntu'), 'installpath:install-ubuntu'),
- # ('Install MAAS Region Server', 'installpath:maas-region-ser... |
cd09a040270eb3cf1b1966e76382e9e92f4323a8 | soco/__init__.py | soco/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.6'
__website__ = 'https://github.com/SoCo/SoCo... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.6'
__website__ = 'https://github.com/SoCo/SoCo... | Fix for logger configuration errors | Fix for logger configuration errors
| Python | mit | dajobe/SoCo,flavio/SoCo,KennethNielsen/SoCo,lawrenceakka/SoCo,lawrenceakka/SoCo,bwhaley/SoCo,dundeemt/SoCo,dsully/SoCo,dsully/SoCo,TrondKjeldas/SoCo,bwhaley/SoCo,simonalpha/SoCo,petteraas/SoCo,flavio/SoCo,xxdede/SoCo,SoCo/SoCo,fgend31/SoCo,TrondKjeldas/SoCo,SoCo/SoCo,xxdede/SoCo,dundeemt/SoCo,petteraas/SoCo,intfrr/SoCo... | ---
+++
@@ -14,3 +14,8 @@
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
+
+# http://docs.python.org/2/howto/logging.html#library-config
+# Avoids spurious error messages if no logger is configured by the user
+import loggi... |
46c1378f345c8290fa34fc7f756ef6fafa8e2aa8 | lucid/modelzoo/aligned_activations.py | lucid/modelzoo/aligned_activations.py | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | Remove stray print statement O_o | Remove stray print statement O_o
| Python | apache-2.0 | tensorflow/lucid,tensorflow/lucid,tensorflow/lucid,tensorflow/lucid | ---
+++
@@ -32,6 +32,5 @@
PATH_TEMPLATE.format(sanitize(layer.model_class.name), sanitize(layer.name), page)
for page in range(NUMBER_OF_PAGES)
]
- print(activation_paths)
activations = [load(path) for path in activation_paths]
return np.vstack(activations) |
1e5a956eb289b8333ecf3c3cc00f51295f37870a | api_tests/institutions/views/test_institution_users_list.py | api_tests/institutions/views/test_institution_users_list.py | from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from osf_tests.factories import InstitutionFactory, UserFactory
from api.base.settings.defaults import API_BASE
class TestInstitutionUsersList(ApiTestCase):
def setUp(self):
super(TestInstitutionUsersList, self).setUp()
s... | import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
InstitutionFactory,
UserFactory,
)
@pytest.mark.django_db
class TestInstitutionUsersList:
@pytest.fixture()
def institution(self):
return InstitutionFactory()
@pytest.fixture()
def user_on... | Convert institutions users to pytest | Convert institutions users to pytest
| Python | apache-2.0 | cslzchen/osf.io,chennan47/osf.io,crcresearch/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,icereval/osf.io,crcresearch/osf.io,cslzchen/osf.io,sloria/osf.io,felliott/osf.io,binoculars/osf.io,laurenrevere/osf.io,mfraezz/osf.io,felliott/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,crcresearch/osf.io,adlius/osf.i... | ---
+++
@@ -1,29 +1,42 @@
-from nose.tools import * # flake8: noqa
-
-from tests.base import ApiTestCase
-from osf_tests.factories import InstitutionFactory, UserFactory
+import pytest
from api.base.settings.defaults import API_BASE
+from osf_tests.factories import (
+ InstitutionFactory,
+ UserFactory,
+)
... |
b4627ab3448ab70db44d8e9af3310a0755eeca64 | mediacloud/mediawords/db/schema/version.py | mediacloud/mediawords/db/schema/version.py | import re
from mediawords.util.perl import decode_string_from_bytes_if_needed
class SchemaVersionFromLinesException(Exception):
pass
def schema_version_from_lines(sql: str) -> int:
"""Utility function to determine a database schema version from a bunch of SQL commands."""
sql = decode_string_from_bytes... | import re
from mediawords.util.perl import decode_string_from_bytes_if_needed
class McSchemaVersionFromLinesException(Exception):
pass
def schema_version_from_lines(sql: str) -> int:
"""Utility function to determine a database schema version from a bunch of SQL commands."""
sql = decode_string_from_byt... | Prepend “Mc” to exception name | Prepend “Mc” to exception name
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | ---
+++
@@ -3,7 +3,7 @@
from mediawords.util.perl import decode_string_from_bytes_if_needed
-class SchemaVersionFromLinesException(Exception):
+class McSchemaVersionFromLinesException(Exception):
pass
@@ -12,8 +12,8 @@
sql = decode_string_from_bytes_if_needed(sql)
matches = re.search(r'[+\-]*\... |
97fa1de8a22ff8fd9fd80a39328ec57be672575d | mlabdata.py | mlabdata.py | import collections
"""All of the datatypes that get passed around inside Signal Searcher."""
InternetData = collections.namedtuple(
'InternetData',
['key', 'table', 'time', 'upload', 'download', 'rtt', 'samples'])
# Everything below this line is temporary and should be deleted when the
# migration away from... | """All of the datatypes that get passed around inside Signal Searcher."""
import collections
InternetData = collections.namedtuple(
'InternetData',
['key', 'table', 'time', 'upload', 'download', 'rtt', 'samples'])
# Everything below this line is temporary and should be deleted when the
# migration away from... | Make the string be an actual docstring | Make the string be an actual docstring
| Python | apache-2.0 | m-lab/signal-searcher | ---
+++
@@ -1,6 +1,6 @@
+"""All of the datatypes that get passed around inside Signal Searcher."""
+
import collections
-
-"""All of the datatypes that get passed around inside Signal Searcher."""
InternetData = collections.namedtuple(
'InternetData', |
ca31ecaf79e42cacc023277aa163af8887a360ad | mlog/log.py | mlog/log.py | import gzip
import json
from datetime import datetime
def log_database(conn, param, email):
param = json.dumps(param)
email_gz = gzip.compress(email.encode('ascii'))
values = (param, email_gz)
c = conn.cursor()
c.execute('''
INSERT INTO email_log (`param`, `email_gz`)
VALUES (?, ?)
''', values)
... | import gzip
import json
from datetime import datetime
def log_database(conn, param, email):
param = json.dumps(param)
email_gz = gzip.compress(email.encode('ascii'))
values = (param, email_gz)
c = conn.cursor()
c.execute('''
INSERT INTO email_log (`param`, `email_gz`)
VALUES (?, ?)
''', values)
... | Use with statement when writing to a file | Use with statement when writing to a file
| Python | agpl-3.0 | fajran/mlog | ---
+++
@@ -16,12 +16,11 @@
def log_text(fname, param, email):
from datetime import datetime
- f = open(fname, 'a')
- f.write("=== %s ===\n" % datetime.now())
- f.write("args: %s\n" % (" ".join(param),))
- f.write("-------------\n")
- f.write(email)
- f.write("\n\n")
- f.flush()
- f.close()
+ with open... |
d1e5cce57da49bd93950004b1a4e8766b525106a | backend/unpp_api/apps/common/tests/test_views.py | backend/unpp_api/apps/common/tests/test_views.py | from django.urls import reverse
from agency.roles import AgencyRole
from common.tests.base import BaseAPITestCase
from rest_framework import status
class TestGeneralConfigAPIView(BaseAPITestCase):
user_type = BaseAPITestCase.USER_AGENCY
agency_role = AgencyRole.ADMINISTRATOR
def test_view(self):
... | from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from agency.roles import AgencyRole
from common.tests.base import BaseAPITestCase
from rest_framework import status
class TestGeneralConfigAPIView(BaseAPITestCase):
user_type = BaseAPITestCase.USER_A... | Add testin for unmigrated changes in models | Add testin for unmigrated changes in models
| Python | apache-2.0 | unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal | ---
+++
@@ -1,3 +1,5 @@
+from django.core.management import call_command
+from django.test import TestCase
from django.urls import reverse
from agency.roles import AgencyRole
@@ -24,3 +26,12 @@
def test_view(self):
response = self.client.get('/api/doc/')
self.assertEqual(response.status_cod... |
df385ac3c06018a2d151ead1e07293166ff92614 | erpnext/patches/v11_0/move_leave_approvers_from_employee.py | erpnext/patches/v11_0/move_leave_approvers_from_employee.py | import frappe
from frappe import _
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("hr", "doctype", "department_approver")
frappe.reload_doc("hr", "doctype", "employee")
frappe.reload_doc("hr", "doctype", "department")
if frappe.db.has_column('Department', 'leave_approver... | import frappe
from frappe import _
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("hr", "doctype", "department_approver")
frappe.reload_doc("hr", "doctype", "employee")
frappe.reload_doc("hr", "doctype", "department")
if frappe.db.has_column('Department', 'leave_approver... | Check if table exists else return | Check if table exists else return
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext | ---
+++
@@ -12,6 +12,9 @@
if frappe.db.has_column('Department', 'expense_approver'):
rename_field('Department', "expense_approver", "expense_approvers")
+
+ if not frappe.db.table_exists("Employee Leave Approver"):
+ return
approvers = frappe.db.sql("""select distinct app.leave_approver, emp.department fr... |
a50ff464da06a92edd23d743fecdfa65aa40bedd | test_swift.py | test_swift.py | #!/usr/bin/env python3
from os.path import dirname, realpath
import sys
from test import JAVA_SUITES, INTERPRETERS, run_suites, run_suite
import test
test.REPO_DIR = dirname(realpath(__file__))
SWIFT_SUITES = JAVA_SUITES
def java_to_swift_interpreter(interpreter):
if interpreter.language == 'java':
interpreter.l... | #!/usr/bin/env python3
from os.path import dirname, realpath
import sys
from test import JAVA_SUITES, INTERPRETERS, run_suites, run_suite
import test
test.REPO_DIR = dirname(realpath(__file__))
SWIFT_SUITES = JAVA_SUITES
def java_to_swift_interpreter(interpreter):
if interpreter.language == 'java':
# interpreter... | Fix small bug in swift test runner | Fix small bug in swift test runner
| Python | mit | hashemi/slox,hashemi/slox | ---
+++
@@ -11,7 +11,7 @@
def java_to_swift_interpreter(interpreter):
if interpreter.language == 'java':
- interpreter.language = 'swift'
+ # interpreter.language = 'swift'
interpreter.args = ['.build/debug/slox']
return interpreter
|
8f484f4e79d50f71c0a593429f3e2dad0db56fff | microcosm_flask/matchers.py | microcosm_flask/matchers.py | """
Hamcrest matching support for JSON responses.
"""
from json import dumps, loads
from hamcrest.core.base_matcher import BaseMatcher
def prettify(value):
return dumps(
value,
sort_keys=True,
indent=4,
separators=(',', ': '),
)
class JSON(object):
"""
Dictionary wra... | """
Hamcrest matching support for JSON responses.
"""
from json import dumps, loads
from hamcrest.core.base_matcher import BaseMatcher
def prettify(value):
return dumps(
value,
sort_keys=True,
indent=4,
separators=(',', ': '),
)
class JSON(object):
"""
Dictionary wra... | Add get operation to JSON wrapper | Add get operation to JSON wrapper
| Python | apache-2.0 | globality-corp/microcosm-flask,globality-corp/microcosm-flask | ---
+++
@@ -25,6 +25,9 @@
def __getitem__(self, key):
return self.dct[key]
+
+ def get(self, key):
+ return self.dct.get(key)
def describe_to(self, description):
description.append(prettify(self.dct)) |
a326f2daad6817f426099518da77bc241fd9b51e | bibpy/doi/__init__.py | bibpy/doi/__init__.py | # -*- coding: utf-8 -*-
"""Tools for downloading bibtex files from digital object identifiers."""
import bibpy
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Request, urlopen
def download(doi, source='http://dx.doi.org/{0}', raw=False):
"""Download a bibtex fil... | # -*- coding: utf-8 -*-
"""Tools for downloading bibtex files from digital object identifiers."""
import bibpy
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Request, urlopen
def retrieve(doi, source='http://dx.doi.org/{0}', raw=False, **options):
"""Download a... | Rename doi function, add keyword options | Rename doi function, add keyword options
| Python | mit | MisanthropicBit/bibpy,MisanthropicBit/bibpy | ---
+++
@@ -10,7 +10,7 @@
from urllib2 import Request, urlopen
-def download(doi, source='http://dx.doi.org/{0}', raw=False):
+def retrieve(doi, source='http://dx.doi.org/{0}', raw=False, **options):
"""Download a bibtex file specified by a digital object identifier.
The source is a URL containin... |
8cceb96ae2d8352107dc2e03b336e84e9f2bdfb3 | partner_feeds/templatetags/partner_feed_tags.py | partner_feeds/templatetags/partner_feed_tags.py | from django import template
from partner_feeds.models import Partner
register = template.Library()
@register.assignment_tag
def get_partners(*args):
partners = []
for name in args:
partner = Partner.objects.get(name=name)
partner.posts = partner.post_set.all().order_by('-date')
partners... | from django import template
from partner_feeds.models import Partner
register = template.Library()
@register.assignment_tag
def get_partners(*args):
partners = []
for name in args:
try:
partner = Partner.objects.get(name=name)
except Partner.DoesNotExist:
continue
... | Make Django template tag forgiving of nonexistent partners. | Make Django template tag forgiving of nonexistent partners.
| Python | bsd-2-clause | theatlantic/django-partner-feeds | ---
+++
@@ -6,7 +6,10 @@
def get_partners(*args):
partners = []
for name in args:
- partner = Partner.objects.get(name=name)
+ try:
+ partner = Partner.objects.get(name=name)
+ except Partner.DoesNotExist:
+ continue
partner.posts = partner.post_set.all()... |
f0bcc52a73d4efcc498e9c6d180552188af2359d | IPython/html/kernelspecs/handlers.py | IPython/html/kernelspecs/handlers.py | from tornado import web
from ..base.handlers import IPythonHandler
from ..services.kernelspecs.handlers import kernel_name_regex
class KernelSpecResourceHandler(web.StaticFileHandler, IPythonHandler):
SUPPORTED_METHODS = ('GET', 'HEAD')
def initialize(self):
web.StaticFileHandler.initialize(self, path... | from tornado import web
from ..base.handlers import IPythonHandler
from ..services.kernelspecs.handlers import kernel_name_regex
class KernelSpecResourceHandler(web.StaticFileHandler, IPythonHandler):
SUPPORTED_METHODS = ('GET', 'HEAD')
def initialize(self):
web.StaticFileHandler.initialize(self, path... | Fix HEAD requests for kernelspec resources | Fix HEAD requests for kernelspec resources
Closes gh-7237
Closes gh-7258
StaticFileHandler.get() is a coroutine. When Tornado calls a handler
method, it uses the return value to determine whether or not it's a
coroutine. So when head() calls get(), it needs to pass the return value
on for Tornado to handle it properl... | Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -20,7 +20,7 @@
@web.authenticated
def head(self, kernel_name, path):
- self.get(kernel_name, path, include_body=False)
+ return self.get(kernel_name, path, include_body=False)
default_handlers = [
(r"/kernelspecs/%s/(?P<path>.*)" % kernel_name_regex, KernelSpecResourceHand... |
27ee2752a71ee415154c40e1978edb9d5221a331 | IPython/lib/tests/test_deepreload.py | IPython/lib/tests/test_deepreload.py | """Test suite for the deepreload module."""
from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload
@dec.skipif_not_numpy
def test_deepreload_numpy():
import numpy
exclude = [
# Standard exclusions:
'sys', 'os.path', '__builtin__', '__main__',
... | # -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.testing import decorators as dec
from IPython.lib.deepreload import r... | Reformat test to a standard style. | Reformat test to a standard style.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -1,7 +1,16 @@
+# -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
from IPython.testing import decorators as dec
... |
c2f2acc518f017a0d7b8ccfa6640595f2769aa98 | nib/plugins/prettyurls.py | nib/plugins/prettyurls.py | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
from nib import Resource, Processor, after
apache_redirects = b"""
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)$ /$1/index.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)$ /$1... | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
from nib import Resource, Processor, after
apache_redirects = b"""
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)$ /$1/index.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)$ /$1... | Add nginx rules for pretty URLs | Add nginx rules for pretty URLs
| Python | mit | jreese/nib | ---
+++
@@ -23,6 +23,14 @@
RewriteBase /
"""
+nginx_rules = b"""
+location / {
+ #root {0};
+ index index.html;
+ try_files $uri $uri.html $uri/index.html;
+}
+"""
+
@after
class PrettyURLProcessor(Processor):
def process(self, documents, resources):
@@ -45,4 +53,8 @@
htaccess.content +... |
cec7ee7e98498ec8d15f35c4aef77ea44baefe6b | adhocracy/tests/lib/test_text.py | adhocracy/tests/lib/test_text.py | from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(re... | from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(re... | Fix tests after markdown library change | Fix tests after markdown library change
Addendum to da03b3f033cce2b957a71cf6cb334a8c207c5047
| Python | agpl-3.0 | alkadis/vcv,phihag/adhocracy,phihag/adhocracy,phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,SysTheron/adhocracy,SysTheron/adhocracy,alkadis/vcv,SysTheron/adhocracy,l... | ---
+++
@@ -9,14 +9,14 @@
source = ('header\n'
'========')
result = render(source)
- self.assertEqual(result, u'<h1>header</h1>\n')
+ self.assertEqual(result, u'<h1>header</h1>')
def test_render_no_substitution(self):
from adhocracy.lib.text import re... |
13208d4656adcf52a5842200ee1d9e079fdffc2b | bin/rate_limit_watcher.py | bin/rate_limit_watcher.py | #!/usr/bin/env python
import requests
URL = 'http://tutorials.pluralsight.com/gh_rate_limit'
def main():
resp = requests.get(URL)
if resp.status_code == 200:
print resp.content
else:
print 'Failed checking rate limit, status_code: %d' % (resp.status_code)
if __name__ == '__main__':
... | #!/usr/bin/env python
"""
Script to print out Github API rate limit for REPO_OWNER user i.e. the main
github user account used for the guides-cms application.
"""
import argparse
from datetime import datetime
import requests
DOMAIN = 'http://tutorials.pluralsight.com/'
URL = '/gh_rate_limit'
def main(domain):
... | Print rate limits from new JSON response url in a pretty, parsable format | Print rate limits from new JSON response url in a pretty, parsable format
| Python | agpl-3.0 | paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms | ---
+++
@@ -1,16 +1,71 @@
#!/usr/bin/env python
+"""
+Script to print out Github API rate limit for REPO_OWNER user i.e. the main
+github user account used for the guides-cms application.
+"""
+
+import argparse
+from datetime import datetime
import requests
-URL = 'http://tutorials.pluralsight.com/gh_rate_limi... |
f5a856b6c6c64ff8bba56a04a25bb639e98ff0e2 | navigator/settings/prod.py | navigator/settings/prod.py | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.e... | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.e... | Add locust testing box to allowed IPs, and get the SSL redirect from the environment so that it can be turned off for load testing | Add locust testing box to allowed IPs, and get the SSL redirect from the environment so that it can be turned off for load testing
pep8
| Python | mit | dahfool/navigator,uktrade/navigator,uktrade/navigator,dahfool/navigator,dahfool/navigator,dahfool/navigator,uktrade/navigator,uktrade/navigator | ---
+++
@@ -19,7 +19,8 @@
ip_check = os.environ.get('RESTRICT_IPS', False)
RESTRICT_IPS = ip_check == 'True' or ip_check == '1'
-ALLOWED_IPS = []
+ALLOWED_IPS = ['54.229.170.70']
ALLOWED_IP_RANGES = ['165.225.80.0/22', '193.240.203.32/29', '94.119.64.0/24', '178.208.163.0/24']
-SECURE_SSL_REDIRECT = True
+ssl_... |
63af2d4267f7107232777fa0d8b222dc00f07a90 | test_setup.py | test_setup.py | """Test setup.py."""
import os
import subprocess
import sys
import setup
def test_setup():
"""Run setup.py check."""
command = [
sys.executable,
setup.__file__,
'check',
'--metadata',
'--strict',
]
assert subprocess.run(command, check=False).returncode == 0
... | """Test setup.py."""
import os
import subprocess
import sys
import sysconfig
import setup
def test_setup():
"""Run setup.py check."""
command = [
sys.executable,
setup.__file__,
'check',
'--metadata',
'--strict',
]
assert subprocess.run(command, check=False).... | Check sysconfig 'scripts' instead of scanning PATH | Check sysconfig 'scripts' instead of scanning PATH
| Python | lgpl-2.1 | dmtucker/backlog | ---
+++
@@ -4,6 +4,7 @@
import os
import subprocess
import sys
+import sysconfig
import setup
@@ -22,15 +23,6 @@
def test_console_scripts():
"""Ensure console scripts were installed correctly."""
- assert all(
- any(
- os.path.isfile(
- os.path.join(
- ... |
36ceeed4ff6b578e8b63b222cd9beea4e788a819 | mongo_thingy/__init__.py | mongo_thingy/__init__.py | from pymongo import MongoClient
from thingy import classproperty, DatabaseThingy
class Thingy(DatabaseThingy):
client = None
_collection = None
@classproperty
def collection(cls):
return cls._collection or cls.table
@classproperty
def collection_name(cls):
return cls.collecti... | from pymongo import MongoClient
from thingy import classproperty, DatabaseThingy
class Thingy(DatabaseThingy):
client = None
_collection = None
@classproperty
def collection(cls):
return cls._collection or cls.table
@classproperty
def collection_name(cls):
return cls.collecti... | Define __all__ to restrict global imports | Define __all__ to restrict global imports
| Python | mit | numberly/mongo-thingy | ---
+++
@@ -31,3 +31,6 @@
client = MongoClient(*args, **kwargs)
Thingy.client = client
return client
+
+
+__all__ = ["Thingy", "connect"] |
2b30ebfb05d64dac4663ab4e37dca65c0130f83a | goodtablesio/tasks.py | goodtablesio/tasks.py | import datetime
import logging
import dataset
from celery import Celery
from sqlalchemy.types import DateTime
from sqlalchemy.dialects.postgresql import JSONB
from goodtables import Inspector
from . import config
log = logging.getLogger(__name__)
# Module API
app = Celery('tasks')
app.config_from_object(config)
... | import datetime
import logging
import dataset
from celery import Celery
from sqlalchemy.types import DateTime
from sqlalchemy.dialects.postgresql import JSONB
from goodtables import Inspector
from . import config
log = logging.getLogger(__name__)
# Module API
app = Celery('tasks')
app.config_from_object(config)
... | Make settings optional on validation task | Make settings optional on validation task
| Python | agpl-3.0 | frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io | ---
+++
@@ -33,7 +33,8 @@
"""
# Get report
- inspector = Inspector(**validation_conf['settings'])
+ settings = validation_conf.get('settings', {})
+ inspector = Inspector(**settings)
report = inspector.inspect(validation_conf['files'], preset='tables')
# Save report |
fb49d44cd1cb8ea8a3d291d79546914f15a58491 | greenwich/__init__.py | greenwich/__init__.py | from greenwich.raster import (driver_for_path, frombytes, geom_to_array, open,
AffineTransform, ImageDriver, Raster)
from greenwich.geometry import Envelope, Geometry
from greenwich.srs import SpatialReference
| from greenwich.raster import (driver_for_path, fromarray, frombytes,
geom_to_array, open, AffineTransform, ImageDriver, Raster)
from greenwich.geometry import Envelope, Geometry
from greenwich.srs import SpatialReference
| Add fromarray to package root | Add fromarray to package root
| Python | bsd-3-clause | bkg/greenwich | ---
+++
@@ -1,4 +1,4 @@
-from greenwich.raster import (driver_for_path, frombytes, geom_to_array, open,
- AffineTransform, ImageDriver, Raster)
+from greenwich.raster import (driver_for_path, fromarray, frombytes,
+ geom_to_array, open, AffineTransform, ImageDriver, Raster)
from greenwich.geometry import Envel... |
71088ebbed3f6060def0455814036185c70ba194 | shopify_auth/context_processors.py | shopify_auth/context_processors.py | import shopify
def current_shop(request):
if not shopify.ShopifyResource.site:
return {'current_shop': None}
return {'current_shop': shopify.Shop.current()} | from django.conf import settings
import shopify
def shopify_context(request):
return {
'shopify_current_shop': shopify.Shop.current() if shopify.ShopifyResource.site else None,
'shopify_app_api_key': settings.SHOPIFY_APP_API_KEY,
} | Rename `current_shop` context processor to `shopify_context`, and add a little more useful Shopify information. | Rename `current_shop` context processor to `shopify_context`, and add a little more useful Shopify information. | Python | mit | funkybob/django-shopify-auth,RafaAguilar/django-shopify-auth,discolabs/django-shopify-auth,RafaAguilar/django-shopify-auth,discolabs/django-shopify-auth,funkybob/django-shopify-auth | ---
+++
@@ -1,6 +1,8 @@
+from django.conf import settings
import shopify
-def current_shop(request):
- if not shopify.ShopifyResource.site:
- return {'current_shop': None}
- return {'current_shop': shopify.Shop.current()}
+def shopify_context(request):
+ return {
+ 'shopify_current_shop': shopify.Shop.cur... |
4c39c270af91ddbc213e077fc06b4bf67c7c6e99 | django/core/checks/compatibility/django_1_7_0.py | django/core/checks/compatibility/django_1_7_0.py | from __future__ import unicode_literals
from .. import Warning, register, Tags
@register(Tags.compatibility)
def check_1_7_compatibility(**kwargs):
errors = []
errors.extend(_check_middleware_classes(**kwargs))
return errors
def _check_middleware_classes(app_configs=None, **kwargs):
"""
Checks ... | from __future__ import unicode_literals
from .. import Warning, register, Tags
@register(Tags.compatibility)
def check_1_7_compatibility(**kwargs):
errors = []
errors.extend(_check_middleware_classes(**kwargs))
return errors
def _check_middleware_classes(app_configs=None, **kwargs):
"""
Checks ... | Add missing spaces to implicitly joined strings | Add missing spaces to implicitly joined strings
| Python | bsd-3-clause | liu602348184/django,yask123/django,RevelSystems/django,sgzsh269/django,wweiradio/django,Anonymous-X6/django,spisneha25/django,adamchainz/django,dfunckt/django,Anonymous-X6/django,abomyi/django,jasonbot/django,syphar/django,mttr/django,ckirby/django,tbeadle/django,rmboggs/django,megaumi/django,blindroot/django,rrrene/dj... | ---
+++
@@ -23,10 +23,10 @@
return [
Warning(
"MIDDLEWARE_CLASSES is not set.",
- hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES."
+ hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
... |
12cf94f7cccad5d9fce8b44726756c33f4219a0c | automata/pda/exceptions.py | automata/pda/exceptions.py | #!/usr/bin/env python3
"""Exception classes specific to pushdown automata."""
from automata.base.exceptions import AutomatonException
class PDAException(AutomatonException):
"""The base class for all PDA-related errors."""
pass
class NondeterminismError(PDAException):
"""A DPDA is exhibiting nondeterm... | #!/usr/bin/env python3
"""Exception classes specific to pushdown automata."""
from automata.base.exceptions import AutomatonException
class PDAException(AutomatonException):
"""The base class for all PDA-related errors."""
pass
class NondeterminismError(PDAException):
"""A DPDA is exhibiting nondeterm... | Add blank line to comply with PEP 8 | Add blank line to comply with PEP 8
| Python | mit | caleb531/automata | ---
+++
@@ -15,6 +15,7 @@
pass
+
class InvalidAcceptanceMode(PDAException):
"""The given acceptance mode is invalid."""
pass |
85dcb6ff036d03fd1fadc62a519147cf6b9ca8de | floq/blockmatrix.py | floq/blockmatrix.py | import numpy as np
# Provide functions to get/set blocks in numpy arrays
def get_block_from_matrix(matrix,dim_block,n_block,row,column):
start_row = row*dim_block
start_column = column*dim_block
stop_row = start_row+dim_block
stop_column = start_column+dim_block
return matrix[start_row:stop_row,... | import numpy as np
# Provide functions to get/set blocks in numpy arrays
def get_block_from_matrix(matrix,dim_block,n_block,row,col):
start_row = row*dim_block
start_col = col*dim_block
stop_row = start_row+dim_block
stop_col = start_col+dim_block
return matrix[start_row:stop_row,start_col:stop_... | Rename column -> col for consistency with row | Rename column -> col for consistency with row
| Python | mit | sirmarcel/floq | ---
+++
@@ -2,20 +2,20 @@
# Provide functions to get/set blocks in numpy arrays
-def get_block_from_matrix(matrix,dim_block,n_block,row,column):
+def get_block_from_matrix(matrix,dim_block,n_block,row,col):
start_row = row*dim_block
- start_column = column*dim_block
+ start_col = col*dim_block
... |
980cbb13e874f7d3769dff12992779f676a5b2f3 | plotly/plotly/__init__.py | plotly/plotly/__init__.py | """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from . plotly import (
sign_in, update_plot_options, get_plot_options, get... | """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from . plotly import (
sign_in, update_plot_options, get_plot_options, get... | Add get_config to the list of public functions for plotly.py | Add get_config to the list of public functions for plotly.py
| Python | mit | plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/plotly.py,ee-in/python-api | ---
+++
@@ -9,5 +9,5 @@
"""
from . plotly import (
sign_in, update_plot_options, get_plot_options, get_credentials, iplot,
- plot, iplot_mpl, plot_mpl, get_figure, Stream, image
+ plot, iplot_mpl, plot_mpl, get_figure, Stream, image, get_config
) |
388826605b556a9632c3dea22ca3ba1219dfc5ea | wallp/main.py | wallp/main.py | import sys
from redcmd.api import execute_commandline
def main():
from .db.manage.db import DB
db = DB()
response = db.check()
from util.printer import printer
response and printer.printf('program maintenance', response)
from .util import log
from .db.app.config import Config, ConfigError
from . import c... | import sys
from redcmd.api import execute_commandline
def main():
from .db.manage.db import DB
db = DB()
response = db.check()
from util.printer import printer
response and printer.printf('program maintenance', response)
from .util import log
from .db.app.config import Config, ConfigError
from . import c... | Change default subcommand to "source random" | Change default subcommand to "source random"
| Python | mit | amol9/wallp | ---
+++
@@ -30,5 +30,5 @@
printer.printf('program maintenance', 'updated autocomplete data')
execute_commandline(prog=const.app_name, description=const.app_description, version=__version__, _to_hyphen=True,
- default_subcommand='change', moves=True, update_autocomplete_cb=update_autocomplete_cb)
+ default... |
e7691a775dc745984155a5f2e07140c207c3ab20 | api/base/parsers.py | api/base/parsers.py | from rest_framework.parsers import JSONParser
from api.base.renderers import JSONAPIRenderer
from api.base.exceptions import JSONAPIException
class JSONAPIParser(JSONParser):
"""
Parses JSON-serialized data. Overrides media_type.
"""
media_type = 'application/vnd.api+json'
renderer_class = JSONAPI... | from rest_framework.parsers import JSONParser
from rest_framework.exceptions import ValidationError
from api.base.renderers import JSONAPIRenderer
from api.base.exceptions import JSONAPIException
class JSONAPIParser(JSONParser):
"""
Parses JSON-serialized data. Overrides media_type.
"""
media_type = '... | Enforce that request data is a dictionary. | Enforce that request data is a dictionary.
| Python | apache-2.0 | DanielSBrown/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,sloria/osf.io,Ghalko/osf.io,felliott/osf.io,caseyrygt/osf.io,jnayak1/osf.io,caneruguz/osf.io,mfraezz/osf.io,kch8qx/osf.io,KAsante95/osf.io,emetsger/osf.io,caseyrygt/osf.io,mluo613/osf.io,samchrisinger/osf.io,wearpants/osf.io,billyhunt/osf.io,chennan47/osf.io,Ne... | ---
+++
@@ -1,4 +1,5 @@
from rest_framework.parsers import JSONParser
+from rest_framework.exceptions import ValidationError
from api.base.renderers import JSONAPIRenderer
from api.base.exceptions import JSONAPIException
@@ -15,16 +16,18 @@
Parses the incoming bytestream as JSON and returns the resultin... |
bc9488b6954c172d903521df9f00c7ff71243fff | tests.py | tests.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
linescan.py - Effortlessly read lines from a text file using any encoding
Created 2013-2014 Triangle717
<http://Triangle717.WordPress.com/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
from __future__ import print_function
... | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
linescan.py - Effortlessly read lines from a text file using any encoding
Created 2013-2014 Triangle717
<http://Triangle717.WordPress.com/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
from __future__ import print_function
... | Fix F401 error (module imported but unused) | Fix F401 error (module imported but unused)
[ci skip] | Python | mit | le717/linescan.py | ---
+++
@@ -10,7 +10,6 @@
"""
from __future__ import print_function
-import sys
import os
import linescan |
d2106c0a6cb4bbf523914786ded873261cb174c2 | nipype/pipeline/__init__.py | nipype/pipeline/__init__.py | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from .engine import Node, MapNode, Workflow
from .utils import write_prov
| # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from engine import Node, MapNode, JoinNode, Workflow
from .utils import write_prov
| Add JoinNode to pipeline init | Add JoinNode to pipeline init
| Python | bsd-3-clause | arokem/nipype,gerddie/nipype,Leoniela/nipype,fprados/nipype,pearsonlab/nipype,blakedewey/nipype,carolFrohlich/nipype,blakedewey/nipype,gerddie/nipype,dgellis90/nipype,glatard/nipype,arokem/nipype,carlohamalainen/nipype,carolFrohlich/nipype,Leoniela/nipype,glatard/nipype,dmordom/nipype,grlee77/nipype,carolFrohlich/nipyp... | ---
+++
@@ -5,5 +5,5 @@
"""
__docformat__ = 'restructuredtext'
-from .engine import Node, MapNode, Workflow
+from engine import Node, MapNode, JoinNode, Workflow
from .utils import write_prov |
780d1fa408677994c739ce489bd0fde2ed6242f0 | ideascaly/__init__.py | ideascaly/__init__.py | __author__ = 'jorgesaldivar'
| # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
"""
IdeaScaly: IdeaScale API client
"""
__version__ = '0.1'
__author__ = 'Jorge Saldivar'
__license__ = 'MIT'
from ideascaly.api import API
from ideascaly.auth import AuthNonSSO, AuthNonSSOMem, AuthSSO, AuthResearch
from ideascaly.error import Id... | Add details of the project | Add details of the project
| Python | mit | joausaga/ideascaly | ---
+++
@@ -1 +1,17 @@
-__author__ = 'jorgesaldivar'
+# IdeaScaly
+# Copyright 2015 Jorge Saldivar
+# See LICENSE for details.
+
+"""
+IdeaScaly: IdeaScale API client
+"""
+
+__version__ = '0.1'
+__author__ = 'Jorge Saldivar'
+__license__ = 'MIT'
+
+from ideascaly.api import API
+from ideascaly.auth import AuthNonSSO... |
30b56f27cff21b93d68524fc992d6e731fb80e57 | tests.py | tests.py | from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class BoardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
print "list boards"
se... | from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class TrelloTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
self.assertEquals(
... | Make it a single test case | Make it a single test case
| Python | bsd-3-clause | Wooble/py-trello,mehdy/py-trello,ntrepid8/py-trello,portante/py-trello,nMustaki/py-trello,WoLpH/py-trello,sarumont/py-trello,merlinpatt/py-trello,gchp/py-trello | ---
+++
@@ -3,30 +3,22 @@
import unittest
import os
-class BoardTestCase(unittest.TestCase):
+class TrelloTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
- print "list boards"
self.asse... |
7e2565007c926765750641b048607ed29b8aada0 | cmsplugin_zinnia/admin.py | cmsplugin_zinnia/admin.py | """Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zi... | """Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zi... | Add comment about why excepting KeyError | Add comment about why excepting KeyError
| Python | bsd-3-clause | bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia | ---
+++
@@ -29,6 +29,7 @@
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
+ # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmi... |
6d143e8b3d060ca4639b08c15d7e826e0ee68c8c | neutron/tests/unit/objects/test_address_scope.py | neutron/tests/unit/objects/test_address_scope.py | # Copyright (c) 2016 Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | # Copyright (c) 2016 Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Use BaseDbObjectTestCase in AddressScope UT | Use BaseDbObjectTestCase in AddressScope UT
AddressScopeDbObjectTestCase class is using _BaseObjectTestCase class
which doesn't contain all the unit test cases for Oslo-Versioned
classes. This patch replace that class.
Partially-Implements: blueprint adopt-oslo-versioned-objects-for-db
Change-Id: I180046743471487a9f... | Python | apache-2.0 | huntxu/neutron,noironetworks/neutron,noironetworks/neutron,eayunstack/neutron,openstack/neutron,mahak/neutron,mahak/neutron,cloudbase/neutron,mahak/neutron,sebrandon1/neutron,huntxu/neutron,sebrandon1/neutron,openstack/neutron,cloudbase/neutron,openstack/neutron,eayunstack/neutron | ---
+++
@@ -22,7 +22,7 @@
_test_class = address_scope.AddressScope
-class AddressScopeDbObjectTestCase(obj_test_base._BaseObjectTestCase,
+class AddressScopeDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
testlib_api.SqlTestCase):
_test_class = address_scope.Ad... |
ca62db36a14c9bcc447cb612a8fba4dd2c678629 | functional_tests.py | functional_tests.py | #!/usr/bin/env python
from unittest import TestCase
import mechanize
class ResponseTests(TestCase):
def test_close_pickle_load(self):
import pickle
b = mechanize.Browser()
r = b.open("http://wwwsearch.sf.net/bits/cctest2.txt")
r.read()
r.close()
r.seek(0)
... | #!/usr/bin/env python
from unittest import TestCase
import mechanize
class ResponseTests(TestCase):
def test_close_pickle_load(self):
print ("This test is expected to fail unless Python standard library"
"patch http://python.org/sf/1144636 has been applied")
import pickle
... | Add warning about failing functional test | Add warning about failing functional test
| Python | bsd-3-clause | python-mechanize/mechanize,python-mechanize/mechanize | ---
+++
@@ -6,6 +6,8 @@
class ResponseTests(TestCase):
def test_close_pickle_load(self):
+ print ("This test is expected to fail unless Python standard library"
+ "patch http://python.org/sf/1144636 has been applied")
import pickle
b = mechanize.Browser() |
baaeb4fe0998bac8e0cb853d8124aa6134f55996 | poradnia/letters/admin.py | poradnia/letters/admin.py | from django.contrib import admin
from .models import Attachment, Letter
class AttachmentInline(admin.StackedInline):
'''
Stacked Inline View for Attachment
'''
model = Attachment
class LetterAdmin(admin.ModelAdmin):
'''
Admin View for Letter
'''
inlines = [
Attachmen... | from django.contrib import admin
from .models import Attachment, Letter
class AttachmentInline(admin.StackedInline):
'''
Stacked Inline View for Attachment
'''
model = Attachment
@admin.register(Letter)
class LetterAdmin(admin.ModelAdmin):
'''
Admin View for Letter
'''
inlin... | Rewrite DjangoAdmin in letters for decorators | Rewrite DjangoAdmin in letters for decorators
| Python | mit | rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia | ---
+++
@@ -10,6 +10,7 @@
model = Attachment
+@admin.register(Letter)
class LetterAdmin(admin.ModelAdmin):
'''
Admin View for Letter
@@ -17,5 +18,3 @@
inlines = [
AttachmentInline,
]
-
-admin.site.register(Letter, LetterAdmin) |
e36e6c4db61381ca9f29ce1dc5f645cb65d3ba21 | capstone/util/play.py | capstone/util/play.py | from __future__ import print_function
import random
from capstone.util import print_header
def play_match(game, players, verbose=True):
"""Plays a match between the given players"""
if verbose:
print(game)
while not game.is_over():
cur_player = players[game.cur_player()]
move = cur... | from __future__ import print_function
import random
from . import print_header
def play_match(game, players, verbose=True):
"""Plays a match between the given players"""
if verbose:
print(game)
while not game.is_over():
cur_player = players[game.cur_player()]
move = cur_player.choo... | Change absolute import to relative | Change absolute import to relative
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -1,6 +1,6 @@
from __future__ import print_function
import random
-from capstone.util import print_header
+from . import print_header
def play_match(game, players, verbose=True): |
5486503c3e9664c1683e5de9381b4d0d413182c3 | ipywidgets/widgets/widget_description.py | ipywidgets/widgets/widget_description.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Contains the DOMWidget class"""
from traitlets import Unicode
from .widget import Widget, widget_serialization, register
from .trait_types import InstanceDict
from .widget_style import Style
from .widget_core impor... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Contains the DOMWidget class"""
from traitlets import Unicode
from .widget import Widget, widget_serialization, register
from .trait_types import InstanceDict
from .widget_style import Style
from .widget_core impor... | Tweak the help text for the new tooltip attribute. | Tweak the help text for the new tooltip attribute. | Python | bsd-3-clause | ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets | ---
+++
@@ -21,7 +21,7 @@
"""Widget that has a description label to the side."""
_model_name = Unicode('DescriptionModel').tag(sync=True)
description = Unicode('', help="Description of the control.").tag(sync=True)
- description_tooltip = Unicode(None, allow_none=True, help="Tooltip for the descript... |
0b41090984647de0e5b3228e871c26c57a005938 | omp/__init__.py | omp/__init__.py | '''
OpenMP wrapper using a (user provided) libgomp dynamically loaded library
'''
import sys
import glob
import ctypes
class omp(object):
LD_LIBRARY_PATHS = [
"/usr/lib/x86_64-linux-gnu/",
# MacPorts install gcc in a "non standard" path on OSX
] + glob.glob("/opt/local/lib/gcc*/")
def __... | '''
OpenMP wrapper using a (user provided) libgomp dynamically loaded library
'''
import sys
import glob
import ctypes
class omp(object):
LD_LIBRARY_PATHS = [
"/usr/lib/x86_64-linux-gnu/",
# MacPorts install gcc in a "non standard" path on OSX
] + glob.glob("/opt/local/lib/gcc*/")
def __... | Fix gomp library dynamic loading issues | Fix gomp library dynamic loading issues
* bug introduce from commit : 4a4676258bfd47a7fbefc51644eb58ffc60ab6ad
| Python | bsd-3-clause | pbrunet/pythran,artas360/pythran,pbrunet/pythran,hainm/pythran,pbrunet/pythran,hainm/pythran,pombredanne/pythran,artas360/pythran,pombredanne/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,pombredanne/pythran,serge-sans-paille/pythran | ---
+++
@@ -18,13 +18,13 @@
paths = omp.LD_LIBRARY_PATHS
# Try to load find libgomp shared library using loader search dirs
- libgomp_path = ctypes.util.find_library("libgomp")
+ libgomp_path = ctypes.util.find_library("gomp")
# Try to use custom paths if lookup failed
... |
3fcb69fbb623184a30d1d5ecb41e4c3c33128f1a | src/lyra/tests/dictionary/dict_descr_example.py | src/lyra/tests/dictionary/dict_descr_example.py |
important: Set[str] = {"Albert Einstein" , "Alan Turing"}
texts: Dict[str, str] = input() # {"<author >" : "<t e x t >"}
freqdict: Dict[str, int] = {} # defaultdict(int) err: int recognized as varId #initialized to 0
a: str = "" #necessary?
b: str = ""
for a, b in texts.items():
if a in important: #... |
important: Set[str] = {"Albert Einstein" , "Alan Turing"}
texts: Dict[str, str] = input() # {"<author >" : "<t e x t >"}
freqdict: Dict[str, int] = {} # defaultdict(int) err: int recognized as varId #initialized to 0
a: str = "" #necessary?
b: str = ""
for a, b in texts.items():
if a in important: #t... | Fix to typing of loop variables | Fix to typing of loop variables
| Python | mpl-2.0 | caterinaurban/Lyra | ---
+++
@@ -3,7 +3,7 @@
texts: Dict[str, str] = input() # {"<author >" : "<t e x t >"}
freqdict: Dict[str, int] = {} # defaultdict(int) err: int recognized as varId #initialized to 0
-a: str = "" #necessary?
+a: str = "" #necessary?
b: str = ""
for a, b in texts.items():
if a in important: ... |
e99a0bdde697a0508bc17a8dd66943cdf97bdc3d | Main_program/src/main_program.py | Main_program/src/main_program.py | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
if __name__ == "__main__":
print "Hello World"
| # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
print("Hello World")
print("Hessel is een home") | Test commit push and pull | Test commit push and pull
| Python | apache-2.0 | HesselTjeerdsma/Cyber-Physical-Pacman-Game,HesselTjeerdsma/Cyber-Physical-Pacman-Game,HesselTjeerdsma/Cyber-Physical-Pacman-Game,HesselTjeerdsma/Cyber-Physical-Pacman-Game,HesselTjeerdsma/Cyber-Physical-Pacman-Game,HesselTjeerdsma/Cyber-Physical-Pacman-Game | ---
+++
@@ -2,5 +2,5 @@
# To change this template file, choose Tools | Templates
# and open the template in the editor.
-if __name__ == "__main__":
- print "Hello World"
+print("Hello World")
+print("Hessel is een home") |
70cb8045b00445089db6aaa710a0899e1f4cbab1 | porick/settings.py | porick/settings.py | SITE_NAME = 'Porick'
WELCOME_TEXT = '''Porick is yet another IRC Quotes web application, designed to replace <i>Chirpy!</i>'''
HOMEPAGE_BUTTON_TEXT = 'Start browsing'
QUOTES_PER_PAGE = 10
TABLES = {
'accounts': 'chirpy_accounts',
'event_metadata': 'chirpy_event_metadata',
'events': 'chirpy_events',
'new... | SITE_NAME = 'Porick.'
WELCOME_TEXT = '''Porick is yet another IRC Quotes web application, designed to replace <i>Chirpy!</i>'''
HOMEPAGE_BUTTON_TEXT = 'Start browsing'
QUOTES_PER_PAGE = 10
TABLES = {
'accounts': 'chirpy_accounts',
'event_metadata': 'chirpy_event_metadata',
'events': 'chirpy_events',
'ne... | Add hipster full-stop to the front-page | Add hipster full-stop to the front-page
| Python | apache-2.0 | kopf/porick,kopf/porick,kopf/porick | ---
+++
@@ -1,4 +1,4 @@
-SITE_NAME = 'Porick'
+SITE_NAME = 'Porick.'
WELCOME_TEXT = '''Porick is yet another IRC Quotes web application, designed to replace <i>Chirpy!</i>'''
HOMEPAGE_BUTTON_TEXT = 'Start browsing'
QUOTES_PER_PAGE = 10 |
43a672574d13ce3ce267f5e4773c5d26827a4b9a | app/sso/backends.py | app/sso/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False
def authenticate(self, username=No... | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from hashlib import sha1
class SimpleHashModelBackend(ModelBackend):
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False
def authenticate(self, username=No... | Switch authenticator to migrate back to Django style passwords | Switch authenticator to migrate back to Django style passwords
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -17,11 +17,10 @@
if '$' in user.password:
if user.check_password(password):
- user.password = sha1(password).hexdigest()
- user.save()
return user
else:
if user.password == sha1(password).hexdigest():
+ user.set_p... |
74cd91babf7466c35fbb680c10d5f2451b1409b0 | appengine_config.py | appengine_config.py | import os
import sys
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.
vendor.add('lib')
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep
SHARED_SOURCE_DIRECTORIES = [
os.path.abspath(os.environ.get('ISB_CGC_COMMON_MODU... | import os
import sys
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.
vendor.add('lib')
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep
SHARED_SOURCE_DIRECTORIES = [
os.path.abspath('./ISB-CGC-Common')
]
# Add the sh... | Use hardcoded path for ISB-CGC-Common | Use hardcoded path for ISB-CGC-Common
| Python | apache-2.0 | isb-cgc/ISB-CGC-API,isb-cgc/ISB-CGC-API,isb-cgc/ISB-CGC-API | ---
+++
@@ -8,7 +8,7 @@
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep
SHARED_SOURCE_DIRECTORIES = [
- os.path.abspath(os.environ.get('ISB_CGC_COMMON_MODULE_PATH'))
+ os.path.abspath('./ISB-CGC-Common')
]
# Add the shared Django application subdirect... |
edfc43f4c6041166845e5e4ffd2db58802d3e8c6 | ml/pytorch/image_classification/architectures.py | ml/pytorch/image_classification/architectures.py | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flat... | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flat... | Add custom FC layer module | FEAT: Add custom FC layer module
| Python | apache-2.0 | ronrest/convenience_py,ronrest/convenience_py | ---
+++
@@ -41,3 +41,19 @@
return sq
+def fc(fin, out, bn=True, bias=False, dropout=None, activation=nn.ReLU):
+ """ Fully connected module
+ FC > BatchNorm > Activation > Dropout
+ """
+ sq = nn.Sequential()
+ sq.add_module("fc", nn.Linear(fin, out, bias=bias))
+
+ if bn is not None:
+... |
23606cec326b75cb73ba31b93410770659481d41 | test_echo.py | test_echo.py | # -*- coding: utf-8 -*-
import subprocess
import pytest
def test_basic(string="This is a test."):
"""Test function to test echo server and client with inputted string."""
process = subprocess.Popen(['./echo_client.py', string],
stdout=subprocess.PIPE)
assert string == proces... | # -*- coding: utf-8 -*-
import subprocess
def test_basic(string=u"This is a test."):
"""Test function to test echo server and client with inputted string."""
process = subprocess.Popen(['./echo_client.py', string],
stdout=subprocess.PIPE)
assert string == process.stdout.read... | Change unicode test, to test decoding and encoding is done correctly. | Change unicode test, to test decoding and encoding is done correctly.
| Python | mit | bm5w/network_tools | ---
+++
@@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
import subprocess
-import pytest
-def test_basic(string="This is a test."):
+def test_basic(string=u"This is a test."):
"""Test function to test echo server and client with inputted string."""
process = subprocess.Popen(['./echo_client.py', string],
... |
54461c89b61ba118ef98389c09b45138b32224ab | stagecraft/apps/datasets/admin/backdrop_user.py | stagecraft/apps/datasets/admin/backdrop_user.py | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | Add filter_horizontal to backdrop user admin | Add filter_horizontal to backdrop user admin
- Provides a much more usable interface to filter and add data_sets for backdrop admin users
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft | ---
+++
@@ -16,6 +16,7 @@
search_fields = ['email', 'data_sets']
list_display = ('email', 'numer_of_datasets_user_has_access_to',)
list_per_page = 30
+ filter_horizontal = ('data_sets',)
def queryset(self, request):
return BackdropUser.objects.annotate( |
3af95029c3f784e17247abcd0123156ff9384513 | pronto/serializers/base.py | pronto/serializers/base.py | import abc
import io
import typing
from typing import BinaryIO, ClassVar
from ..ontology import Ontology
class BaseSerializer(abc.ABC):
format: ClassVar[str] = NotImplemented
def __init__(self, ont: Ontology):
self.ont = ont
@abc.abstractmethod
def dump(self, file: BinaryIO, encoding: str ... | import abc
import io
import typing
from typing import BinaryIO, ClassVar
from ..ontology import Ontology
class BaseSerializer(abc.ABC):
format: ClassVar[str] = NotImplemented
def __init__(self, ont: Ontology):
self.ont = ont
@abc.abstractmethod
def dump(self, file: BinaryIO) -> None:
... | Fix signature of `BaseSerializer.dump` to remove `encoding` argument | Fix signature of `BaseSerializer.dump` to remove `encoding` argument
| Python | mit | althonos/pronto | ---
+++
@@ -14,7 +14,7 @@
self.ont = ont
@abc.abstractmethod
- def dump(self, file: BinaryIO, encoding: str = "utf-8") -> None:
+ def dump(self, file: BinaryIO) -> None:
return NotImplemented
def dumps(self) -> str: |
dbc234df7541f6aab32bce0c8f8ba149f9e4ad22 | speeches/management/commands/populatespeakers.py | speeches/management/commands/populatespeakers.py | from django.core.management.base import NoArgsCommand
import pprint
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
pp = pprint.PrettyPrinter(indent=4)
# Do popu... | from django.core.management.base import NoArgsCommand
import pprint
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
pp = pprint.PrettyPrinter(indent=4)
# Do popu... | Make speaker population code use get_or_create instead of exception | Make speaker population code use get_or_create instead of exception
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | ---
+++
@@ -11,13 +11,8 @@
# Do populating
api = PopIt(instance = 'ukcabinet', hostname = 'ukcabinet.popit.mysociety.org', api_version = 'v1')
results = api.person.get()
- self.stdout.write('Names will be:\n')
for person in results['results']:
- self.stdout.write(... |
93e7703e6b7c9115e441c1a285e508a7d0738639 | mica/starcheck/__init__.py | mica/starcheck/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, get_mp_dir, get_monitor_windows
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .starcheck import (get_starcheck_catalog, get_starcheck_catalog_at_date,
get_mp_dir, get_monitor_windows, get_dither, get_att, get_starcat)
| Add new get_ starcheck methods to exported/init methods | Add new get_ starcheck methods to exported/init methods
| Python | bsd-3-clause | sot/mica,sot/mica | ---
+++
@@ -1,2 +1,3 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
-from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, get_mp_dir, get_monitor_windows
+from .starcheck import (get_starcheck_catalog, get_starcheck_catalog_at_date,
+ get_mp_dir, get... |
ab16cd72a2f2ed093f206b48379fb9f03f8d2f36 | tests/example.py | tests/example.py | import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
uni... | import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def setUp(self):
""" This method will be called *before* each test run. """
pass
def tearDown(self):
""" T... | Add setUp and tearDown to test file | Add setUp and tearDown to test file
| Python | mit | pawel-lewtak/coding-dojo-template-python | ---
+++
@@ -7,6 +7,14 @@
class ExampleTest(unittest.TestCase):
+ def setUp(self):
+ """ This method will be called *before* each test run. """
+ pass
+
+ def tearDown(self):
+ """ This method will be called *after* each test run. """
+ pass
+
def test_example(self):
... |
0ff0a3137ea938b7db8167d132b08b9e8620e864 | contrib/internal/run-pyflakes.py | contrib/internal/run-pyflakes.py | #!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.
import os
import subprocess
import sys
module_exclusions = [
'djblets',
'django_evolution',
'dist',
'ez_setup.py',
'settings_local.py',
'ReviewBoard.egg-info',
]
... | #!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.
import os
import subprocess
import sys
module_exclusions = [
'djblets',
'django_evolution',
'dist',
'ez_setup.py',
'htdocs',
'settings_local.py',
'ReviewBoard.e... | Exclude htdocs, because that just takes way too long to scan. | Exclude htdocs, because that just takes way too long to scan.
| Python | mit | atagar/ReviewBoard,atagar/ReviewBoard,sgallagher/reviewboard,chazy/reviewboard,chipx86/reviewboard,Khan/reviewboard,custode/reviewboard,atagar/ReviewBoard,Khan/reviewboard,chazy/reviewboard,atagar/ReviewBoard,bkochendorfer/reviewboard,davidt/reviewboard,asutherland/opc-reviewboard,Khan/reviewboard,Khan/reviewboard,beol... | ---
+++
@@ -13,6 +13,7 @@
'django_evolution',
'dist',
'ez_setup.py',
+ 'htdocs',
'settings_local.py',
'ReviewBoard.egg-info',
] |
16d928d67b76843d8eeea4e145e43e3d073b1410 | qiskit/__init__.py | qiskit/__init__.py | from ._classicalregister import ClassicalRegister
from ._quantumregister import QuantumRegister
from ._quantumcircuit import QuantumCircuit
from ._gate import Gate
from ._compositegate import CompositeGate
from ._instruction import Instruction
from ._instructionset import InstructionSet
from ._qiskiterror import... | from ._classicalregister import ClassicalRegister
from ._quantumregister import QuantumRegister
from ._quantumcircuit import QuantumCircuit
from ._gate import Gate
from ._compositegate import CompositeGate
from ._instruction import Instruction
from ._instructionset import InstructionSet
from ._qiskiterror import... | Change version number to next major stable | Change version number to next major stable
Master branch is used as a development branch, so the version number should point to the next major stable version. | Python | apache-2.0 | ChristopheVuillot/qiskit-sdk-py,ChristopheVuillot/qiskit-sdk-py,QISKit/qiskit-sdk-py,ChristopheVuillot/qiskit-sdk-py,atilag/qiskit-sdk-py,atilag/qiskit-sdk-py,atilag/qiskit-sdk-py,QISKit/qiskit-sdk-py,QISKit/qiskit-sdk-py | ---
+++
@@ -11,5 +11,5 @@
from ._quantumprogram import QuantumProgram
from ._quantumprogram import Result
-__version__ = '0.3.5'
+__version__ = '0.4.0'
|
84257aaf865a913a0ed1888cdf6ce6f22d63f4e5 | tests/functional/firefox/os/test_fxos_navigation.py | tests/functional/firefox/os/test_fxos_navigation.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.fxos_navigation import FirefoxPage
@pytest.mark.nondestructive
@pytest.mark.parametr... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.family_navigation import FirefoxPage
@pytest.mark.nondestructive
@pytest.mark.parame... | Fix incorrect import for FxOS nav tests. | Fix incorrect import for FxOS nav tests.
| Python | mpl-2.0 | mozilla/bedrock,Sancus/bedrock,TheJJ100100/bedrock,flodolo/bedrock,MichaelKohler/bedrock,Sancus/bedrock,ericawright/bedrock,sgarrity/bedrock,CSCI-462-01-2017/bedrock,jgmize/bedrock,TheoChevalier/bedrock,sylvestre/bedrock,analytics-pros/mozilla-bedrock,gerv/bedrock,mkmelin/bedrock,analytics-pros/mozilla-bedrock,kyoshino... | ---
+++
@@ -4,7 +4,7 @@
import pytest
-from pages.firefox.fxos_navigation import FirefoxPage
+from pages.firefox.family_navigation import FirefoxPage
@pytest.mark.nondestructive |
63146c651817ebad688bbcd154fefbf109a39ba0 | server.py | server.py | from igc.util import cache, util
util.setupLog()
from flask import Flask
from flask import send_from_directory
from flask_cors import CORS
from igc.controller.controller_register import register_controllers
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///./sqllite.db"
app.config['SQ... | from igc.util import cache, util
util.setupLog()
from flask import Flask
from flask import send_from_directory
from flask_cors import CORS
from igc.controller.controller_register import register_controllers
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///./sqllite.db"
app.config['SQ... | Scale back threading, beacause Rasp Pi doesn't have enough threads | Scale back threading, beacause Rasp Pi doesn't have enough threads
| Python | agpl-3.0 | pac-club-2017/instant-grade-checker,pac-club-2017/instant-grade-checker,pac-club-2017/instant-grade-checker,pac-club-2017/instant-grade-checker | ---
+++
@@ -12,7 +12,7 @@
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
register_controllers(app)
cache.initalizeCache()
-for x in range(5):
+for x in range(3):
print "Starting Cache Thread: " + str(x)
thread = cache.CacheThread()
thread.start() |
f996038681aed05645164642c8fed7d46735ca4b | deferrable/backend/sqs.py | deferrable/backend/sqs.py | from .base import BackendFactory, Backend
from ..queue.sqs import SQSQueue
class SQSBackendFactory(BackendFactory):
def __init__(self, sqs_connection_or_thunk, visibility_timeout=30, wait_time=10, create_if_missing=False):
if callable(sqs_connection_or_thunk):
self.sqs_connection_thunk = sqs_co... | from .base import BackendFactory, Backend
from ..queue.sqs import SQSQueue
class SQSBackendFactory(BackendFactory):
def __init__(self, sqs_connection_thunk, visibility_timeout=30, wait_time=10, create_if_missing=False):
"""To allow backends to be initialized lazily, this factory requires a thunk
(p... | Remove option for non-thunk SQS initialization | Remove option for non-thunk SQS initialization
| Python | mit | gamechanger/deferrable | ---
+++
@@ -2,11 +2,13 @@
from ..queue.sqs import SQSQueue
class SQSBackendFactory(BackendFactory):
- def __init__(self, sqs_connection_or_thunk, visibility_timeout=30, wait_time=10, create_if_missing=False):
- if callable(sqs_connection_or_thunk):
- self.sqs_connection_thunk = sqs_connection... |
48f6329a74bde4b045aff31e6b2def11c151d294 | couchdb/tests/testutil.py | couchdb/tests/testutil.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_d... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs ... | Use a random number instead of uuid for temp database name. | Use a random number instead of uuid for temp database name.
| Python | bsd-3-clause | gcarranza/couchdb-python,jur9526/couchdb-python | ---
+++
@@ -6,7 +6,8 @@
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
-import uuid
+import random
+import sys
from couchdb import client
class TempDatabaseMixin(object):
@@ -25,7 +26,12 @@
def temp_db(self):
if self.t... |
f87585d51493157e89c0117a25bf7a6d4b2b135f | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
from django.conf import settings
import django
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
'spillway',
'tests',
),
'DATABASES': {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.spatialite',
'NAME': ':memory:'
... | #!/usr/bin/env python
import os
import sys
from django.conf import settings
import django
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
'django.contrib.gis',
'spillway',
'tests',
),
'DATABASES': {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.spatialite',
... | Enable contrib.gis for test runs so templates are found | Enable contrib.gis for test runs so templates are found
| Python | bsd-3-clause | kuzmich/django-spillway,barseghyanartur/django-spillway,bkg/django-spillway | ---
+++
@@ -7,6 +7,7 @@
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
+ 'django.contrib.gis',
'spillway',
'tests',
), |
e01140053a2a906084d0ba50801b17d4ae7ce850 | samples/unmanage_node.py | samples/unmanage_node.py | import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
interfaceId = results['resu... | import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', i... | Correct node variable name and validate results | Correct node variable name and validate results
| Python | apache-2.0 | solarwinds/orionsdk-python | ---
+++
@@ -9,12 +9,17 @@
password = ''
swis = SwisClient(hostname, username, password)
- results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
- interfaceId = results['results'][0]['NodeID']
- netObjectId = 'N:{}'.format(interfaceId)
- now = datetime.utcnow()
- tomorrow = now + time... |
fd3c24537b9af6f7c79fc17b932c01372a569856 | brake/backends/dummybe.py | brake/backends/dummybe.py | import random
from cachebe import CacheBackend
class DummyBackend(CacheBackend):
"""
A dummy rate-limiting backend that disables rate-limiting,
for testing.
"""
def get_ip(self, request):
return str(random.randrange(10e20))
| import random
from cachebe import CacheBackend
class DummyBackend(CacheBackend):
"""
A dummy rate-limiting backend that disables rate-limiting,
for testing.
"""
def get_ip(self, request):
return str(random.randrange(10e20))
def limit(self, func_name, request,
ip=True, ... | Make the dummy limit function always return nothing. | Make the dummy limit function always return nothing.
| Python | bsd-3-clause | SilentCircle/django-brake,SilentCircle/django-brake,skorokithakis/django-brake,skorokithakis/django-brake | ---
+++
@@ -11,3 +11,8 @@
def get_ip(self, request):
return str(random.randrange(10e20))
+
+ def limit(self, func_name, request,
+ ip=True, field=None, count=5, period=None):
+ """Return limit data about any keys relevant for requst."""
+ return [] |
ded82a3f9f438206a5f6ffb02739ad2fe71a08ce | rtrss/config_production.py | rtrss/config_production.py | import os
SQLALCHEMY_DATABASE_URI = os.environ.get('OPENSHIFT_POSTGRESQL_DB_URL')
# directory to store runtime data, write access required
DATA_DIR = os.environ.get('OPENSHIFT_DATA_DIR')
SECRET_KEY = os.environ.get('RTRSS_SECRET_KEY')
FILESTORAGE_URL = os.environ.get('RTRSS_FILESTORAGE_URL')
GCS_PRIVATEKEY_URL = os... | import os
SQLALCHEMY_DATABASE_URI = os.environ.get('OPENSHIFT_POSTGRESQL_DB_URL')
# directory to store runtime data, write access required
DATA_DIR = os.environ.get('OPENSHIFT_DATA_DIR')
SECRET_KEY = os.environ.get('RTRSS_SECRET_KEY')
FILESTORAGE_URL = os.environ.get('RTRSS_FILESTORAGE_URL')
GCS_PRIVATEKEY_URL = os... | Add DABUG config value to production config | Add DABUG config value to production config
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss | ---
+++
@@ -13,3 +13,4 @@
PORT = int(os.environ.get('OPENSHIFT_PYTHON_PORT'))
IP = os.environ.get('OPENSHIFT_PYTHON_IP')
+DEBUG = False |
f9b87aa94295473fa1a630cb812058554a1cf542 | openacademy/__openerp__.py | openacademy/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Open Academy",
'summary': """Manage trainings""",
'description': """
Open Academy module for managing trainings:
- training courses
- training sessions
- attendees registration
""",
'author': "tebanep",
'website': ... | # -*- coding: utf-8 -*-
{
'name': "Open Academy",
'summary': """Manage trainings""",
'description': """
Open Academy module for managing trainings:
- training courses
- training sessions
- attendees registration
""",
'author': "tebanep",
'website': ... | Fix missing extension in course view file | Fix missing extension in course view file
| Python | mit | tebanep/odoo_training_addons | ---
+++
@@ -27,7 +27,7 @@
'data': [
# 'security/ir.model.access.csv',
#'templates.xml',
- 'view/openacademy_course_view',
+ 'view/openacademy_course_view.xml',
],
# only loaded in demonstration mode
'demo': [ |
f1939ef0eadb164dfbe95bf90b3a4cd8757c8a75 | src/ovirtsdk/infrastructure/common.py | src/ovirtsdk/infrastructure/common.py | #
# Copyright (c) 2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | #
# Copyright (c) 2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | Add empty export method to decorator base | sdk: Add empty export method to decorator base
Decorators for resources and collections extend a common base class, for
example:
class VMSnapshotDisks(Base)
The resource decorators also extend the corresponding parameter class:
class VMSnapshotDisk(params.Disk, Base)
This means that resource decorators impleme... | Python | apache-2.0 | DragonRoman/ovirt-engine-sdk,DragonRoman/ovirt-engine-sdk,DragonRoman/ovirt-engine-sdk | ---
+++
@@ -43,3 +43,9 @@
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
+
+ def export(self, outfile, level, namespace_='', name_='', namespacedef_='', pretty_print=True):
+ # This empty method is necessary in order to avoid exceptions when th... |
18e07d14cf0c0f72e1af50b55bd054d917cb346b | docs/source/parameters.py | docs/source/parameters.py |
def _getvar(var, path, default=None):
with open(path) as f:
for line in f:
if var in line:
g = {}
l = {}
exec line in g, l
return l[var]
return default
def _version():
import os
return _getvar("__version__", os.path.jo... |
def _getvar(var, path, default=None):
with open(path) as f:
for line in f:
if var in line and "=" in line and "__all__" not in line:
g = {}
l = {}
exec line in g, l
return l[var]
return default
def _version():
import os
... | Read doc version number from _metadata.py | Read doc version number from _metadata.py
| Python | apache-2.0 | datawire/bakerstreet,datawire/bakerstreet | ---
+++
@@ -2,7 +2,7 @@
def _getvar(var, path, default=None):
with open(path) as f:
for line in f:
- if var in line:
+ if var in line and "=" in line and "__all__" not in line:
g = {}
l = {}
exec line in g, l
@@ -12,7 +12,7 @@
de... |
b2a56e8f731f3f0d35e8fe4d2379909a3151a667 | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | Move Flickr over to its newly-secured API domain | Move Flickr over to its newly-secured API domain
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -11,7 +11,7 @@
request_token_url = 'http://www.flickr.com/services/oauth/request_token'
authorize_url = 'http://www.flickr.com/services/oauth/authorize'
access_token_url = 'http://www.flickr.com/services/oauth/access_token'
- api_domain = 'secure.flickr.com'
+ api_domain = 'api.flickr.... |
b1b4b0efd8619e1cb00ee317cc4d57e4dce00eec | projects/wsgi.py | projects/wsgi.py | """
WSGI config for projects project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | """
WSGI config for projects project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | Read the script name if the proxy passes it | Read the script name if the proxy passes it
| Python | mit | cmheisel/project-status-dashboard,cmheisel/project-status-dashboard,cmheisel/project-status-dashboard | ---
+++
@@ -13,4 +13,18 @@
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projects.settings")
-application = get_wsgi_application()
+_application = get_wsgi_application()
+
+def application(environ, start_response):
+ script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
+ if script_name:
+ environ[... |
5ab86a2456b54d5af73e15b61de95994b95be8cb | kovot/remote_mod.py | kovot/remote_mod.py | #! /usr/bin/env python
# coding:utf-8
import requests
import logging
from kovot.response import Response
class RemoteCallerMod:
def __init__(self, server, port):
self._root_url = "http://{}:{}".format(server, port)
def generate_responses(self, bot, message):
url = "{}/api/get_responses".for... | #! /usr/bin/env python
# coding:utf-8
import requests
import logging
from kovot.response import Response
class RemoteCallerMod:
def __init__(self, server, port):
self._root_url = "http://{}:{}".format(server, port)
def generate_responses(self, bot, message):
url = "{}/api/generate_responses... | Fix bug; no generate_responses method in RemoteCallerMod | Fix bug; no generate_responses method in RemoteCallerMod
| Python | mit | kenkov/kovot,kenkov/kovot | ---
+++
@@ -12,7 +12,7 @@
self._root_url = "http://{}:{}".format(server, port)
def generate_responses(self, bot, message):
- url = "{}/api/get_responses".format(self._root_url)
+ url = "{}/api/generate_responses".format(self._root_url)
logging.debug("{} requests to {}".format(se... |
d8e5dce3489817a5065c045688b03f9e85c0b9a4 | tests/data_structures/commons/binary_search_tree_unit_test.py | tests/data_structures/commons/binary_search_tree_unit_test.py | import unittest
from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree
class BinarySearchTreeUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
bst = BinarySearchTree.create()
bst.put("one", 1)
bst.put("two", 2)
bst.put("three", 3)
bst.p... | import unittest
from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree
class BinarySearchTreeUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
bst = BinarySearchTree.create()
bst.put("one", 1)
bst.put("two", 2)
bst.put("three", 3)
bst.p... | Increase the unit test coverage for the binary search tree | Increase the unit test coverage for the binary search tree
| Python | bsd-3-clause | chen0040/pyalgs | ---
+++
@@ -11,6 +11,7 @@
bst.put("two", 2)
bst.put("three", 3)
bst.put("six", 6)
+ bst.put("ten", 10)
bst.put("ten", 10)
self.assertEqual(1, bst.get("one"))
@@ -35,5 +36,13 @@
self.assertFalse(bst.contains_key("three"))
self.assertEqual(2, bst.s... |
c8e7400008f19f89519cbfd067c8e82f41fc503a | signac/__init__.py | signac/__init__.py | """
signac aids in the management, access and analysis of large-scale
computational investigations.
The framework provides a simple data model, which helps to organize
data production and post-processing as well as distribution among collaboratos.
"""
# The VERSION string represents the actual (development) version o... | """
signac aids in the management, access and analysis of large-scale
computational investigations.
The framework provides a simple data model, which helps to organize
data production and post-processing as well as distribution among collaboratos.
"""
from . import contrib
from . import db
# The VERSION string repre... | Put contrib and db into global API. | Put contrib and db into global API.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac | ---
+++
@@ -6,6 +6,9 @@
data production and post-processing as well as distribution among collaboratos.
"""
+from . import contrib
+from . import db
+
# The VERSION string represents the actual (development) version of the
# package.
VERSION = '0.1.7'
@@ -13,4 +16,4 @@
# required to be updated and can therefo... |
17198f73f66190711a2df3c7b47008b2a0c50f8e | transaction_downloader/transaction_downloader.py | transaction_downloader/transaction_downloader.py | """Transaction Downloader.
Usage:
transaction-downloader auth --account=<account-name>
transaction-downloader -h | --help
transaction-downloader --version
Options:
-h --help Show this screen.
--version Show version.
--account=<account-name> Account to work with.
"""
from d... | """Transaction Downloader.
Usage:
transaction-downloader auth --account=<account-name>
transaction-downloader -h | --help
transaction-downloader --version
Options:
-h --help Show this screen.
--version Show version.
--account=<account-name> Account to work with.
"""
import... | Add function to read in plaid + account credentials into one structure. | Add function to read in plaid + account credentials into one structure.
| Python | mit | ebridges/plaid2qif,ebridges/plaid2qif,ebridges/plaid2qif | ---
+++
@@ -10,8 +10,21 @@
--version Show version.
--account=<account-name> Account to work with.
"""
+import json
from docopt import docopt
from pkg_resources import require
+
+def read_credentials(account):
+ credentials = {}
+ with open('plaid-credentials.json') as json_data:
+ cre... |
c9372c38fb86494f1b7d0ba32ecfafa073d6da77 | tohu/v6/utils.py | tohu/v6/utils.py | from collections import namedtuple
__all__ = ['identity', 'print_generated_sequence']
def identity(x):
"""
Helper function which returns its argument unchanged.
That is, `identity(x)` returns `x` for any input `x`.
"""
return x
def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=No... | from collections import namedtuple
__all__ = ['identity', 'print_generated_sequence']
def identity(x):
"""
Helper function which returns its argument unchanged.
That is, `identity(x)` returns `x` for any input `x`.
"""
return x
def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=No... | Add helper function to create a list of namedtuples useful for testing and debugging | Add helper function to create a list of namedtuples useful for testing and debugging
| Python | mit | maxalbert/tohu | ---
+++
@@ -22,3 +22,21 @@
elems = [format(next(gen), fmt) for _ in range(num)]
sep_initial = "\n\n" if '\n' in sep else " "
print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
+
+
+def make_dummy_tuples(chars='abcde'):
+ """
+ Helper function to create a list of namedtuples whi... |
d9adcad2b67b7e25e5997f3bfafb0208ab225fa9 | tests/integration/cattletest/core/test_proxy.py | tests/integration/cattletest/core/test_proxy.py | from common_fixtures import * # NOQA
import requests
def test_proxy(client, admin_user_client):
domain = 'releases.rancher.com'
s = admin_user_client.by_id_setting('api.proxy.whitelist')
if domain not in s.value:
s.value += ',{}'.format(domain)
admin_user_client.update(s, value=s.value)... | from common_fixtures import * # NOQA
import requests
def test_proxy(client, admin_user_client):
domain = 'releases.rancher.com'
s = admin_user_client.by_id_setting('api.proxy.whitelist')
if domain not in s.value:
s.value += ',{}'.format(domain)
admin_user_client.update(s, value=s.value)... | Use http for proxy test | Use http for proxy test
| Python | apache-2.0 | cjellick/cattle,vincent99/cattle,vincent99/cattle,cloudnautique/cattle,jimengliu/cattle,wlan0/cattle,rancher/cattle,cjellick/cattle,Cerfoglg/cattle,rancherio/cattle,rancherio/cattle,rancherio/cattle,wlan0/cattle,cloudnautique/cattle,jimengliu/cattle,rancher/cattle,cjellick/cattle,cloudnautique/cattle,Cerfoglg/cattle,Ce... | ---
+++
@@ -20,8 +20,8 @@
base_url = client.schema.types['schema'].links['collection']
base_url = base_url.replace('/schemas', '')
- r = requests.get(base_url + '/proxy/{}/{}'.format(domain,
- 'ui/latest/humans.txt'),
+ r = requests.get(base_url +... |
e39bcde813d35c8079743fbed7e77f2c8e4b4596 | examples/mainwindow.py | examples/mainwindow.py | import sys
from os.path import join, dirname, abspath
from qtpy import uic
from qtpy.QtCore import Slot
from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox
import qtmodern.styles
import qtmodern.windows
_UI = join(dirname(abspath(__file__)), 'mainwindow.ui')
class MainWindow(QMainWindow):
def __... | import sys
from os.path import join, dirname, abspath
from qtpy import uic
from qtpy.QtCore import Slot
from qtpy.QtWidgets import QApplication, QMainWindow, QMessageBox
import qtmodern.styles
import qtmodern.windows
_UI = join(dirname(abspath(__file__)), 'mainwindow.ui')
class MainWindow(QMainWindow):
def __... | Update example to switch between light and dark themes | Update example to switch between light and dark themes | Python | mit | gmarull/qtmodern | ---
+++
@@ -16,7 +16,16 @@
def __init__(self):
QMainWindow.__init__(self)
- uic.loadUi(_UI, self)
+ self.ui = uic.loadUi(_UI, self)
+
+ self.ui.actionLight.triggered.connect(self.lightTheme)
+ self.ui.actionDark.triggered.connect(self.darkTheme)
+
+ def lightThem... |
990d98b323e21d8824b2aead8700f56d66fe6ba3 | plasmapy/utils/__init__.py | plasmapy/utils/__init__.py | from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
... | from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
... | Fix AppVeyor build or break it in a different way | Fix AppVeyor build or break it in a different way
| Python | bsd-3-clause | StanczakDominik/PlasmaPy | ---
+++
@@ -35,4 +35,4 @@
assert_can_handle_nparray,
)
-import roman
+from . import roman |
8da480a92f3e27807275868c27cb41cbde8504d8 | 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... | Set logging level higher so we don't spam tests with debug messages | Set logging level higher so we don't spam tests with debug messages
| Python | bsd-3-clause | INM-6/python-neo,apdavison/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,samuelgarcia/python-neo | ---
+++
@@ -22,11 +22,15 @@
"""
+import logging
import unittest
from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
+
+
+logging.getLogger().setLevel(logging.INFO)
class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase): |
369adf5a3a303612edf9f0169c7b37b7c711a852 | frappe/website/page_renderers/web_page.py | frappe/website/page_renderers/web_page.py | import frappe
class WebPage(object):
def __init__(self, path=None, http_status_code=None):
self.headers = None
self.http_status_code = http_status_code or 200
if not path:
path = frappe.local.request.path
self.path = path.strip('/ ')
self.basepath = None
self.basename = None
self.name = None
self.r... | import frappe
class WebPage(object):
def __init__(self, path=None, http_status_code=None):
self.headers = None
self.http_status_code = http_status_code or 200
if not path:
path = frappe.local.request.path
self.path = path.strip('/ ')
self.basepath = ''
self.basename = ''
self.name = ''
self.route =... | Set default value as empty string | fix: Set default value as empty string
| Python | mit | frappe/frappe,mhbu50/frappe,frappe/frappe,StrellaGroup/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,yashodhank/frappe,StrellaGroup/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/frappe,yashodhank/frappe | ---
+++
@@ -7,10 +7,10 @@
if not path:
path = frappe.local.request.path
self.path = path.strip('/ ')
- self.basepath = None
- self.basename = None
- self.name = None
- self.route = None
+ self.basepath = ''
+ self.basename = ''
+ self.name = ''
+ self.route = ''
self.file_dir = None
def can_r... |
5c6dd036e9fc14d04805a0f31af5a9c28fe51cf5 | tx_salaries/management/commands/generate_transformer_hash.py | tx_salaries/management/commands/generate_transformer_hash.py | from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
ma... | from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
ma... | Add message if transformer_hash already exists | Add message if transformer_hash already exists
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries | ---
+++
@@ -17,4 +17,9 @@
for i in range(1, int(label_row)):
reader.next()
labels = reader.next()
- print transformer.generate_key(labels)
+ transformer_key = transformer.generate_key(labels)
+
+ if transformer_key in transformer.TRANSFORMERS.keys():
+ pr... |
3c742914bd032648665f9069456d78c0a03e5568 | bluebottle/projects/documents.py | bluebottle/projects/documents.py | from django_elasticsearch_dsl import DocType, Index
from bluebottle.projects.models import Project
# The name of your index
project = Index('projects')
# See Elasticsearch Indices API reference for available settings
project.settings(
number_of_shards=1,
number_of_replicas=0
)
@project.doc_type
class Projec... | from django_elasticsearch_dsl import DocType
from bluebottle.projects.models import Project
from bluebottle.utils.documents import MultiTenantIndex
# The name of your index
project = MultiTenantIndex('projects')
# See Elasticsearch Indices API reference for available settings
project.settings(
number_of_shards=1,... | Use a different index for different tenants | Use a different index for different tenants
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -1,8 +1,10 @@
-from django_elasticsearch_dsl import DocType, Index
-from bluebottle.projects.models import Project
+from django_elasticsearch_dsl import DocType
+
+from bluebottle.projects.models import Project
+from bluebottle.utils.documents import MultiTenantIndex
# The name of your index
-project =... |
3f81676d8bc39b459d98a1a91b9ced97be58451d | celestial/exoplanets_importer.py | celestial/exoplanets_importer.py | import requests
import csv
from models import Planet, SolarSystem
from django.core.exceptions import ValidationError
class ExoplanetsImporter:
@staticmethod
def run(filename = None):
if filename!=None:
csv_data = open(filename)
else:
csv_data = requests.get('http://exopl... | import requests
import csv
from models import Planet, SolarSystem
from django.core.exceptions import ValidationError
class ExoplanetsImporter:
@staticmethod
def run(filename = None):
if filename!=None:
csv_data = open(filename)
else:
csv_data = requests.get('http://exopl... | Refactor importer slightly to avoid creation problems | Refactor importer slightly to avoid creation problems
| Python | mit | Floppy/kepler-explorer,Floppy/kepler-explorer,Floppy/kepler-explorer | ---
+++
@@ -23,25 +23,19 @@
got_headers = True
else:
# Find and store system data
- stardata = {
- 'name': row[headers['STAR']],
- 'temperature': row[headers['TEFF']] or None
- }
try:
- ... |
5387fa4c96bb0cdc62e83203065dda84d91c8a57 | project_recalculate/models/resource_calendar.py | project_recalculate/models/resource_calendar.py | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... | Define UTC as tz in get_working_days_of_date method | [FIX] Define UTC as tz in get_working_days_of_date method
| Python | agpl-3.0 | OCA/project,OCA/project | ---
+++
@@ -13,6 +13,8 @@
leaves=None, compute_leaves=False,
resource_id=None, default_interval=None,
context=None):
+ context = context or {}
+ context['tz'] = 'UTC'
if start_dt is None:
... |
354af0bd82da57e718e9612ffb11e3b56d335fbf | projects/search_indexes.py | projects/search_indexes.py | import datetime
import os
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile
from projects import constants
class FileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='project__user')
project = CharFiel... | import datetime
import os
import codecs
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile
from projects import constants
class FileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='project__user')
pro... | Fix unicode fail in search indexing. | Fix unicode fail in search indexing.
| Python | mit | atsuyim/readthedocs.org,tddv/readthedocs.org,singingwolfboy/readthedocs.org,raven47git/readthedocs.org,LukasBoersma/readthedocs.org,stevepiercy/readthedocs.org,johncosta/private-readthedocs.org,michaelmcandrew/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,sid-kap/readthedocs.org,... | ---
+++
@@ -1,5 +1,7 @@
import datetime
import os
+import codecs
+
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile
@@ -23,7 +25,7 @@
def prepare_text(self, obj):
full_path = obj.project.full_html_path
to_read = os.path.join(full_path,... |
a4e402caf7b5a90607b6a206046c96c53a37e860 | slack_client/exceptions.py | slack_client/exceptions.py | class SlackError(Exception):
pass
class SlackNo(SlackError):
def __init__(self, msg_error):
self.msg = msg_error
def __str__(self):
return repr(self.msg)
class SlackTooManyRequests(SlackError):
def __init__(self, time_to_wait):
self.time_to_wait = time_to_wait
def __str__... | class SlackError(Exception):
pass
class SlackNo(SlackError):
pass
class SlackMissingAPI(SlackError):
pass
| Add a custom exception (SlackMissingAPI) | Add a custom exception (SlackMissingAPI)
This exception is raised when a SlackObject is created without
any way to get an API.
Remove custom implementation for exceptions. There is no reason strong
enough for this.
| Python | mit | Shir0kamii/slack-client | ---
+++
@@ -2,16 +2,7 @@
pass
class SlackNo(SlackError):
- def __init__(self, msg_error):
- self.msg = msg_error
+ pass
- def __str__(self):
- return repr(self.msg)
-
-class SlackTooManyRequests(SlackError):
- def __init__(self, time_to_wait):
- self.time_to_wait = time_to_w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.