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 |
|---|---|---|---|---|---|---|---|---|---|---|
c2789dd620a6f6d4c08e4608e94656a0d2b906c7 | parsimonious/utils.py | parsimonious/utils.py | """General tools which don't depend on other parts of Parsimonious"""
import ast
from sys import version_info
from six import python_2_unicode_compatible
class StrAndRepr(object):
"""Mix-in to add a ``__str__`` and ``__repr__`` which return the
UTF-8-encoded value of ``__unicode__``"""
if version_info ... | """General tools which don't depend on other parts of Parsimonious"""
import ast
from six import python_2_unicode_compatible
class StrAndRepr(object):
"""Mix-in to which gives the class the same __repr__ and __str__."""
def __repr__(self):
return self.__str__()
def evaluate_string(string):
""... | Fix a bug in unicode encoding of reprs. | Fix a bug in unicode encoding of reprs.
The previous implementation could lead to double-decoding:
>>> from parsimonious.utils import Token
>>> repr(Token('asdf'))
'<Token "asdf">'
>>> repr(Token(u'💣'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "parsim... | Python | mit | lucaswiman/parsimonious,erikrose/parsimonious | ---
+++
@@ -1,22 +1,15 @@
"""General tools which don't depend on other parts of Parsimonious"""
import ast
-from sys import version_info
from six import python_2_unicode_compatible
class StrAndRepr(object):
- """Mix-in to add a ``__str__`` and ``__repr__`` which return the
- UTF-8-encoded value of `... |
c32165b680356fe9f1e422a1d11127f867065f94 | wiring/categories.py | wiring/categories.py | __all__ = (
'Category',
)
class Category(tuple):
"""
This type acts as tuple with one key difference - two instances of it are
equal only when they have the same type. This allows you to easily mitigate
collisions when using common types (like string) in a dict or as a Wiring
:term:`specificat... | __all__ = (
'Category',
)
class Category(tuple):
"""
This type acts as tuple with one key difference - two instances of it are
equal only when they have the same type. This allows you to easily mitigate
collisions when using common types (like string) in a dict or as a Wiring
:term:`specificat... | Fix error in docstring example. | Fix error in docstring example.
| Python | apache-2.0 | msiedlarek/wiring,msiedlarek/wiring | ---
+++
@@ -22,7 +22,7 @@
graph = Graph()
graph.register_instance(Public('database', 1), 'db://public/1')
- graph.register_instance(Private('database', 1), 'db://private/1')
+ graph.register_instance(Secret('database', 1), 'db://private/1')
assert Public('database', 1) != ... |
72f93daa9d47a37e374605610043a24731aef7a8 | test/test_sampling.py | test/test_sampling.py | # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=5)
de... | # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=10)
d... | Increase re-running limit of test_profiler | Increase re-running limit of test_profiler
| Python | bsd-3-clause | sublee/profiling,JeanPaulShapo/profiling,JeanPaulShapo/profiling,what-studio/profiling,what-studio/profiling,sublee/profiling | ---
+++
@@ -17,7 +17,7 @@
spin(0.5)
-@pytest.mark.flaky(reruns=5)
+@pytest.mark.flaky(reruns=10)
def test_profiler():
profiler = SamplingProfiler(top_frame=sys._getframe(),
sampler=ItimerSampler(0.0001)) |
79ff39c4d6a5ad91a32cfdc7b59a89fa5461d244 | MongoHN/forms.py | MongoHN/forms.py | """ MongoHN.forms - WTForms used by MongoHN """
from MongoHN.models import User
from flask.ext.wtf import Form
from wtforms import SubmitField, TextField, BooleanField, PasswordField
from wtforms.validators import Required, DataRequired
class LoginForm(Form):
username = TextField('Username', validators = [ Requir... | """ MongoHN.forms - WTForms used by MongoHN """
from MongoHN.models import User
from flask.ext.wtf import Form
from wtforms import SubmitField, TextField, BooleanField, PasswordField
from wtforms.validators import Required, DataRequired, ValidationError
class LoginForm(Form):
username = TextField('Username', vali... | Use ValidationError rather than ValueError | Use ValidationError rather than ValueError
| Python | mit | bsandrow/MongoHN,bsandrow/MongoHN | ---
+++
@@ -3,7 +3,7 @@
from MongoHN.models import User
from flask.ext.wtf import Form
from wtforms import SubmitField, TextField, BooleanField, PasswordField
-from wtforms.validators import Required, DataRequired
+from wtforms.validators import Required, DataRequired, ValidationError
class LoginForm(Form):
... |
3e5af3f8ba0eacc8f29e51daec43e395eae27ab8 | partner_email_check/models/res_partner.py | partner_email_check/models/res_partner.py | # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
try:
from validate_email import validate_email
except ImportError:
... | # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
try:
from validate_email import validate_email
except ImportError:
... | Make debugger record a debug message instead of error when importing validate_email in partner_email_check | [FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check
| Python | agpl-3.0 | Vauxoo/partner-contact,Vauxoo/partner-contact | ---
+++
@@ -10,7 +10,7 @@
try:
from validate_email import validate_email
except ImportError:
- _logger.error('Cannot import "validate_email".')
+ _logger.debug('Cannot import "validate_email".')
def validate_email(email):
_logger.warning( |
543c7307f26553d78bf3f18b5f93a2bc23cfb875 | reports/admin.py | reports/admin.py | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
list_filter = ['created_at']
search_fields = ['addressed_to', 'reported_from', 'content', '... | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
list_filter = ['created_at', 'content']
search_fields = ['addressed_to', 'reported_from__us... | Fix some issues, because of models change | Fix some issues, because of models change
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -4,7 +4,7 @@
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
- list_filter = ['created_at']
- search_fields = ['addressed_to', 'reported_from', 'content', 'signed_from']
+ list_filter = ['created_at... |
c553db9e84344897ca995f56c710944da88c0a56 | packages/syft/src/syft/core/node/domain/domain_interface.py | packages/syft/src/syft/core/node/domain/domain_interface.py | # third party
from pydantic import BaseSettings
# relative
from ...adp.adversarial_accountant import AdversarialAccountant
from ..abstract.node_service_interface import NodeServiceInterface
from ..common.node_manager.association_request_manager import AssociationRequestManager
from ..common.node_manager.dataset_manage... | # third party
from pydantic import BaseSettings
# relative
from ...adp.adversarial_accountant import AdversarialAccountant
from ..abstract.node_service_interface import NodeServiceInterface
from ..common.node_manager.association_request_manager import AssociationRequestManager
from ..common.node_manager.dataset_manage... | Remove groups attribute from DomainInterface | Remove groups attribute from DomainInterface
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -6,14 +6,12 @@
from ..abstract.node_service_interface import NodeServiceInterface
from ..common.node_manager.association_request_manager import AssociationRequestManager
from ..common.node_manager.dataset_manager import DatasetManager
-from ..common.node_manager.group_manager import GroupManager
from .... |
d7d1200846a3e19eb9399b3c47ec553e8c118046 | smap-nepse/preprocessing/feat_select.py | smap-nepse/preprocessing/feat_select.py | import pandas as pd
from sklearn.feature_selection import SelectKBest, f_classif
def select_kbest_clf(data_frame, target, k=4):
"""
Selecting K-Best features for classification
:param data_frame: A pandas dataFrame with the training data
:param target: target variable name in DataFrame
:param k: de... | import pandas as pd
from sklearn.feature_selection import SelectKBest, f_classif
def select_kbest_clf(data_frame, target, k=4):
"""
Selecting K-Best features for classification
:param data_frame: A pandas dataFrame with the training data
:param target: target variable name in DataFrame
:param k: de... | Select features using classification model | Select features using classification model
| Python | mit | samshara/Stock-Market-Analysis-and-Prediction | ---
+++
@@ -22,10 +22,11 @@
return feat_scores
df = pd.read_csv("NABIL.csv")
-df.drop(df.columns[[1]], axis=1, inplace=True)
-#print(df.columns)
+df.drop(df.columns[[0,1,9,13]], axis=1, inplace=True)
+df.drop(df.index[:19],inplace=True)
+kbest_feat = select_kbest_clf(df, 'Updown', k=4)
+kbest_feat = kbest_f... |
d50703ee3da5feb264c53d622c039a0bde67d233 | airplay-sniff.py | airplay-sniff.py | #!/usr/bin/env python2
from scapy.all import *
def airplay_callback(pkt):
try:
if pkt['Raw'].load[0:5] == 'SETUP':
# Someone is starting to play! Add them to the list yo
with open('/tmp/playing.txt', 'w') as f:
f.write(pkt[IP].src)
print "Updated playing.txt to " + pkt[IP].src
elif pkt['Raw'].load[0:... | #!/usr/bin/env python2
from scapy.all import *
cur_ip = False
def airplay_callback(pkt):
try:
if pkt[IP].sprintf('%proto%') == 'tcp':
# This could be anything! Parse further
if pkt['Raw'].load[0:5] == 'TEARD':
# Anyone can teardown, only remove the IP if it's the currently playing person
global cur_i... | Change sniffing to be more robust | Change sniffing to be more robust
Known bugs: Will update playing.txt when someone tries to use the speakers
if already in use. Saving grace is it'll change to the right person a second later.
| Python | bsd-2-clause | ss23/airplay-control-intercept,ss23/airplay-control-intercept,ss23/airplay-control-intercept | ---
+++
@@ -1,18 +1,28 @@
#!/usr/bin/env python2
from scapy.all import *
+cur_ip = False
+
def airplay_callback(pkt):
try:
- if pkt['Raw'].load[0:5] == 'SETUP':
- # Someone is starting to play! Add them to the list yo
- with open('/tmp/playing.txt', 'w') as f:
- f.write(pkt[IP].src)
- print "Updated ... |
6b9c9f98ce10db9e9a767c1ae81c0655c9d4d28c | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_lin... | #!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_lin... | Fix typo is -> as | Fix typo is -> as
| Python | mit | henriquebastos/django-test-without-migrations,henriquebastos/django-test-without-migrations | ---
+++
@@ -26,6 +26,6 @@
print("Testing failed: could not import {0}, try pip installing it".format(module))
sys.exit(1)
- # Add pdb flag is this is only supported by nose
+ # Add pdb flag as this is only supported by nose
subprocess.call(['django-admin', 'test', 'tests.myapp.n... |
5d812fbacab2970a1a601f8d801b08305873490d | src/ekklesia_portal/concepts/argument/argument_contracts.py | src/ekklesia_portal/concepts/argument/argument_contracts.py | from colander import Length
from deform import Form
from deform.widget import TextAreaWidget
from ekklesia_portal.helper.contract import Schema, string_property
from ekklesia_portal.helper.translation import _
class ArgumentSchema(Schema):
title = string_property(title=_('title'), validator=Length(min=5, max=80))... | from colander import Length
from deform import Form
from deform.widget import TextAreaWidget, TextInputWidget
from ekklesia_portal.helper.contract import Schema, string_property
from ekklesia_portal.helper.translation import _
TITLE_MAXLENGTH = 80
ABSTRACT_MAXLENGTH = 160
class ArgumentSchema(Schema):
title = s... | Add maxlength to argument form title and abstract | Add maxlength to argument form title and abstract
| Python | agpl-3.0 | dpausp/arguments,dpausp/arguments,dpausp/arguments,dpausp/arguments | ---
+++
@@ -1,18 +1,23 @@
from colander import Length
from deform import Form
-from deform.widget import TextAreaWidget
+from deform.widget import TextAreaWidget, TextInputWidget
from ekklesia_portal.helper.contract import Schema, string_property
from ekklesia_portal.helper.translation import _
+TITLE_MAXLENG... |
8ee00372c7ae005d6060ac2813a13b8db447b292 | stock_request_direction/models/stock_request_order.py | stock_request_direction/models/stock_request_order.py | # Copyright (c) 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
direction = fields.Selection([('outbound', 'Outbound'),
... | # Copyright (c) 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
direction = fields.Selection([('outbound', 'Outbound'),
... | Add warehouse_id to existing onchange. | [IMP] Add warehouse_id to existing onchange.
| Python | agpl-3.0 | Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse | ---
+++
@@ -13,7 +13,7 @@
states={'draft': [('readonly', False)]},
readonly=True)
- @api.onchange('direction')
+ @api.onchange('warehouse_id', 'direction')
def _onchange_location_id(self):
if self.direction == 'outbound':
... |
94a55dfc68fcd2352f867b01fc703a202c87f453 | troposphere/events.py | troposphere/events.py | # Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
class Target(AWSProperty):
props = {
'Arn': (basestring, True),
'Id': (basestring, True),
'Input': (basestring, False),
'InputPath': (... | # Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
class Target(AWSProperty):
props = {
'Arn': (basestring, True),
'Id': (basestring, True),
'Input': (basestring, False),
'InputPath': (... | Remove RoleArn from Events::Rule and add to Target property | Remove RoleArn from Events::Rule and add to Target property
| Python | bsd-2-clause | pas256/troposphere,pas256/troposphere,ikben/troposphere,7digital/troposphere,ikben/troposphere,cloudtools/troposphere,7digital/troposphere,johnctitus/troposphere,johnctitus/troposphere,cloudtools/troposphere | ---
+++
@@ -11,8 +11,8 @@
'Arn': (basestring, True),
'Id': (basestring, True),
'Input': (basestring, False),
- 'InputPath': (basestring, False)
-
+ 'InputPath': (basestring, False),
+ 'RoleArn': (basestring, False),
}
@@ -24,9 +24,7 @@
'Description': (... |
f6df4f359b3d949b3f87a22bda1a78237c396aef | tests/integrations/current/test_read.py | tests/integrations/current/test_read.py | import os
from tests.integrations.base import BaseTest
class TestReadCurrentView(BaseTest):
def test_listdirs(self):
dirs = set(os.listdir("%s/current" % self.mount_path))
assert dirs == set(['testing', 'me'])
def test_read_from_a_file(self):
with open("%s/current/testing" % self.mou... | import os
from tests.integrations.base import BaseTest
class TestReadCurrentView(BaseTest):
def test_listdirs(self):
dirs = set(os.listdir("%s/current" % self.mount_path))
assert dirs == set(['testing', 'me'])
def test_read_from_a_file(self):
with open("%s/current/testing" % self.mou... | Test time related stats from current view | Test time related stats from current view
| Python | apache-2.0 | bussiere/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs,PressLabs/gitfs | ---
+++
@@ -16,11 +16,16 @@
filename = "%s/current/testing" % self.mount_path
stats = os.stat(filename)
- # TODO: get created + modified time
+ filename = "%s/testing_repo/testing" % self.repo_path
+ real_stats = os.stat(filename)
+
attrs = {
'st_uid': os... |
662791d49deb945e911be5e07af2bbb3499a45ca | tests/test_load_cfg.py | tests/test_load_cfg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test load qc configurations (utils.load_cfg)
"""
import pkg_resources
from cotede.utils import load_cfg
CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg')
if f[-5:] == '.json']
def test_inout():
""" load_cfg shouldn't overwrite ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test load qc configurations (utils.load_cfg)
"""
import os.path
import pkg_resources
from cotede.utils import load_cfg, cotede_dir
CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg')
if f[-5:] == '.json']
def test_no_local_duplicate_... | Test to check cfg duplicate in local cfg. | Test to check cfg duplicate in local cfg.
If the factory config fail, the default is to fail safe searching to
a local cfg file, what could hide problems with the builtin cfg file.
| Python | bsd-3-clause | castelao/CoTeDe | ---
+++
@@ -4,13 +4,28 @@
""" Test load qc configurations (utils.load_cfg)
"""
+import os.path
import pkg_resources
-from cotede.utils import load_cfg
+from cotede.utils import load_cfg, cotede_dir
CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg')
if f[-5:] == '.json']
+
+... |
c95d78378c7b3b234439e1d9a9bc41539b9080f5 | preferences/models.py | preferences/models.py | import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = mo... | import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = mo... | Add rep and sen from address fields to Preferences model | Add rep and sen from address fields to Preferences model
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot | ---
+++
@@ -9,6 +9,8 @@
address = models.CharField(max_length=100, blank=True, null=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
+ rep_from_address = models.CharField(max_length=255, blank=True, null=True)
+ sen_from_address = models.CharFiel... |
2bebbbfc12e1013e3c5c0a42329bac520c574b9b | tests/test_settings.py | tests/test_settings.py | import pytest
import npc
import os
from tests.util import fixture_dir
@pytest.fixture
def settings():
return npc.settings.Settings()
def test_creation(settings):
assert settings is not None
def test_override(settings):
override_path = fixture_dir(['settings/settings-vim.json'])
old_editor = settings.... | import pytest
import npc
import os
from tests.util import fixture_dir
def test_creation(prefs):
assert prefs is not None
def test_override(prefs):
override_path = fixture_dir(['settings/settings-vim.json'])
old_editor = prefs.get('editor')
prefs.load_more(override_path)
assert prefs.get('editor') ... | Refactor settings tests to use global fixture | Refactor settings tests to use global fixture
| Python | mit | aurule/npc,aurule/npc | ---
+++
@@ -3,28 +3,24 @@
import os
from tests.util import fixture_dir
-@pytest.fixture
-def settings():
- return npc.settings.Settings()
+def test_creation(prefs):
+ assert prefs is not None
-def test_creation(settings):
- assert settings is not None
+def test_override(prefs):
+ override_path = fix... |
7a8569fb28a1214b4898b113c384eb3967c656ef | tlsenum/parse_hello.py | tlsenum/parse_hello.py | import construct
from tlsenum import hello_constructs
class ClientHello(object):
@property
def protocol_version(self):
return self._protocol_version
@protocol_version.setter
def protocol_version(self, protocol_version):
assert protocol_version in ["3.0", "1.0", "1.1", "1.2"]
... | import time
import os
import construct
from tlsenum import hello_constructs
class ClientHello(object):
@property
def protocol_version(self):
return self._protocol_version
@protocol_version.setter
def protocol_version(self, protocol_version):
assert protocol_version in ["3.0", "1.0"... | Add random and session_id fields. | Add random and session_id fields.
| Python | mit | Ayrx/tlsenum,Ayrx/tlsenum | ---
+++
@@ -1,3 +1,6 @@
+import time
+import os
+
import construct
from tlsenum import hello_constructs
@@ -25,6 +28,20 @@
self._protocol_minor = 3
def build(self):
- return hello_constructs.ProtocolVersion.build(
- construct.Container(major=3, minor=self._protocol_minor)
+ ... |
c64a9a586a5997c3a5a8683913e6a52075618ac8 | virtool/uploads/models.py | virtool/uploads/models.py | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column... | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column... | Fix format issue with `__repr__` | Fix format issue with `__repr__`
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -32,4 +32,4 @@
return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \
f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \
f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}... |
1089413956f3eff9d233d276ebe728e89d814096 | matchers/sifter.py | matchers/sifter.py | from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url... | from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues... | Make the Sifter issue matching more specific. | Make the Sifter issue matching more specific.
Now it matches:
* 3-5 digit numbers
* Preceded by a #, whitespace, or beginning-of-line.
* Followed by a comma, period, question mark, exclamation point,
whitespace, or end-of-line. | Python | bsd-2-clause | honza/nigel | ---
+++
@@ -5,7 +5,7 @@
import json
-NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
+NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)'
API_KEY = os.environ.get('SIFTER')
|
061386e402fb3f1300c0c71be9b07ecc16590ecc | cronjobs/extract_kalliope_originators.py | cronjobs/extract_kalliope_originators.py | #!/usr/bin/python3
import re
import sys
import xml.etree.ElementTree as ET
valid_gnd = re.compile('[0-9\-X]+')
def Main():
if len(sys.argv) != 2:
print("Usage: " + sys.argv[0] + " kalliope_originator_record_file")
exit(1)
root = ET.parse(sys.argv[1]).getroot()
gnds_and_type = {}
for re... | #!/usr/bin/python3
import re
import sys
import xml.etree.ElementTree as ET
valid_gnd = re.compile('[0-9\-X]+')
def Main():
if len(sys.argv) != 2:
print("Usage: " + sys.argv[0] + " kalliope_originator_record_file")
exit(1)
root = ET.parse(sys.argv[1]).getroot()
gnds_and_type = {}
for re... | Make compatible with CentOS 8 | Make compatible with CentOS 8
| Python | agpl-3.0 | ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools | ---
+++
@@ -11,9 +11,9 @@
exit(1)
root = ET.parse(sys.argv[1]).getroot()
gnds_and_type = {}
- for recordData in root.findall('.//{*}recordData'):
- genre = recordData.find('.//{*}genre')
- name = recordData.find('.//{*}name')
+ for recordData in root.findall('.//{http://www.loc.... |
dc8a2d710acbdf79444d05cc266b9f1ef13e838e | pykwalify/__init__.py | pykwalify/__init__.py | # -*- coding: utf-8 -*-
""" pykwalify """
# python stdlib
import logging
import logging.config
import os
__author__ = 'Grokzen <Grokzen@gmail.com>'
__version_info__ = (1, 6, 0)
__version__ = '.'.join(map(str, __version_info__))
log_level_to_string_map = {
5: "DEBUG",
4: "INFO",
3: "WARNING",
2: "ER... | # -*- coding: utf-8 -*-
""" pykwalify """
# python stdlib
import logging
import logging.config
import os
__author__ = 'Grokzen <Grokzen@gmail.com>'
__version_info__ = (1, 6, 0)
__version__ = '.'.join(map(str, __version_info__))
log_level_to_string_map = {
5: "DEBUG",
4: "INFO",
3: "WARNING",
2: "ER... | Change ambigous variable name to be more clear what it is | Change ambigous variable name to be more clear what it is
| Python | mit | grokzen/pykwalify | ---
+++
@@ -26,20 +26,20 @@
"""
Init logging settings with default set to INFO
"""
- l = log_level_to_string_map[min(log_level, 5)]
+ log_level = log_level_to_string_map[min(log_level, 5)]
- msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if l in os.environ else "%(levelname)s - %(... |
197662c014704d6b32597fc7e059800315a57ebd | dashboard_app/tests/models/sw_package.py | dashboard_app/tests/models/sw_package.py | """
Test for the SoftwarePackage model
"""
from django.db import IntegrityError
from django.test import TestCase
from dashboard_app.models import SoftwarePackage
from launch_control.utils.call_helper import ObjectFactoryMixIn
class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn):
class Dummy:
cla... | """
Test for the SoftwarePackage model
"""
from django.db import IntegrityError
from django.test import TestCase
from dashboard_app.models import SoftwarePackage
from launch_control.utils.call_helper import ObjectFactoryMixIn
class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn):
class Dummy:
cla... | Add regression tests for LP:744922 | Add regression tests for LP:744922
| Python | agpl-3.0 | OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server | ---
+++
@@ -22,6 +22,14 @@
self.assertEqual(sw_package.name, dummy.name)
self.assertEqual(sw_package.version, dummy.version)
+ def test_LP744922(self):
+ """
+ Regression test for https://bugs.launchpad.net/launch-control/+bug/744922
+ """
+ sw_package = SoftwarePack... |
d79fde9a1bceea2ea8bc9aa8d14e5ec66a44600d | mesoblog/models.py | mesoblog/models.py | from django.db import models
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
# Article model represents one article in the... | from django.db import models
import random
import re
import string
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
def... | Make sure slugs are unique and not integer only. | Make sure slugs are unique and not integer only.
This fixes issues #1, #2 & #5
| Python | mit | grundleborg/mesosphere | ---
+++
@@ -1,4 +1,8 @@
from django.db import models
+
+import random
+import re
+import string
# Represents a category which articles can be part of
class Category(models.Model):
@@ -7,6 +11,23 @@
def __str__(self):
return self.name+" ["+str(self.id)+"]"
+
+ def save(self):
+ # Make su... |
8492e70a50abe4641d96b7ecdd0e7f583167b755 | lambda_utils/logger.py | lambda_utils/logger.py | # -*- coding: utf-8 -*-
import os
import logging
import threading
class Logger(object):
def configure_logging(self):
log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper())
logging.getLogger().setLevel(log_level)
def __call__(self, function):
self.configure_logging()... | # -*- coding: utf-8 -*-
import os
import logging
import threading
class Logger(object):
def configure_logging(self):
log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper())
logging.getLogger().setLevel(log_level)
def __call__(self, function):
self.configure_logging()
... | Reduce complexity and try/catch block in Logger | Reduce complexity and try/catch block in Logger
| Python | mit | CloudHeads/lambda_utils | ---
+++
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
import os
import logging
import threading
@@ -16,8 +15,8 @@
return self.wrapped_function
def wrapped_function(self, event, context):
+ timeout_notification = self.add_logging_on_timeout(context)
try:
- timeout_notificatio... |
c91e42c32d8314d3d156c577f854fa311c5b1b67 | model_presenter.py | model_presenter.py | import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.... | import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
... | Fix the error that X is required for plotting | Fix the error that X is required for plotting
This enables money-monkey in server environment
| Python | mit | cjluo/money-monkey | ---
+++
@@ -1,3 +1,7 @@
+import matplotlib
+# Do not use X for plotting
+matplotlib.use('Agg')
+
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter |
cc99acd8381522e02703497121201cafd2f820a4 | website/oauth/views.py | website/oauth/views.py | import httplib as http
from flask import redirect
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.oauth.models import ExternalAccount
from website.oauth.utils import get_service
@must_be_logged_in
def oauth_disconnect(external_account_id, auth):
ac... | import httplib as http
from flask import redirect
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.oauth.models import ExternalAccount
from website.oauth.utils import get_service
@must_be_logged_in
def oauth_disconnect(external_account_id, auth):
ac... | Change behavior of removing an external account to persist the object | Change behavior of removing an external account to persist the object
| Python | apache-2.0 | caseyrygt/osf.io,hmoco/osf.io,mluo613/osf.io,baylee-d/osf.io,erinspace/osf.io,amyshi188/osf.io,zkraime/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,mfraezz/osf.io,caneruguz/osf.io,himanshuo/osf.io,revanthkolli/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,HalcyonChimera/osf.io,ZobairAlijan/osf.io,... | ---
+++
@@ -24,9 +24,9 @@
user_settings.revoke_oauth_access(account)
user_settings.save()
- ExternalAccount.remove_one(account)
+ # ExternalAccount.remove_one(account)
# # only after all addons have been dealt with can we remove it from the user
- # user.external_accounts.remove(acco... |
748e4d7e30e71f88095554db3d898c1702d17b50 | wuvt/admin/__init__.py | wuvt/admin/__init__.py | from flask import Blueprint
bp = Blueprint('admin', __name__)
from wuvt.admin import views
| from flask import Blueprint
bp = Blueprint('admin', __name__)
from wuvt.admin import views
from wuvt import app
from wuvt import format_datetime
@app.context_processor
def utility_processor():
def format_price(amount, currency='$'):
return u'{1}{0:.2f}'.format(amount/100, currency)
return dict(format... | Add format_price and format_datetime to jinja context. | Add format_price and format_datetime to jinja context.
| Python | agpl-3.0 | wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site | ---
+++
@@ -3,3 +3,11 @@
bp = Blueprint('admin', __name__)
from wuvt.admin import views
+from wuvt import app
+from wuvt import format_datetime
+
+@app.context_processor
+def utility_processor():
+ def format_price(amount, currency='$'):
+ return u'{1}{0:.2f}'.format(amount/100, currency)
+ return di... |
e08799591061e5b30723758a8c74e6118e9fe342 | bgui/gl_utils.py | bgui/gl_utils.py | # This file handles differences between BGL and PyOpenGL, and provides various
# utility functions for OpenGL
try:
from OpenGL.GL import *
from OpenGL.GLU import *
from bgl import Buffer
USING_BGL = False
except ImportError:
from bgl import *
USING_BGL = True
if USING_BGL:
_glGenTextures = glGenTextures
def g... | # This file handles differences between BGL and PyOpenGL, and provides various
# utility functions for OpenGL
try:
from bgl import *
USING_BGL = True
except ImportError:
from OpenGL.GL import *
from OpenGL.GLU import *
from bgl import Buffer
if USING_BGL:
_glGenTextures = glGenTextures
def glGenTextures(n, tex... | Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL. | Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL.
| Python | mit | Moguri/bgui,Moguri/bgui,Remwrath/bgui,marcioreyes/bgui | ---
+++
@@ -2,13 +2,12 @@
# utility functions for OpenGL
try:
+ from bgl import *
+ USING_BGL = True
+except ImportError:
from OpenGL.GL import *
from OpenGL.GLU import *
from bgl import Buffer
- USING_BGL = False
-except ImportError:
- from bgl import *
- USING_BGL = True
if USING_BGL:
_glGenTextures ... |
0aac6e12a66cec9021a7f5ad0e6beb8821a82d1d | test/lldbplatformutil.py | test/lldbplatformutil.py | """ This module contains functions used by the test cases to hide the
architecture and/or the platform dependent nature of the tests. """
def check_first_register_readable(test_case):
if test_case.getArchitecture() in ['x86_64', 'i386']:
test_case.expect("register read eax", substrs = ['eax = 0x'])
eli... | """ This module contains functions used by the test cases to hide the
architecture and/or the platform dependent nature of the tests. """
def check_first_register_readable(test_case):
if test_case.getArchitecture() in ['amd64', 'x86_64', 'i386']:
test_case.expect("register read eax", substrs = ['eax = 0x']... | Add amd64 architecture alias for x86_64 | test: Add amd64 architecture alias for x86_64
64-bit x86 is called amd64 on FreeBSD.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@234164 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb | ---
+++
@@ -2,7 +2,7 @@
architecture and/or the platform dependent nature of the tests. """
def check_first_register_readable(test_case):
- if test_case.getArchitecture() in ['x86_64', 'i386']:
+ if test_case.getArchitecture() in ['amd64', 'x86_64', 'i386']:
test_case.expect("register read eax", su... |
0a97195dc8bb5f6caf68d84b96631c26e0c8c348 | linguine/untokenize.py | linguine/untokenize.py | import string
def untokenize(tokens):
return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
| import string
def untokenize(tokens):
#Joins all tokens in the list into a single string.
#If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining.
#Then strip the total string so that leading spaces and trailing spaces are removed.
return "".join([" "+i i... | Add comment clarifying how it operates. | Add comment clarifying how it operates. | Python | mit | jmp3833/linguine-python,rigatoni/linguine-python,kmp3325/linguine-python,Pastafarians/linguine-python | ---
+++
@@ -1,3 +1,6 @@
import string
def untokenize(tokens):
+ #Joins all tokens in the list into a single string.
+ #If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining.
+ #Then strip the total string so that leading spaces and trailing spaces are re... |
3bfaff43564c0776912213afefe2e25664f0b1c0 | server/server/urls.py | server/server/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
from accounts import views as views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^django/inventor... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from accounts import views as views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^django/inventor... | Add get and post functionality to the auth user stuff. | Add get and post functionality to the auth user stuff.
| Python | agpl-3.0 | TomDataworks/angular-inventory,TomDataworks/angular-inventory | ---
+++
@@ -14,7 +14,7 @@
url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
url(r'^django/create/inventory/$', 'inventory.views.create'),
- url... |
5ddaf8f653df98752ca67b8bfec9b8adfcf168b1 | pgcli/pgtoolbar.py | pgcli/pgtoolbar.py | from prompt_toolkit.layout.toolbars import Toolbar
from prompt_toolkit.layout.utils import TokenList
from pygments.token import Token
class PGToolbar(Toolbar):
def __init__(self, token=None):
token = token or Token.Toolbar.Status
super(self.__class__, self).__init__(token=token)
def get_tokens... | from prompt_toolkit.layout.toolbars import Toolbar
from prompt_toolkit.layout.utils import TokenList
from pygments.token import Token
class PGToolbar(Toolbar):
def __init__(self, token=None):
token = token or Token.Toolbar.Status
super(self.__class__, self).__init__(token=token)
def get_tokens... | Use the default buffer instead of current_buffer. | Use the default buffer instead of current_buffer.
| Python | bsd-3-clause | nosun/pgcli,TamasNo1/pgcli,d33tah/pgcli,MattOates/pgcli,suzukaze/pgcli,zhiyuanshi/pgcli,dbcli/vcli,bitemyapp/pgcli,janusnic/pgcli,thedrow/pgcli,dbcli/pgcli,bitemyapp/pgcli,n-someya/pgcli,koljonen/pgcli,johshoff/pgcli,d33tah/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,darikg/pgcli,w4ngyi/pgcli,j-bennet/pgcli,MattOates/pgcli,dar... | ---
+++
@@ -10,17 +10,17 @@
def get_tokens(self, cli, width):
result = TokenList()
result.append((self.token, ' '))
- if cli.current_buffer.completer.smart_completion:
+ if cli.buffers['default'].completer.smart_completion:
result.append((self.token.On, '[F2] Smart Co... |
2edd0ee699cfc0ef66d27ccb87ddefad26aa1a77 | Challenges/chall_31.py | Challenges/chall_31.py | #!/usr/local/bin/python3
# Python Challenge - 31
# http://www.pythonchallenge.com/pc/ring/grandpa.html
# http://www.pythonchallenge.com/pc/rock/grandpa.html
# Username: repeat; Password: switch
# Keyword: kohsamui, thailand;
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pi... | #!/usr/local/bin/python3
# Python Challenge - 31
# http://www.pythonchallenge.com/pc/ring/grandpa.html
# http://www.pythonchallenge.com/pc/rock/grandpa.html
# Username: repeat; Password: switch
# Keyword: kohsamui, thailand;
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pi... | Add info for mandelbrot set | Add info for mandelbrot set
| Python | mit | HKuz/PythonChallenge | ---
+++
@@ -18,7 +18,7 @@
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
- Login required: island: country
+ Login required: island: country -> search for Grandpa rock
Next page:
UFO's ?
That was too easy. You are sti... |
c5c458cb367a22205e21087b93ff3cc5ed0a149a | app/soc/models/grading_project_survey.py | app/soc/models/grading_project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Set default taking access for GradingProjectSurvey to org. | Set default taking access for GradingProjectSurvey to org.
This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -32,4 +32,4 @@
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
- self.taking_access = 'mentor'
+ self.taking_access = 'org' |
9e1ea2d7ec5c8e7cfd0c1a15f552b1d5dcdd7546 | helusers/providers/helsinki/provider.py | helusers/providers/helsinki/provider.py | from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class HelsinkiAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('html_url')
def... | from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class HelsinkiAccount(ProviderAccount):
def get_profile_url(... | Add account adapter for allauth | Add account adapter for allauth
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | ---
+++
@@ -1,6 +1,7 @@
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
+from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class HelsinkiAccount(ProviderA... |
df56478315c7b58526fbecf3fdfc4df5326d5ba0 | custom_fixers/fix_alt_unicode.py | custom_fixers/fix_alt_unicode.py | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, BlankLine
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = """
func=funcdef< 'def' name='__unicode__'
... | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = "'__unicode__'"
def transform(self, node, results):
new = node.clone()
new.value = '__str__... | Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__. | Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
| Python | mit | andreas-h/pybtex,andreas-h/pybtex,chbrown/pybtex,chbrown/pybtex | ---
+++
@@ -3,15 +3,12 @@
from lib2to3 import fixer_base
-from lib2to3.fixer_util import Name, BlankLine
class FixAltUnicode(fixer_base.BaseFix):
- PATTERN = """
- func=funcdef< 'def' name='__unicode__'
- parameters< '(' NAME ')' > any+ >
- """
+ PATTERN = "'__unicode__'"
... |
cb83a61df5ed82dd9af7ebd3c01d00a3d88e3491 | infosystem/subsystem/domain/resource.py | infosystem/subsystem/domain/resource.py | from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['active', 'name', 'parent_id']
attributes += entity.Entity.attributes
active = db.Column(db.Boolean(), nullable=False)
name = db.Column(db.String(60), nullable=False... | from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
name = db.Column(db.String(60), nullable=False, unique=True)
parent_id = db.Column(
db.CHAR(32), ... | Remove attribute from domain and get from entity | Remove attribute from domain and get from entity
| Python | apache-2.0 | samueldmq/infosystem | ---
+++
@@ -4,10 +4,9 @@
class Domain(entity.Entity, db.Model):
- attributes = ['active', 'name', 'parent_id']
+ attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
- active = db.Column(db.Boolean(), nullable=False)
name = db.Column(db.String(60), nullable=False, unique... |
7ac48c9a474f5a0edd10121f58442326d6e8d75c | backend/geonature/core/command/__init__.py | backend/geonature/core/command/__init__.py | import os
import sys
from geonature.core.command.main import main
import geonature.core.command.create_gn_module
# Load modules commands
from geonature.utils.env import ROOT_DIR
plugin_folder = os.path.join(str(ROOT_DIR), 'external_modules')
sys.path.insert(0, os.path.join(plugin_folder))
for dirname in os.listdir(... | import os
import sys
from pathlib import Path
from geonature.core.command.main import main
import geonature.core.command.create_gn_module
# Load modules commands
from geonature.utils.env import ROOT_DIR
def import_cmd(dirname):
try:
print("Import module {}".format(dirname))
module_cms = __impo... | TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module | TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module
| Python | bsd-2-clause | PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature | ---
+++
@@ -1,5 +1,6 @@
import os
import sys
+from pathlib import Path
from geonature.core.command.main import main
import geonature.core.command.create_gn_module
@@ -7,6 +8,26 @@
# Load modules commands
from geonature.utils.env import ROOT_DIR
+
+
+def import_cmd(dirname):
+ try:
+ print("Import ... |
e1819c59cc5debde7da26a76fb9d2589b2ad6879 | Rynda/settings/test.py | Rynda/settings/test.py | # coding: utf-8
from .local import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_ROOT = os.path.join(S... | # coding: utf-8
from .local import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_ROOT = os.path.join(S... | Test database creator using syncdb instead of South | Test database creator using syncdb instead of South
| Python | mit | sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda | ---
+++
@@ -14,3 +14,4 @@
}
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_ROOT = os.path.join(SITE_ROOT, 'test')
+SOUTH_TESTS_MIGRATE = False |
5a8275a498a84d2110f58c1dbde4e67ddfa3748c | scripts/assemble_quests.py | scripts/assemble_quests.py | """
Assembles the zone configurations for each quest
into one file. Every quest that is in quest_dir
and every zone that is in each quest will be
included.
Example output:
{
quest1: [
{
zone: A,
...
},
{
zone: B,
... | """
Assembles the zone configurations for each quest
into one file. Every quest that is in quest_dir
and every zone that is in each quest will be
included.
Example output:
{
quest1: [
{
zone: A,
...
},
{
zone: B,
... | Fix build issue on OSX. | Fix build issue on OSX.
Our script assumes the quest directory only has subdirectories of quests
but OSX adds DS_STORE files to each directory and these were being
picked up and causing the assemble quests script to fail.
| Python | apache-2.0 | lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-water... | ---
+++
@@ -43,9 +43,10 @@
}
for zone in sorted(os.listdir(questPath)):
- with open(os.path.join(questPath, zone, 'zone.json')) as f:
- data = json.load(f)
- output[quest]['zones'].append(data)
+ if os.path.isdir(os.path.join(questPath, zone)):
+... |
f4b50b12ae8ad4da6e04ddc186c077c31af00611 | SimpleHTTP404Server.py | SimpleHTTP404Server.py | import os
import SimpleHTTPServer
class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Overrides the default request handler to handle GitHub custom 404 pages.
(Pretty much a 404.html page in your root.)
See https://help.github.com/articles/custom-404-pages
This currently only wor... | import os
import SimpleHTTPServer
class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Overrides the default request handler to handle GitHub custom 404 pages.
(Pretty much a 404.html page in your root.)
See https://help.github.com/articles/custom-404-pages
This currently only wor... | Remove some print lines from the fake server. | Remove some print lines from the fake server.
| Python | mit | clokep/SimpleHTTP404Server,clokep/SimpleHTTP404Server | ---
+++
@@ -15,8 +15,7 @@
"""
def do_GET(self):
path = self.translate_path(self.path)
- print(self.path)
- print(path)
+
# If the path doesn't exist, fake it to be the 404 page.
if not os.path.exists(path):
self.path = '404.html'
@@ -24,8 +23,5 @@
... |
6d924b21c40b5881d0b2c56b5550bf93f073e049 | txircd/config.py | txircd/config.py | import yaml
_defaults = {
"bind_client": [ "tcp:6667:interface={::}", "ssl:6697:interface={::}" ],
"bind_server": []
}
class Config(object):
def __init__(self, configFileName):
self._configData = {}
self._readConfig(configFileName)
for key, val in _defaults:
if key not ... | import yaml
_defaults = {
"bind_client": [ "tcp:6667:interface={::}" ],
"bind_server": []
}
class Config(object):
def __init__(self, configFileName):
self._configData = {}
self._readConfig(configFileName)
for key, val in _defaults:
if key not in self._configData:
... | Remove the SSL default since it requires certs | Remove the SSL default since it requires certs
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | ---
+++
@@ -1,7 +1,7 @@
import yaml
_defaults = {
- "bind_client": [ "tcp:6667:interface={::}", "ssl:6697:interface={::}" ],
+ "bind_client": [ "tcp:6667:interface={::}" ],
"bind_server": []
}
|
139eac65c71c729e7500dfe894dc9686bd384ab4 | UConnRCMPy/constants.py | UConnRCMPy/constants.py | """
Constants used in UConnRCMPy.
"""
import cantera
one_atm_in_torr = 760.0
"""Conversion between atmosphere and Torr."""
one_atm_in_bar = 1.01325
"""Conversion between atmosphere and bar."""
one_bar_in_pa = 1E5
"""Conversion between bar and Pascal."""
cantera_version = None
"""Installed version of Cantera software."... | """
Constants used in UConnRCMPy.
"""
import cantera
one_atm_in_torr = 760.0
"""Conversion between atmosphere and Torr."""
one_atm_in_bar = 1.01325
"""Conversion between atmosphere and bar."""
one_bar_in_pa = 1E5
"""Conversion between bar and Pascal."""
cantera_version = None
"""Installed version of Cantera software."... | Fix map object not subscriptable in cantera_version | Fix map object not subscriptable in cantera_version
| Python | bsd-3-clause | bryanwweber/UConnRCMPy | ---
+++
@@ -13,7 +13,7 @@
"""Installed version of Cantera software."""
try:
- cantera_version = map(int, cantera.__version__.split('.'))
+ cantera_version = list(map(int, cantera.__version__.split('.')))
except ValueError:
- cantera_version = map(int, cantera.__version__.split('.')[0:2])
+ cantera_ve... |
acbace21652d45a5fb17bbb487692ab6057313df | api/parsers/datanasa.py | api/parsers/datanasa.py | import json
from flaskext.mongoalchemy import MongoAlchemy
import requests
from api import app
from api import db
ENDPOINT = 'http://data.nasa.gov/api/'
class Dataset(db.Document):
""" Represents a dataset,
we could split this out to hold all the actual data,
slug, url, title, etc
"""
remote_id ... | import json
from flaskext.mongoalchemy import BaseQuery
import requests
from api import app
from api import db
ENDPOINT = 'http://data.nasa.gov/api/'
class DatasetQuery(BaseQuery):
def get_by_remote_id(self, pk):
return self.filter(self.type.remote_id==pk)
class Dataset(db.Document):
""" Represen... | Define a query on Dataset to retrive them by remote id | Define a query on Dataset to retrive them by remote id
| Python | mit | oxford-space-apps/open-data-api | ---
+++
@@ -1,5 +1,5 @@
import json
-from flaskext.mongoalchemy import MongoAlchemy
+from flaskext.mongoalchemy import BaseQuery
import requests
from api import app
@@ -7,6 +7,12 @@
ENDPOINT = 'http://data.nasa.gov/api/'
+
+
+class DatasetQuery(BaseQuery):
+ def get_by_remote_id(self, pk):
+ retur... |
044f1169b518628c8409a38845ffa5c18b7cb748 | packs/clicrud/actions/config_command.py | packs/clicrud/actions/config_command.py | # encoding: utf-8
from st2actions.runners.pythonrunner import Action
from clicrud.device.generic import generic
import sys
class ConfigCommand(Action):
def run(self, host, command, save):
self.method = self.config['method']
self.username = self.config['username']
self.password = self.conf... | # encoding: utf-8
from st2actions.runners.pythonrunner import Action
from clicrud.device.generic import generic
import sys
class ConfigCommand(Action):
def run(self, host, command, save):
self.method = self.config['method']
self.username = self.config['username']
self.password = self.conf... | Use finally so connection is also closed on exception. | Use finally so connection is also closed on exception.
| Python | apache-2.0 | StackStorm/st2contrib,StackStorm/st2contrib,StackStorm/st2contrib | ---
+++
@@ -24,8 +24,9 @@
for cmd in command:
utf8_commands.append(cmd.encode('utf-8', 'ignore'))
+ transport = None
+
try:
-
transport = generic(host=utf8_host, username=self.username,
enable=self.enable, method=self.method,
... |
43291c827d2d7b0a350971b2efa26ca9e1c1e593 | src/sentry/api/endpoints/system_health.py | src/sentry/api/endpoints/system_health.py | from __future__ import absolute_import
import itertools
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
permission_classes = (SuperuserPermission,)
... | from __future__ import absolute_import
import itertools
from hashlib import md5
from rest_framework.response import Response
from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission
class SystemHealthEndpoint(Endpoint):
permission_classes = (S... | Add `id` to `SystemHealthEndpoint` response. | Add `id` to `SystemHealthEndpoint` response.
| Python | bsd-3-clause | gencer/sentry,zenefits/sentry,looker/sentry,alexm92/sentry,JackDanger/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,ifduyue/sentry,beeftornado/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,BuildingLink/sentry,mvaled/sentry,BuildingLink/sentry,mvaled/sentry,mvaled/sentry,mvaled/sentry,JamesMura/sentry,beef... | ---
+++
@@ -1,6 +1,7 @@
from __future__ import absolute_import
import itertools
+from hashlib import md5
from rest_framework.response import Response
@@ -17,6 +18,7 @@
return Response({
'problems': map(
lambda problem: {
+ 'id': md5(problem.message).h... |
8a16f7d51d34573d41846da25664b084ff6eb071 | publication_figures.py | publication_figures.py | """
Create nice looking publication figures
"""
import numpy as np
import networkx as nx
import seaborn as sns
import matplotlib as mpl
import matplotlib.pylab as plt
from tqdm import tqdm
from main import analyze_system
from setup import generate_basic_system
from nm_data_generator import add_node_to_system
def... | Create some more nice figures | Create some more nice figures
| Python | mit | kpj/SDEMotif,kpj/SDEMotif | ---
+++
@@ -0,0 +1,93 @@
+"""
+ Create nice looking publication figures
+"""
+
+import numpy as np
+import networkx as nx
+
+import seaborn as sns
+import matplotlib as mpl
+import matplotlib.pylab as plt
+
+from tqdm import tqdm
+
+from main import analyze_system
+from setup import generate_basic_system
+from nm_dat... | |
f617c1ce192739594c161f717d5d04cc17ede22e | distarray/local/tests/paralleltest_io.py | distarray/local/tests/paralleltest_io.py | import tempfile
import h5py
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
from distarray.testing import comm_null_passes, MpiTestCase
class TestFlatFileIO(MpiTestCase):
@comm_null_passes
def test_flat_file_read_write(self):
... | import tempfile
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
from distarray.testing import comm_null_passes, MpiTestCase
class TestFlatFileIO(MpiTestCase):
@comm_null_passes
def test_flat_file_read_write(self):
larr0 = Loc... | Move h5py import into HDF test. | Move h5py import into HDF test. | Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray | ---
+++
@@ -1,5 +1,4 @@
import tempfile
-import h5py
from numpy.testing import assert_allclose
from os import path
from distarray.local import LocalArray, save, load, save_hdf5
@@ -24,6 +23,8 @@
@comm_null_passes
def test_hdf5_file_write(self):
+ import h5py
+
dataset = "data"
... |
b80eae0285af97d8fe954a5df667e03b004efa12 | instrument-classification/leaderboard.py | instrument-classification/leaderboard.py | import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns:
df['auc'] = np.nan
df = df[['model_id'... | import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns:
df['auc'] = np.nan
df = df[['model_id'... | Fix ordering of latest models on the leader board. | Fix ordering of latest models on the leader board.
| Python | mit | bzamecnik/ml-playground,bzamecnik/ml-playground,bzamecnik/ml,bzamecnik/ml,bzamecnik/ml | ---
+++
@@ -12,7 +12,7 @@
df = df[['model_id', 'split', 'loss', 'error', 'auc']]
return df
-files = glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv')
+files = sorted(glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv'))
df = pd.concat([load_df(... |
80d0ba5716d4b6cdef1c5d64a670abfa59f81557 | bin/verify_cached_graphs.py | bin/verify_cached_graphs.py | #!/usr/bin/env python
import sys
from pprint import pprint as pp
from cc.payment import flow
def verify():
for ignore_balances in (True, False):
cached = flow.get_cached_graph(ignore_balances)
if not cached:
continue
graph = flow.build_graph(ignore_balances)
diff = com... | #!/usr/bin/env python
import sys
from pprint import pprint as pp
from cc.payment import flow
def verify():
for ignore_balances in (True, False):
graph = flow.build_graph(ignore_balances)
cached = flow.get_cached_graph(ignore_balances)
if not cached:
flow.set_cached_graph(graph... | Load cached graph in verify cached graphs tool if not already present. | Load cached graph in verify cached graphs tool if not already present.
| Python | agpl-3.0 | rfugger/villagescc,rfugger/villagescc,rfugger/villagescc,rfugger/villagescc | ---
+++
@@ -7,10 +7,11 @@
def verify():
for ignore_balances in (True, False):
+ graph = flow.build_graph(ignore_balances)
cached = flow.get_cached_graph(ignore_balances)
if not cached:
+ flow.set_cached_graph(graph, ignore_balances)
continue
- graph = fl... |
cca17afe5ed3937713e86f9a8d9c3be0dcdf60b0 | aiosparkapi/__init__.py | aiosparkapi/__init__.py | import aiosparkapi.requests
from .api.messages import Messages
from .api.webhooks import Webhooks
from .api.people import People
import aiohttp
class AioSparkApi:
def __init__(self, *, access_token):
self._client = aiohttp.ClientSession('https://api.ciscospark.com/v1/')
self._requests = aiospark... | Add a AioSparkApi class to set up the whole thing | Add a AioSparkApi class to set up the whole thing
| Python | mit | martiert/aiosparkapi | ---
+++
@@ -0,0 +1,22 @@
+import aiosparkapi.requests
+from .api.messages import Messages
+from .api.webhooks import Webhooks
+from .api.people import People
+
+import aiohttp
+
+
+class AioSparkApi:
+
+ def __init__(self, *, access_token):
+ self._client = aiohttp.ClientSession('https://api.ciscospark.com/... | |
75cec3cef9fb73ec3a4068cc35dc33f3f492275b | bin/public/extract_challenge_uuids.py | bin/public/extract_challenge_uuids.py | # Exports all data for the particular user for the particular day
# Used for debugging issues with trip and section generation
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
import gzip
import json
import emission.core.wrapper.user as ecwu
# Input data using one email per line (easy to copy/paste... | # Exports all data for the particular user for the particular day
# Used for debugging issues with trip and section generation
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
import gzip
import json
import emission.core.wrapper.user as ecwu
# Input data using one email per line (easy to copy/paste... | Support use case where the user sent consent from the wrong email | Support use case where the user sent consent from the wrong email
| Python | bsd-3-clause | sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server | ---
+++
@@ -19,6 +19,15 @@
uuid_filename = sys.argv[2]
emails = open(user_email_filename).readlines()
- uuids = [ecwu.User.fromEmail(e.strip()).uuid for e in emails]
+ uuids = []
+ for e in emails:
+ user = ecwu.User.fromEmail(e.strip())
+ if user is None... |
610eeb064ba95e79617650d939ae5e9110b6ab89 | restlib2/structures.py | restlib2/structures.py | import re
class AttrDict(object):
"A case-insensitive attribute accessible dict-like object"
def __init__(self, name, *args, **kwargs):
for key, value in dict(*args, **kwargs).iteritems():
if not isinstance(key, basestring) or not key:
raise TypeError('attribute names must ... | import re
class AttrDict(object):
"A case-insensitive attribute accessible dict-like object"
def __init__(self, name, *args, **kwargs):
self.name = name
for key, value in dict(*args, **kwargs).iteritems():
if not isinstance(key, basestring) or not key:
raise TypeEr... | Add missing assignment of name in constructor | Add missing assignment of name in constructor | Python | bsd-2-clause | bruth/restlib2 | ---
+++
@@ -4,6 +4,8 @@
class AttrDict(object):
"A case-insensitive attribute accessible dict-like object"
def __init__(self, name, *args, **kwargs):
+ self.name = name
+
for key, value in dict(*args, **kwargs).iteritems():
if not isinstance(key, basestring) or not key:
... |
373d5d55279695ead6b83fb99824a3249416697f | auditlog/__openerp__.py | auditlog/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | Add OCA as author of OCA addons | Add OCA as author of OCA addons
In order to get visibility on https://www.odoo.com/apps the OCA board has
decided to add the OCA as author of all the addons maintained as part of the
association.
| Python | agpl-3.0 | YannickB/server-tools,YannickB/server-tools,OCA/server-tools,YannickB/server-tools,OCA/server-tools,OCA/server-tools | ---
+++
@@ -22,7 +22,7 @@
{
'name': "Audit Log",
'version': "1.0",
- 'author': "ABF OSIELL",
+ 'author': "ABF OSIELL,Odoo Community Association (OCA)",
'website': "http://www.osiell.com",
'category': "Tools",
'depends': [ |
3535ea637112ef21fefd8df811721d271c109581 | salt/runners/manage.py | salt/runners/manage.py | '''
General management functions for salt, tools like seeing what hosts are up
and what hosts are down
'''
# Import salt modules
import salt.client
import salt.cli.key
def down():
'''
Print a list of all the down or unresponsive salt minions
'''
client = salt.client.LocalClient(__opts__['config'])
... | '''
General management functions for salt, tools like seeing what hosts are up
and what hosts are down
'''
# Import salt modules
import salt.client
import salt.cli.key
def down():
'''
Print a list of all the down or unresponsive salt minions
'''
client = salt.client.LocalClient(__opts__['config'])
... | Add an "up" to list all "up" minions | Add an "up" to list all "up" minions
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -19,3 +19,12 @@
keys.remove(minion)
for minion in sorted(keys):
print minion
+
+def up():
+ '''
+ Print a list of all of the minions that are up
+ '''
+ client = salt.client.LocalClient(__opts__['config'])
+ minions = client.cmd('*', 'test.ping', timeout=1)
+ for mi... |
c34960e07ccce749a7fb5e53ff7593b87fe453d7 | sazabi/plugins/joke.py | sazabi/plugins/joke.py | import requests
from random import choice
from sazabi.types import SazabiBotPlugin
class Joke(SazabiBotPlugin):
async def parse(self, client, message, *args, **kwargs):
if message.content == "~joke":
response = requests.get('https://www.reddit.com/r/oneliners/new.json').json()
if ... | import requests
from random import choice
from sazabi.types import SazabiBotPlugin
class Joke(SazabiBotPlugin):
async def parse(self, client, message, *args, **kwargs):
if message.content == "~joke":
response = requests.get(
'https://www.reddit.com/r/oneliners/new.json',
... | Add user agent to reddit request | Add user agent to reddit request
| Python | mit | frankzhao/sazabi,frankzhao/sazabi | ---
+++
@@ -7,7 +7,9 @@
class Joke(SazabiBotPlugin):
async def parse(self, client, message, *args, **kwargs):
if message.content == "~joke":
- response = requests.get('https://www.reddit.com/r/oneliners/new.json').json()
+ response = requests.get(
+ 'https://www.red... |
dd1e6cdf2f6f040f532863549df606083f3f4bf2 | utils/gyb_syntax_support/protocolsMap.py | utils/gyb_syntax_support/protocolsMap.py | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAs... | SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = {
'ExpressibleByConditionElement': [
'ExpressibleByConditionElementList'
],
'ExpressibleByDeclBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleByMemberDeclListItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleBy... | Replace ExpressibleAs protocols by ExpressibleBy protocols | [SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols
The protocols in the standard library are called `ExpressibleBy*` and SwiftSyntax should follow the same naming convention.
| Python | apache-2.0 | JGiola/swift,apple/swift,gregomni/swift,atrick/swift,roambotics/swift,benlangmuir/swift,atrick/swift,roambotics/swift,ahoppen/swift,glessard/swift,apple/swift,ahoppen/swift,gregomni/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,apple/swift,roambotics/swift,glessard/swift,benlangmuir/swift,gregomni/... | ---
+++
@@ -1,18 +1,18 @@
-SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
- 'ExpressibleAsConditionElement': [
- 'ExpressibleAsConditionElementList'
+SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = {
+ 'ExpressibleByConditionElement': [
+ 'ExpressibleByConditionElementList'
],
- 'Expressi... |
3642fefbb1d4b5f2aeead54135ac37f0a5b635cd | tests/general.py | tests/general.py | import unittest
from app import create_app, configure_settings, db
class AppTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
configure_settings(self.app)
def tearDo... | import unittest
from app import create_app, db
class AppTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
# Temporary. Will be removed once default settings has been set... | Add placeholder settings to unit tests | Add placeholder settings to unit tests
| Python | mit | Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger | ---
+++
@@ -1,6 +1,6 @@
import unittest
-from app import create_app, configure_settings, db
+from app import create_app, db
class AppTestCase(unittest.TestCase):
@@ -9,7 +9,10 @@
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
- configure_settings(se... |
4377cb01932fb6cb9d324f98c55b4467e803add5 | tests/test_go.py | tests/test_go.py | # -*- coding: utf-8 -*-
import mock
import completor
from completor.compat import to_unicode
from completers.go import Go # noqa
def test_format_cmd(vim_mod):
vim_mod.funcs['line2byte'] = mock.Mock(return_value=20)
vim_mod.funcs['completor#utils#tempname'] = mock.Mock(
return_value=b'/tmp/vJBio2A/2.... | # -*- coding: utf-8 -*-
import mock
import completor
from completor.compat import to_unicode
from completers.go import Go # noqa
def test_format_cmd(vim_mod):
vim_mod.funcs['line2byte'] = mock.Mock(return_value=20)
vim_mod.funcs['completor#utils#tempname'] = mock.Mock(
return_value=b'/tmp/vJBio2A/2.... | Fix test for go completor. | Fix test for go completor. | Python | mit | maralla/completor.vim,maralla/completor.vim | ---
+++
@@ -10,12 +10,14 @@
vim_mod.funcs['line2byte'] = mock.Mock(return_value=20)
vim_mod.funcs['completor#utils#tempname'] = mock.Mock(
return_value=b'/tmp/vJBio2A/2.vim')
+ vim_mod.current.buffer.name = '/home/vagrant/bench.vim'
vim_mod.current.window.cursor = (1, 5)
go = complet... |
c5fe052756f9fe2bfe091d24fabcb6be02bda763 | server/core/management/commands/poll_urls.py | server/core/management/commands/poll_urls.py | import datetime
import multiprocessing
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from core.models import WebPage, PageScrapeResult
from core.views import scrape_url
class Command(BaseCommand):
help = "Poll all the urls and scrape the results"
can_impo... | import datetime
import multiprocessing
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from core.models import WebPage, PageScrapeResult
from core.views import scrape_url
class Command(BaseCommand):
help = "Poll all the urls and scrape the results"
can_impo... | Use the cpu count for the process pool size. | Use the cpu count for the process pool size.
| Python | mit | theju/atifier,theju/atifier | ---
+++
@@ -13,7 +13,7 @@
can_import_settings = True
def handle(self, *args, **options):
- pool = multiprocessing.Pool(10)
+ pool = multiprocessing.Pool(multiprocessing.cpu_count() + 2)
curr_min = datetime.datetime.now().minute
for page in WebPage.objects.all():
... |
bd170dc4ce58c78213ea5dc7c9d779ad914762bb | social_core/tests/backends/test_udata.py | social_core/tests/backends/test_udata.py | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps... | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps... | Fix tests for udata/datagouvfr backend | Fix tests for udata/datagouvfr backend
| Python | bsd-3-clause | python-social-auth/social-core,python-social-auth/social-core | ---
+++
@@ -11,7 +11,9 @@
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
- 'token_type': 'bearer'
+ 'token_type': 'bearer',
+ 'first_name': 'foobar',
+ 'email': 'foobar@example.com'
})
request_token_body = urlencode({
... |
83020d996733b5376cfa5814ca81c8f823029346 | tests/run/pyclass_annotations_pep526.py | tests/run/pyclass_annotations_pep526.py | # cython: language_level=3
# mode: run
# tag: pure3.7, pep526, pep484
from __future__ import annotations
try:
from typing import ClassVar
except ImportError: # Py<=3.5
ClassVar = {int: int}
class PyAnnotatedClass:
"""
>>> PyAnnotatedClass.__annotations__["CLASS_VAR"]
'ClassVar[int]'
>>> PyA... | # cython: language_level=3
# mode: run
# tag: pure3.7, pep526, pep484
from __future__ import annotations
import sys
try:
from typing import ClassVar
except ImportError: # Py<=3.5
ClassVar = {int: int}
class PyAnnotatedClass:
"""
>>> PyAnnotatedClass.__annotations__["CLASS_VAR"]
'ClassVar[int]'... | Repair a Python compatibility test in Py3.10. | Repair a Python compatibility test in Py3.10.
| Python | apache-2.0 | scoder/cython,scoder/cython,scoder/cython,da-woods/cython,cython/cython,cython/cython,da-woods/cython,cython/cython,da-woods/cython,da-woods/cython,scoder/cython,cython/cython | ---
+++
@@ -3,6 +3,8 @@
# tag: pure3.7, pep526, pep484
from __future__ import annotations
+
+import sys
try:
from typing import ClassVar
@@ -40,8 +42,13 @@
class PyVanillaClass:
"""
- >>> PyVanillaClass.__annotations__
- Traceback (most recent call last):
- ...
- AttributeError: type... |
1517bb31a8ec0d5df96e2693977081b3d1a64f69 | tests/integration/minion/test_timeout.py | tests/integration/minion/test_timeout.py | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
... | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | Update old utils paths to use new paths | Update old utils paths to use new paths
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -8,7 +8,7 @@
import os
import sys
-import salt.utils
+import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
@@ -25,7 +25,7 @@
'''
# Launch the command
sleep_length = 30
- if salt.utils.is_windows():
+ if salt.utils.pl... |
29613035bb8af7dedec7383a62a5e488547e4795 | transmutagen/tests/test_coefficients.py | transmutagen/tests/test_coefficients.py | import pytest
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
TOTAL_DEGREES = 2
from .crv_coeffs import coeffs as correct_coeffs
# TODO: Should we use the CRAM cache here?
from ..cram import CRAM_exp, CRAM_coeffs
@slow
def test_coefficients():
... | import pytest
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
TOTAL_DEGREES = 2
from .crv_coeffs import coeffs as correct_coeffs
# TODO: Should we use the CRAM cache here?
from ..cram import CRAM_exp, CRAM_coeffs
@slow
@pytest.mark.parametrize('de... | Use pytest parametrize for the coefficient tests | Use pytest parametrize for the coefficient tests
| Python | bsd-3-clause | ergs/transmutagen,ergs/transmutagen | ---
+++
@@ -12,10 +12,10 @@
from ..cram import CRAM_exp, CRAM_coeffs
@slow
-def test_coefficients():
+@pytest.mark.parametrize('degree', range(1, TOTAL_DEGREES+1))
+def test_coefficients(degree):
generated_coeffs = {}
- for degree in range(1, TOTAL_DEGREES+1):
- expr = CRAM_exp(degree, 30)
- ... |
4ffd42f132769b23ee93c8a5c3416877c772d47e | doc_builder/backends/pdf.py | doc_builder/backends/pdf.py | import re
import os
from django.conf import settings
from doc_builder.base import BaseBuilder
from projects.utils import run
latex_re = re.compile('the LaTeX files are in (.*)\.')
pdf_re = re.compile('Output written on (.*?)')
class Builder(BaseBuilder):
def build(self, project):
self._cd_makefile(proj... | import re
import os
from django.conf import settings
from doc_builder.base import BaseBuilder
from projects.utils import run
latex_re = re.compile('the LaTeX files are in (.*)\.')
pdf_re = re.compile('Output written on (.*?)')
class Builder(BaseBuilder):
def build(self, project):
self._cd_makefile(proj... | Move instead of symlink because we blow that dir away. | Move instead of symlink because we blow that dir away. | Python | mit | wanghaven/readthedocs.org,LukasBoersma/readthedocs.org,clarkperkins/readthedocs.org,CedarLogic/readthedocs.org,nyergler/pythonslides,d0ugal/readthedocs.org,sunnyzwh/readthedocs.org,soulshake/readthedocs.org,mhils/readthedocs.org,johncosta/private-readthedocs.org,nikolas/readthedocs.org,ojii/readthedocs.org,KamranMackey... | ---
+++
@@ -23,16 +23,16 @@
pdf_match = pdf_re.search(pdf_results[1])
if pdf_match:
from_path = os.path.join(os.getcwd(),
- "%s.pdf" % project.slug)
+ "%s.pdf" % pdf_match.group(1).strip())
... |
9937823496db32a4d3eac3eee0fa4d310ea07e11 | dvhb_hybrid/files/models.py | dvhb_hybrid/files/models.py | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Image(UpdatedMixin, models.Model):
author = models.Fo... | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Imag... | Add index for image metainformation | Add index for image metainformation
| Python | mit | dvhbru/dvhb-hybrid | ---
+++
@@ -2,6 +2,7 @@
from django.conf import settings
from django.contrib.postgres.fields import JSONField
+from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _
@@ -22,6 +23,7 @@
verbose_name = _('image')
... |
2d9e7843106b2fce247dda8f14bc192c3d98e91f | tests/test_simpleflow.py | tests/test_simpleflow.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from simpleflow import simpleflow
def test_basic():
assert 0, 'write me!' | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_basic():
import simpleflow
assert True
| Add basic test that only import simpleflow | Add basic test that only import simpleflow
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-from simpleflow import simpleflow
def test_basic():
- assert 0, 'write me!'
+ import simpleflow
+ assert True |
4877f6a242b0c0ecad798ec648d919fc05065c8e | sketchbook/_version.py | sketchbook/_version.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 Kaede Hoshikawa
#
# 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
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 Kaede Hoshikawa
#
# 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
... | Move master version to 0.1.2. | Move master version to 0.1.2.
| Python | apache-2.0 | futursolo/sketchbook,futursolo/sketchbook | ---
+++
@@ -17,7 +17,7 @@
__all__ = ["__version__"]
-_tag_version = (0, 1, 1)
+_tag_version = (0, 1, 2)
_dev = 0
|
6093d2954861f2783da3e5b8473cb13b0469685b | elasticquery/filterquery.py | elasticquery/filterquery.py | # ElasticQuery
# File: elasticquery/filterquery.py
# Desc: The base query class & metaclass
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll... | # ElasticQuery
# File: elasticquery/filterquery.py
# Desc: The base query class & metaclass
import json
from .util import make_dsl_object, unroll_definitions, unroll_struct
class MetaFilterQuery(type):
def __init__(cls, name, bases, d):
super(MetaFilterQuery, cls).__init__(name, bases, d)
unroll... | Support nosetests, handle magic names (and_, or_, etc) | Support nosetests, handle magic names (and_, or_, etc)
| Python | mit | Fizzadar/ElasticQuery,Fizzadar/ElasticQuery | ---
+++
@@ -13,6 +13,9 @@
unroll_definitions(cls._definitions)
def __getattr__(cls, key):
+ if key == '__test__':
+ return None
+
if key not in cls._definitions:
raise cls._exception(key)
@@ -32,8 +35,10 @@
self._dsl_type = dsl_type
def dict(se... |
51f0cd392cab5737cb444b9eef8700fcd4713ea0 | tests/recipes_test.py | tests/recipes_test.py | #!/usr/bin/env python
# Copyright (c) 2015 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.
"""Runs simulation tests and lint on the recipes."""
import os
import subprocess
ROOT_DIR = os.path.dirname(os.path.dirname(os.p... | #!/usr/bin/env python
# Copyright (c) 2015 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.
"""Runs simulation tests and lint on the recipes."""
import os
import subprocess
ROOT_DIR = os.path.dirname(os.path.dirname(os.p... | Remove deprecated (ignored) --use-bootstrap flag | [recipes] Remove deprecated (ignored) --use-bootstrap flag
This has been ignored for a long time, and I'd like to get rid of it.
R=jchinlee@chromium.org, ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org
Change-Id: I240d59cc10a2882041ac2c8abfeb1894237516a6
Reviewed-on: https://chromium-review.googlesource.com/c/... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools | ---
+++
@@ -13,8 +13,8 @@
def recipes_py(*args):
subprocess.check_call([
- os.path.join(ROOT_DIR, 'recipes', 'recipes.py'),
- '--use-bootstrap'] + list(args))
+ os.path.join(ROOT_DIR, 'recipes', 'recipes.py')
+ ] + list(args))
recipes_py('test', 'run')
|
df68b821807d25d204f43d7b1805da6c25f42b43 | src/lib/pagination.py | src/lib/pagination.py | from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A legacy paginator that mocks the one from Eve Python
"""
... | from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class LegacyPaginator(PageNumberPagination):
"""
A legacy paginator that mocks the one from Eve Python
"""
... | Set a maximum to the number of elements that may be requested | Set a maximum to the number of elements that may be requested
| Python | agpl-3.0 | lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django | ---
+++
@@ -10,6 +10,7 @@
"""
page_size = 25
page_size_query_param = "max_results"
+ max_page_size = 100
def get_paginated_response(self, data):
links = OrderedDict() |
f659e612f87ccb2a9d466ae62ed8f2b2700497ab | cms/tests/test_externals.py | cms/tests/test_externals.py | from django.test import TestCase
from ..externals import External
try:
from contextlib import GeneratorContextManager
except ImportError:
from contextlib import _GeneratorContextManager as GeneratorContextManager
from types import FunctionType
class TestExternals(TestCase):
def test_load(self):
... | from django.test import TestCase
from django.utils import six
from ..externals import External
from types import FunctionType
import unittest
class TestExternals(TestCase):
def test_load(self):
external = External('foo')
with self.assertRaises(ImportError):
external._load('')
... | Disable an externals tests on Py3. | Disable an externals tests on Py3.
| Python | bsd-3-clause | dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,danielsamuels/cms,danielsamuels/cms,jamesfoley/cms | ---
+++
@@ -1,13 +1,10 @@
from django.test import TestCase
+from django.utils import six
from ..externals import External
-try:
- from contextlib import GeneratorContextManager
-except ImportError:
- from contextlib import _GeneratorContextManager as GeneratorContextManager
-
from types import FunctionTy... |
658f0f6825b4f4a226349fcee63a0c5fbbd5ba9e | webapp/cached.py | webapp/cached.py | from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def i... | from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def i... | Use ternary operator for arg selection. | Use ternary operator for arg selection.
| Python | mit | cheddartv/stockstream.live,cheddartv/stockstream.live | ---
+++
@@ -9,9 +9,7 @@
def __call__(self, func):
def inner(*args, **kwargs):
- param = args[0]
- if len(args) > 1:
- param = args[1]
+ param = args[1] if len(args) > 1 else args[0]
max_age = kwargs.get('max_age', self.default_max_age)
... |
b50af9b9790dedea7902d827a86d017ce9177070 | digest/management/commands/export_items.py | digest/management/commands/export_items.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from django.db.models import Q
from digest.management.commands.create_dataset import create_dataset
from digest.models import Item
class Command(BaseCommand):
help = 'Create dataset'
def hand... | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.db.models import Q
from digest.management.commands.create_dataset import create_dataset
from digest.models import Item
class Command(BaseCommand):
help = 'Create dataset'
def handle(self, *args, **options):
"""
... | Update export items command for dataset | Update export items command for dataset
| Python | mit | pythondigest/pythondigest,pythondigest/pythondigest,pythondigest/pythondigest | ---
+++
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
from django.core.management.base import BaseCommand
from django.db.models import Q
@@ -25,4 +23,15 @@
for entry in urls:
query = query | Q(link__contains=entry)
- create_dataset(Item.objects.... |
da252b07e661eed25d2ed23104a4b453f6785a29 | ynr/apps/search/utils.py | ynr/apps/search/utils.py | import re
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import Count, F
from people.models import Person
def search_person_by_name(name, synonym=True):
name = name.lower()
name = re.sub(r"[^a-z ]", "", name)
name = " ".join(name.strip().split())
and_name = ... | import re
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import Count, F
from people.models import Person
def search_person_by_name(name, synonym=True):
name = name.lower()
name = re.sub(r"[^a-z ]", " ", name)
name = " ".join(name.strip().split())
and_name =... | Make sure we can search names with ' | Make sure we can search names with '
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -8,7 +8,7 @@
def search_person_by_name(name, synonym=True):
name = name.lower()
- name = re.sub(r"[^a-z ]", "", name)
+ name = re.sub(r"[^a-z ]", " ", name)
name = " ".join(name.strip().split())
and_name = " & ".join(name.split(" "))
or_name = " | ".join(name.split(" ")) |
2d24b1b2f9fd5c661a48f233480ab09322d6bf91 | heltour/local/martinsmacmini.py | heltour/local/martinsmacmini.py | DEBUG = True
# GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH = '/home/vagrant/heltour/gspread.conf'
# SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf'
INTERNAL_IPS = ['127.0.0.1']
# JAVAFO_COMMAND = 'java -jar /home/vagrant/heltour/javafo.jar'
# STATIC_ROOT = '/home/vagrant/heltour/static'
# EMAIL_BACKEND =... | DEBUG = True
# GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH = '/home/vagrant/heltour/gspread.conf'
# SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf'
INTERNAL_IPS = ['127.0.0.1']
LICHESS_CREDS_FILE_PATH = '/Users/colwem/workshop/heltour/.ignore/lichess.conf'
LINK_PROTOCOL = 'http'
SITE_ID = 2
# JAVAFO_COMM... | Add config to local config to enable login to work | Add config to local config to enable login to work
| Python | mit | cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour | ---
+++
@@ -3,6 +3,10 @@
# SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf'
INTERNAL_IPS = ['127.0.0.1']
+
+LICHESS_CREDS_FILE_PATH = '/Users/colwem/workshop/heltour/.ignore/lichess.conf'
+LINK_PROTOCOL = 'http'
+SITE_ID = 2
# JAVAFO_COMMAND = 'java -jar /home/vagrant/heltour/javafo.jar'
# S... |
45fb01574d410c2a764e5b40a5e93a44fa8f6584 | flask_admin/contrib/geoa/form.py | flask_admin/contrib/geoa/form.py | from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geometry')
def convert_geom(self, column, field_args, **extra):
field_args[... | from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geography', 'Geometry')
def convert_geom(self, column, field_args, **extra):
... | Add Geography Type to GeoAlchemy Backend | Add Geography Type to GeoAlchemy Backend
The current GeoAlchemy backend only works with geometry columns, and ignores geography columns (which are also supported by geoalchemy). This 1-word fix adds support for geography columns. | Python | bsd-3-clause | litnimax/flask-admin,petrus-jvrensburg/flask-admin,closeio/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,dxmo/flask-admin,ondoheer/flask-admin,plaes/flask-admin,LennartP/flask-admin,jamesbeebop/flask-admin,NickWoodhams/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,radioprotector/f... | ---
+++
@@ -4,7 +4,7 @@
class AdminModelConverter(SQLAAdminConverter):
- @converts('Geometry')
+ @converts('Geography', 'Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid |
e8711eca94afb6ab05baf6e61ddee95d193f3cd7 | fabfile/oae_env/__init__.py | fabfile/oae_env/__init__.py |
def activity_hosts():
return ["activity0", "activity1", "activity2"]
def app_hosts():
return ["app0", "app1", "app2", "app3"]
def etherpad_hosts():
return ["etherpad0", "etherpad1", "etherpad2"]
def pp_hosts():
return ["pp0", "pp1", "pp2"]
def puppet_host():
return "puppet"
def web_host(... |
def activity_hosts():
return ["activity0", "activity1", "activity2"]
def app_hosts():
return ["app0", "app1", "app2", "app3"]
def etherpad_hosts():
return ["etherpad0", "etherpad1", "etherpad2"]
def pp_hosts():
return ["pp0", "pp1", "pp2"]
def puppet_host():
return "puppet"
def web_host(... | Switch web node to web1 | Switch web node to web1
| Python | apache-2.0 | oaeproject/oae-fabric | ---
+++
@@ -21,4 +21,4 @@
def web_host():
- return "web0"
+ return "web1" |
577ec0c981651cb039f768b9eb92ef91f8511017 | flocker/control/_clusterstate.py | flocker/control/_clusterstate.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | Address review comment: Document return type. | Address review comment: Document return type.
| Python | apache-2.0 | agonzalezro/flocker,Azulinho/flocker,LaynePeng/flocker,runcom/flocker,achanda/flocker,jml/flocker,1d4Nf6/flocker,mbrukman/flocker,jml/flocker,adamtheturtle/flocker,lukemarsden/flocker,moypray/flocker,achanda/flocker,w4ngyi/flocker,LaynePeng/flocker,mbrukman/flocker,w4ngyi/flocker,1d4Nf6/flocker,achanda/flocker,Azulinho... | ---
+++
@@ -33,6 +33,8 @@
def as_deployment(self):
"""
Return cluster state as a Deployment object.
+
+ :return Deployment: Current state of the cluster.
"""
return Deployment(nodes=frozenset([
Node(hostname=hostname, |
02f5db5fdb46684b60a9b5e9125da228a927c2c3 | mrbelvedereci/build/cumulusci/config.py | mrbelvedereci/build/cumulusci/config.py | from cumulusci.core.config import YamlGlobalConfig
from cumulusci.core.config import YamlProjectConfig
class MrbelvedereProjectConfig(YamlProjectConfig):
def __init__(self, global_config_obj, build_flow):
super(MrbelvedereProjectConfig, self).__init__(global_config_obj)
self.build_flow = build_flow... | from cumulusci.core.config import YamlGlobalConfig
from cumulusci.core.config import YamlProjectConfig
class MrbelvedereProjectConfig(YamlProjectConfig):
def __init__(self, global_config_obj, build_flow):
self.build_flow = build_flow
super(MrbelvedereProjectConfig, self).__init__(global_config_obj)... | Set self.build_flow before calling the super __init__ method | Set self.build_flow before calling the super __init__ method
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | ---
+++
@@ -3,8 +3,8 @@
class MrbelvedereProjectConfig(YamlProjectConfig):
def __init__(self, global_config_obj, build_flow):
+ self.build_flow = build_flow
super(MrbelvedereProjectConfig, self).__init__(global_config_obj)
- self.build_flow = build_flow
@property
def config_... |
c8d7224f62d7a8da08514c37acfa83e2754252c6 | functionaltests/api/base.py | functionaltests/api/base.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... | Fix Tempest tests failing on gate-solum-devstack-dsvm | Fix Tempest tests failing on gate-solum-devstack-dsvm
Due to a new commit on tempest, all our devstack tests were
failing. This was due to an inheritance we have to RestClient
from tempest. The signature of the constructor has changed.
This patch changes the signature of our inherited classes to
match the change from... | Python | apache-2.0 | ed-/solum,julienvey/solum,devdattakulkarni/test-solum,openstack/solum,stackforge/solum,gilbertpilz/solum,gilbertpilz/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum,openstack/solum,stackforge/solum,ed-/solum,julienvey/solum,ed-/solum,gilbertpilz/solum | ---
+++
@@ -23,9 +23,9 @@
class SolumClient(rest_client.RestClient):
- def __init__(self, config, username, password, auth_url, tenant_name=None):
- super(SolumClient, self).__init__(config, username, password,
- auth_url, tenant_name)
+ def __init__(self, us... |
998586b575149ae549b755067c831f8b066c1845 | digi/migrations/0002_theme_page_add_body_and_blog_category.py | digi/migrations/0002_theme_page_add_body_and_blog_category.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-04 11:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-04 11:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
... | Use exact version instead of latest in the migration dependencies | Use exact version instead of latest in the migration dependencies
Changed to use the latest migration of wagtail-blog v1.6.9.
Refs
https://github.com/thelabnyc/wagtail_blog/blob/5147d8129127102009c9bd63b1886e7665f6ccfb/blog/migrations/0005_auto_20151019_1121.py
| Python | mit | City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel | ---
+++
@@ -11,7 +11,7 @@
class Migration(migrations.Migration):
dependencies = [
- ('blog', '__latest__'),
+ ('blog', '0005_auto_20151019_1121'),
('digi', '0001_initial'),
]
|
3ced8676d474df3149bf78519e918cfa3b6b0ec3 | src/dal_gm2m/fields.py | src/dal_gm2m/fields.py | """GM2MField support for autocomplete fields."""
class GM2MFieldMixin(object):
"""GM2MField ror FutureModelForm."""
def value_from_object(self, instance, name):
"""Return the list of objects in the GM2MField relation."""
return None if not instance.pk else [
x for x in getattr(ins... | """GM2MField support for autocomplete fields."""
class GM2MFieldMixin(object):
"""GM2MField ror FutureModelForm."""
def value_from_object(self, instance, name):
"""Return the list of objects in the GM2MField relation."""
return None if not instance.pk else [
getattr(x, 'gm2m_tgt',... | Support new versions with django-gm2m | Support new versions with django-gm2m
| Python | mit | yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light | ---
+++
@@ -7,7 +7,9 @@
def value_from_object(self, instance, name):
"""Return the list of objects in the GM2MField relation."""
return None if not instance.pk else [
- x for x in getattr(instance, name).all()]
+ getattr(x, 'gm2m_tgt', x)
+ for x in getattr(inst... |
4855a379c3720588168a61545ab1af3291075489 | Lib/distutils/__init__.py | Lib/distutils/__init__.py | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
# Distutils version
#
# Please coordinate with Marc-Andre Lemburg ... | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
# Distutils version
#
# Please coordinate with Marc-Andre Lemburg ... | Bump the patch level version of distutils since there were a few bug fixes since the 2.5.0 release. | Bump the patch level version of distutils since there were a few bug fixes since
the 2.5.0 release.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -20,4 +20,4 @@
# In general, major and minor version should loosely follow the Python
# version number the distutils code was shipped with.
#
-__version__ = "2.5.0"
+__version__ = "2.5.1" |
07a427d687a2618c03d62eb60d849c4ed26752c4 | config.example.py | config.example.py | # Must be a mysql database!
database_uri = 'mysql://root@localhost/pushjet_api'
# Are we debugging the server?
# Do not turn this on when in production!
debug = True
# Limit requests?
limiter = False
# Google Cloud Messaging configuration (required for android!)
google_api_key = ''
# Message Queueing, this should b... | # Must be a mysql database!
database_uri = 'mysql://root@localhost/pushjet_api'
# Are we debugging the server?
# Do not turn this on when in production!
debug = True
# Limit requests?
limiter = False
# Google Cloud Messaging configuration (required for android!)
google_api_key = ''
# Message Queueing, this should b... | Add default relay uri to the default config | Add default relay uri to the default config | Python | bsd-2-clause | Pushjet/Pushjet-Server-Api | ---
+++
@@ -12,4 +12,4 @@
google_api_key = ''
# Message Queueing, this should be the relay
-zeromq_relay_uri = ''
+zeromq_relay_uri = 'ipc:///tmp/pushjet-relay.ipc' |
eb175a077affcdaa1e1cea6da557dd163890d958 | djlime/forms/utils.py | djlime/forms/utils.py | # -*- coding: utf-8 -*-
"""
djlime.forms.utils
~~~~~~~~~~~~~~~~~~
Utilities for forms.
:copyright: (c) 2012 by Andrey Voronov.
:license: BSD, see LICENSE for more details.
"""
from django.utils import simplejson
def form_errors_to_json(form):
return simplejson.dumps({'success': False,
... | # -*- coding: utf-8 -*-
"""
djlime.forms.utils
~~~~~~~~~~~~~~~~~~
Utilities for forms.
:copyright: (c) 2012 by Andrey Voronov.
:license: BSD, see LICENSE for more details.
"""
from django.utils import simplejson
def _errors_to_dict(form):
return dict([(k, v[0]) for k, v in form.errors.items(... | Improve form_errors_to_json to handle multiple forms | Improve form_errors_to_json to handle multiple forms
| Python | bsd-3-clause | freshlimestudio/djlime | ---
+++
@@ -10,6 +10,16 @@
"""
from django.utils import simplejson
+
+def _errors_to_dict(form):
+ return dict([(k, v[0]) for k, v in form.errors.items()])
+
+
def form_errors_to_json(form):
- return simplejson.dumps({'success': False,
- 'errors': dict([(k, v[0]) for k, v in for... |
cfd6c7c2d7af47329deac3e7ff618b66a078263c | ines/middlewares/logs.py | ines/middlewares/logs.py | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.middlewares import Middleware
from ines.utils import format_error_to_json
class LoggingMi... | # -*- coding: utf-8 -*-
import sys
from traceback import format_exception
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
from ines.convert import force_string
from ines.middlewares import Middleware
from ines.utils import ... | Set log with small message | Set log with small message
| Python | mit | hugobranquinho/ines | ---
+++
@@ -7,6 +7,7 @@
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.interfaces import IRequestFactory
+from ines.convert import force_string
from ines.middlewares import Middleware
from ines.utils import format_error_to_json
@@ -26,19 +27,25 @@
try:
for chunk ... |
47d9217b6ee9837987d25d77cc6e3c750766ed90 | tests/test_formats.py | tests/test_formats.py | from contextlib import contextmanager
from tempfile import TemporaryDirectory
from django.core.management import call_command
from django.test import TestCase
from django_archive import archivers
class FormatsTestCase(TestCase):
"""
Test that the archive command works with all available formats
"""
... | from contextlib import contextmanager
from tempfile import TemporaryDirectory
from django.core.management import call_command
from django.test import TestCase
from django_archive import archivers
class FormatsTestCase(TestCase):
"""
Test that the archive command works with all available formats
"""
... | Fix bug in temporary directory generation. | Fix bug in temporary directory generation.
| Python | mit | nathan-osman/django-archive,nathan-osman/django-archive | ---
+++
@@ -23,7 +23,8 @@
@contextmanager
def _wrap_in_temp_dir(self):
with TemporaryDirectory() as directory:
- yield self.settings(ARCHIVE_DIRECTORY=directory)
+ with self.settings(ARCHIVE_DIRECTORY=directory):
+ yield None
def test_archive(self):
... |
4ec8a5b5880f7e5300d71c34f5b293ea5993f5b2 | tests/test_storage.py | tests/test_storage.py | import os
import json
import pytest
def test_add_single(identity_fixures, identity_store):
for d in identity_fixures:
identity = identity_store.add_identity(d)
for key, val in d.items():
assert getattr(identity, key) == val
def test_add_multiple(identity_fixures, identity_store):
... | import os
import json
import pytest
def test_add_single(identity_fixures, identity_store):
for d in identity_fixures:
identity = identity_store.add_identity(d)
for key, val in d.items():
assert getattr(identity, key) == val
def test_add_multiple(identity_fixures, identity_store):
... | Convert dict view to list for Py3 | Convert dict view to list for Py3
| Python | mit | nocarryr/AWS-Identity-Manager | ---
+++
@@ -19,7 +19,7 @@
identity_store.add_identities(*identity_fixures)
with pytest.raises(IdentityExists):
identity_store.add_identity(identity_fixures[0])
- identity = identity_store.identities.values()[0]
+ identity = list(identity_store.values())[0]
original_id = identity.id
... |
0fbffce39b7e0209d04e26bd43009c2e6e5e0c46 | testsuite/settings.py | testsuite/settings.py | from pathlib import Path
from hoover.site.settings.common import *
INSTALLED_APPS = INSTALLED_APPS + [
'hoover.contrib.twofactor',
'django_otp',
'django_otp.plugins.otp_totp',
]
MIDDLEWARE = MIDDLEWARE + [
'django_otp.middleware.OTPMiddleware',
'hoover.contrib.twofactor.middleware.AutoLogout',
... | from pathlib import Path
from hoover.site.settings.common import *
INSTALLED_APPS = INSTALLED_APPS + [
'hoover.contrib.twofactor',
'django_otp',
'django_otp.plugins.otp_totp',
]
MIDDLEWARE = MIDDLEWARE + [
'django_otp.middleware.OTPMiddleware',
'hoover.contrib.twofactor.middleware.AutoLogout',
... | Remove some indirection, set db password | Remove some indirection, set db password
| Python | mit | hoover/search,hoover/search,hoover/search | ---
+++
@@ -15,7 +15,6 @@
testsuite_dir = Path(__file__).absolute().parent
-del HOOVER_ELASTICSEARCH_URL
SECRET_KEY = 'testing secret key'
HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads')
HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui')
@@ -23,4 +22,14 @@
HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute
... |
8b25f5606b160422f6eb698f4edae8cb5013a310 | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.3.0.dev0 | Update dsub version to 0.3.0.dev0
PiperOrigin-RevId: 241419925
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.2.6'
+DSUB_VERSION = '0.3.0.dev0' |
ce05a68965a252a1756d6eac64bf319ef17ed158 | packages/python/plotly/plotly/io/_utils.py | packages/python/plotly/plotly/io/_utils.py | from __future__ import absolute_import
import plotly
import plotly.graph_objs as go
def validate_coerce_fig_to_dict(fig, validate, clone=True):
from plotly.basedatatypes import BaseFigure
if isinstance(fig, BaseFigure):
fig_dict = fig.to_dict(clone=clone)
elif isinstance(fig, dict):
if v... | from __future__ import absolute_import
import plotly
import plotly.graph_objs as go
def validate_coerce_fig_to_dict(fig, validate, clone=True):
from plotly.basedatatypes import BaseFigure
if isinstance(fig, BaseFigure):
fig_dict = fig.to_dict(clone=clone)
elif isinstance(fig, dict):
if v... | Handle Dash objects in to_json | Handle Dash objects in to_json
| Python | mit | plotly/plotly.py,plotly/plotly.py,plotly/plotly.py | ---
+++
@@ -15,6 +15,8 @@
fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json()
else:
fig_dict = fig
+ elif hasattr(fig, "to_plotly_json"):
+ fig_dict = fig.to_plotly_json()
else:
raise ValueError(
""" |
65e12efb52e9eef330ab8f7a9f50a8f255fb4aae | JasmineCoffeeScriptDetectFileType.py | JasmineCoffeeScriptDetectFileType.py | import sublime, sublime_plugin
import os
class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener):
""" Detects current file type if the file's extension isn't conclusive """
def on_load(self, view):
filename = view.file_name()
if not filename: # buffer has never been saved
return... | import sublime, sublime_plugin
import os
class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener):
""" Detects current file type if the file's extension isn't conclusive """
def on_load(self, view):
filename = view.file_name()
if not filename: # buffer has never been saved
return... | Adjust syntax detector to account for new ST3 default package name | Adjust syntax detector to account for new ST3 default package name
| Python | mit | integrum/sublime-text-jasmine-coffeescript | ---
+++
@@ -11,7 +11,7 @@
name = os.path.basename(filename.lower())
if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"):
- set_syntax(view, "Jasmine CoffeeScript", "jasmine-coffeescript/Syntaxes")
+ set_syntax(view, "Jasmine CoffeeScript", "Jasmine CoffeeScript/Syntaxes")
def s... |
510ea7c6971ede66206cfb5d24b16a38f18ffee1 | mzalendo/odekro/management/commands/add_mps.py | mzalendo/odekro/management/commands/add_mps.py | from django.core.management.base import BaseCommand, CommandError
from odekro import data
class Command(BaseCommand):
"""Read in an info page file and either create or update existing info"""
help = 'Add MPs data'
args = '<file>'
def handle(self, *args, **options):
# file = open(args[])
... | from django.core.management.base import BaseCommand, CommandError
from odekro import data
class Command(BaseCommand):
"""Read in mps data and either create or update existing info"""
help = 'Add MPs data'
args = '<file>'
def handle(self, *args, **options):
# file = open(args[])
if l... | Update a docstring to match the upstream odekro branch | Update a docstring to match the upstream odekro branch
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola | ---
+++
@@ -4,7 +4,7 @@
class Command(BaseCommand):
- """Read in an info page file and either create or update existing info"""
+ """Read in mps data and either create or update existing info"""
help = 'Add MPs data'
args = '<file>' |
b5f7cf1a83d24a36def961f62556f26442d9f5ca | buckets/test/urls.py | buckets/test/urls.py | from django.conf.urls import include, url
from buckets.test import views
urlpatterns = [
url(r'^', include('buckets.urls')),
url(r'^media/s3/uploads$', views.fake_s3_upload, name='fake_s3_upload'),
]
| from django.conf.urls import include, url
from buckets.test import views
urlpatterns = [
url(r'^', include('buckets.urls')),
url(r'^media/s3/uploads/$', views.fake_s3_upload, name='fake_s3_upload'),
]
| Add trailing slash to fake_s3_upload url | Add trailing slash to fake_s3_upload url | Python | agpl-3.0 | Cadasta/django-buckets,Cadasta/django-buckets,Cadasta/django-buckets | ---
+++
@@ -3,5 +3,5 @@
urlpatterns = [
url(r'^', include('buckets.urls')),
- url(r'^media/s3/uploads$', views.fake_s3_upload, name='fake_s3_upload'),
+ url(r'^media/s3/uploads/$', views.fake_s3_upload, name='fake_s3_upload'),
] |
a376d66b4d58e22f35ad4f43e8b6f2ad775d68a8 | vaux/api/downloads.py | vaux/api/downloads.py | from flask.ext import restful
from . import database
from flask import abort, send_file
from werkzeug import secure_filename
import os
class DownloadInstance(restful.Resource):
def get(self, id):
document = database.get_document(id)
if document is None:
abort(404)
return send_f... | from flask.ext import restful
from . import database
from flask import abort, send_file
import mimetypes
class DownloadInstance(restful.Resource):
def get(self, id):
document = database.get_document(id)
if document is None:
abort(404)
mt = mimetypes.guess_type(document['path'])... | Make sure we give people a download with the actual name of the file | Make sure we give people a download with the actual name of the file
| Python | mit | VauxIo/core | ---
+++
@@ -1,8 +1,7 @@
from flask.ext import restful
from . import database
from flask import abort, send_file
-from werkzeug import secure_filename
-import os
+import mimetypes
class DownloadInstance(restful.Resource):
@@ -10,5 +9,8 @@
document = database.get_document(id)
if document is No... |
deac9119d4d03434a2d610920a431127927ac56a | netdisco/discoverables/belkin_wemo.py | netdisco/discoverables/belkin_wemo.py | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description.f... | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description.f... | Update discovery method for Wemo devices | Update discovery method for Wemo devices
| Python | mit | sfam/netdisco,toddeye/netdisco,rohitranjan1991/netdisco,tomduijf/netdisco,brburns/netdisco,balloob/netdisco | ---
+++
@@ -16,4 +16,5 @@
def get_entries(self):
""" Returns all Belkin Wemo entries. """
- return self.find_by_st('urn:Belkin:service:manufacture:1')
+ return self.find_by_device_description(
+ {'manufacturer': 'Belkin International Inc.'}) |
e2c4529fc35c07721f1ed70ae2bf88538a67677b | slave/skia_slave_scripts/compare_gms.py | slave/skia_slave_scripts/compare_gms.py | #!/usr/bin/env python
# Copyright (c) 2012 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.
""" Compare the generated GM images to the baselines """
# System-level imports
import os
import sys
from build_step import Build... | #!/usr/bin/env python
# Copyright (c) 2012 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.
""" Compare the generated GM images to the baselines """
# System-level imports
import os
import sys
from build_step import Build... | Remove Ubuntu12 32 from may_fail_with_warning | Remove Ubuntu12 32 from may_fail_with_warning
It's empty now. TODO: Remove the functionality once we're sure we don't
need it.
R=robertphillips@google.com
Review URL: https://codereview.chromium.org/23545022
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11055 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... | ---
+++
@@ -20,10 +20,7 @@
# Temporary list of builders who are allowed to fail this step without the
# bot turning red.
- may_fail_with_warning = [
- 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release',
- 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release-Trybot',
- ]
+ may_fail_with_warning... |
53764e4ce0f82dc0706a9fd64877ccda5e97c32f | compd-score-match.py | compd-score-match.py | #!/usr/bin/env python
import os
import sys
import yaml
import score
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
matc... | #!/usr/bin/env python
import os
import sys
import yaml
import score
MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
u... | Update match-id to equal that used in compd. | Update match-id to equal that used in compd.
| Python | mit | samphippen/scoring_2013,samphippen/scoring_2013 | ---
+++
@@ -5,6 +5,8 @@
import yaml
import score
+
+MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
@@ -28,7 +30,9 @@
scorer = score.StrangeGameScorer(scores)
scorer.compute_cell_winners()
+match_id = MATCH_ID.format(match_num)
+
for tla in scores.keys():
this_scor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.