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 |
|---|---|---|---|---|---|---|---|---|---|---|
4048d697628ca372d981d888d9ffda4b202c56fa | config.py | config.py | DATADIR = "data/"
TRACKDIR = DATADIR + "tracks/"
LOCKFILE = TRACKDIR + "current_experiment.lock"
PLOTDIR = DATADIR + "plots/"
ARCHIVEDIR = DATADIR + "tracks_archive/"
DBGFRAMEDIR = DATADIR + "debug_frames/"
INIDIR = "ini/"
EXPSCRIPT = "python fishbox.py"
APPDIR = "fishweb/"
TEMPLATEDIR = APPDIR + "views/"
STATICDIR ... | DATADIR = "data/"
TRACKDIR = DATADIR + "tracks/"
LOCKFILE = DATADIR + "current_experiment.lock"
PLOTDIR = DATADIR + "plots/"
ARCHIVEDIR = DATADIR + "tracks_archive/"
DBGFRAMEDIR = DATADIR + "debug_frames/"
INIDIR = "ini/"
EXPSCRIPT = "python fishbox.py"
APPDIR = "fishweb/"
TEMPLATEDIR = APPDIR + "views/"
STATICDIR =... | Move lockfile to root datadir. | Move lockfile to root datadir.
| Python | mit | liffiton/ATLeS,liffiton/ATLeS,liffiton/ATLeS,liffiton/ATLeS | ---
+++
@@ -1,6 +1,6 @@
DATADIR = "data/"
TRACKDIR = DATADIR + "tracks/"
-LOCKFILE = TRACKDIR + "current_experiment.lock"
+LOCKFILE = DATADIR + "current_experiment.lock"
PLOTDIR = DATADIR + "plots/"
ARCHIVEDIR = DATADIR + "tracks_archive/"
DBGFRAMEDIR = DATADIR + "debug_frames/" |
9d73be469a006ae13cd847e17a62e7740bfd3d4e | dlstats/fetchers/__init__.py | dlstats/fetchers/__init__.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from . import eurostat, insee, world_bank
| #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from . import eurostat, insee, world_bank, IMF
| Add IMF to the fetchers | Add IMF to the fetchers
| Python | agpl-3.0 | mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,MichelJuillard/dlstats | ---
+++
@@ -1,3 +1,3 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
-from . import eurostat, insee, world_bank
+from . import eurostat, insee, world_bank, IMF |
bd2636db55396cac2ff6766593d5082562d865e2 | lightning/types/decorators.py | lightning/types/decorators.py | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
if not hasattr(VizType,'_func'):
func = VizType._name
else:
... | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
if not hasattr(self, 'session'):
self.create_session()
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
... | Create session if one doesn't exist | Create session if one doesn't exist
| Python | mit | peterkshultz/lightning-python,garretstuber/lightning-python,lightning-viz/lightning-python,garretstuber/lightning-python,garretstuber/lightning-python,lightning-viz/lightning-python,peterkshultz/lightning-python,peterkshultz/lightning-python | ---
+++
@@ -4,6 +4,8 @@
def viztype(VizType):
def plotter(self, *args, **kwargs):
+ if not hasattr(self, 'session'):
+ self.create_session()
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz |
dc6c8b77ea944e97a9f49dd1f7ae2244f4cad2ca | bluebottle/test/factory_models/organizations.py | bluebottle/test/factory_models/organizations.py | import factory
from bluebottle.organizations.models import OrganizationContact, Organization, OrganizationMember
from .geo import CountryFactory
from .accounts import BlueBottleUserFactory
class OrganizationFactory(factory.DjangoModelFactory):
class Meta(object):
model = Organization
name = factory.... | import factory
from bluebottle.organizations.models import OrganizationContact, Organization
from .geo import CountryFactory
from .accounts import BlueBottleUserFactory
class OrganizationFactory(factory.DjangoModelFactory):
class Meta(object):
model = Organization
name = factory.Sequence(lambda n: '... | Remove unused org member in factory | Remove unused org member in factory
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -1,6 +1,6 @@
import factory
-from bluebottle.organizations.models import OrganizationContact, Organization, OrganizationMember
+from bluebottle.organizations.models import OrganizationContact, Organization
from .geo import CountryFactory
from .accounts import BlueBottleUserFactory
@@ -34,12 +34,3 @@... |
651f2d04dc82ea0e9c653280f0bd4a17bedcb88b | server_app/__main__.py | server_app/__main__.py | import sys
import os
import logging
import time
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat-"+time.strftime("%d-%m-%Y.log"), level=logging.DEBUG)
sys.stderr.close()
sys.stdout.close... | import sys
import os
import logging
import time
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat-"+time.strftime("%d-%m-%Y.log"), level=logging.DEBUG))
sys.stderr.close()
sys.stdout.clos... | Make logger sort by date | Make logger sort by date
| Python | bsd-3-clause | jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat | ---
+++
@@ -5,7 +5,7 @@
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
-logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat-"+time.strftime("%d-%m-%Y.log"), level=logging.DEBUG)
+logging.basicConfig(filename=os.path.expanduser("~/.c... |
ee2cb8687f6e4ecddfef797cc63c7daa40731dc8 | user_management/models/tests/factories.py | user_management/models/tests/factories.py | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
@classmethod
def _prepare(cl... | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
password = factory.PostGeneration... | Use PostGenerationMethodCall instead of _prepare. | Use PostGenerationMethodCall instead of _prepare.
| Python | bsd-2-clause | incuna/django-user-management,incuna/django-user-management | ---
+++
@@ -7,13 +7,4 @@
FACTORY_FOR = get_user_model()
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
-
- @classmethod
- def _prepare(cls, create, **kwargs):
- password = kwargs.pop('password', None)
- ... |
275257cfcf17fa1d2498e64735754cb4b8a3f2e8 | floo/sublime.py | floo/sublime.py | import sys
from collections import defaultdict
import time
timeouts = defaultdict(list)
top_timeout_id = 0
cancelled_timeouts = set()
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
global top_timeout_id
timeout_id = top_timeout_id
top_timeout_id + 1
if... | import sys
from collections import defaultdict
import time
timeouts = defaultdict(list)
top_timeout_id = 0
cancelled_timeouts = set()
calling_timeouts = False
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
global top_timeout_id
timeout_id = top_timeout_id
... | Stop exception if someone calls timeouts from a timeout. | Stop exception if someone calls timeouts from a timeout.
| Python | apache-2.0 | Floobits/floobits-emacs | ---
+++
@@ -6,6 +6,7 @@
timeouts = defaultdict(list)
top_timeout_id = 0
cancelled_timeouts = set()
+calling_timeouts = False
def windows(*args, **kwargs):
@@ -36,6 +37,10 @@
def call_timeouts():
+ global calling_timeouts
+ if calling_timeouts:
+ return
+ calling_timeouts = True
now =... |
ac508ff550dab2b0e9171be4fc6c12529ab111c5 | gateway/conf.py | gateway/conf.py | CAMERA_NETWORK_IP = '0.0.0.0'
CAMERA_NETWORK_TCP_PORT = 9090
MOBILE_NETWORK_IP = '0.0.0.0'
MOBILE_NETWORK_HTTP_PORT = 80
MOBILE_NETWORK_TCP_PORT = 13000
| CAMERA_NETWORK_IP = '0.0.0.0'
CAMERA_NETWORK_TCP_PORT = 9090
MOBILE_NETWORK_IP = '0.0.0.0'
MOBILE_NETWORK_HTTP_PORT = 13000
MOBILE_NETWORK_TCP_PORT = 13001
| Change mobile's HTTP port to 13000 and TCP port to 13001 | Change mobile's HTTP port to 13000 and TCP port to 13001 | Python | mit | walkover/auto-tracking-cctv-gateway | ---
+++
@@ -2,5 +2,5 @@
CAMERA_NETWORK_TCP_PORT = 9090
MOBILE_NETWORK_IP = '0.0.0.0'
-MOBILE_NETWORK_HTTP_PORT = 80
-MOBILE_NETWORK_TCP_PORT = 13000
+MOBILE_NETWORK_HTTP_PORT = 13000
+MOBILE_NETWORK_TCP_PORT = 13001 |
a02f2a1ba8f2cbf0cda0a6b8b794c4970bb4b4f2 | hackfmi/urls.py | hackfmi/urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Unc... | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include... | Add url for media files | Add url for media files
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -1,4 +1,5 @@
from django.conf.urls import patterns, include, url
+from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
@@ -14,4 +15,6 @@
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls))... |
9eae7b3ae0701716621cad8e88d4737cad4523d8 | scripts/json-to-rsf/json2rsf.py | scripts/json-to-rsf/json2rsf.py | import sys
from datetime import datetime
import json
import hashlib
def print_rsf(item, key_field):
key = item[key_field]
timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
item_str = json.dumps(item, separators=(',', ':'), sort_keys=True)
item_hash = hashlib.sha256(item_str.encode("utf-8"))... | import sys
from datetime import datetime
import json
import hashlib
def print_rsf(item, key_field):
key = item[key_field]
timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
item_str = json.dumps(item, separators=(',', ':'), sort_keys=True)
item_hash = hashlib.sha256(item_str.encode("utf-8"))... | Update to use new RSF `append-entry` format | Update to use new RSF `append-entry` format
| Python | mit | openregister/openregister-java,openregister/openregister-java,openregister/openregister-java,openregister/openregister-java,openregister/openregister-java | ---
+++
@@ -10,7 +10,7 @@
item_str = json.dumps(item, separators=(',', ':'), sort_keys=True)
item_hash = hashlib.sha256(item_str.encode("utf-8")).hexdigest()
item_line = "add-item\t" + item_str
- entry_line = "append-entry\t{0}\t{1}\tsha-256:{2}".format(
+ entry_line = "append-entry\tuser\t{0}\t{... |
4095b95930a57e78e35592dba413a776959adcde | logistic_order/model/sale_order.py | logistic_order/model/sale_order.py | # -*- coding: utf-8 -*-
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
... | # -*- coding: utf-8 -*-
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
... | Rename state of SO according to LO and Cost Estimate | [IMP] Rename state of SO according to LO and Cost Estimate
| Python | agpl-3.0 | yvaucher/vertical-ngo,mdietrichc2c/vertical-ngo,jorsea/vertical-ngo,gurneyalex/vertical-ngo,jorsea/vertical-ngo,jgrandguillaume/vertical-ngo | ---
+++
@@ -30,4 +30,16 @@
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
+ 'state': fields.selection([
+ ('draft', 'Draft Cost Estimate'),
+ ('sent', 'Cost Estimate Sent'),
... |
be8b6e9b3cd81a22d85046c769e0d267b41004e3 | MoMMI/types.py | MoMMI/types.py | class SnowflakeID(int):
"""
Represents a Discord Snowflake ID.
"""
pass
| from typing import Union
class SnowflakeID(int):
"""
Represents a Discord Snowflake ID.
"""
pass
MIdentifier = Union[SnowflakeID, str]
| Add string and snowflake identifier union. | Add string and snowflake identifier union.
| Python | mit | PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI | ---
+++
@@ -1,5 +1,10 @@
+from typing import Union
+
+
class SnowflakeID(int):
"""
Represents a Discord Snowflake ID.
"""
pass
+
+MIdentifier = Union[SnowflakeID, str] |
e10af1954feb6834da02ab5e641f0fe7a1785b0e | soapbox/templatetags/soapbox.py | soapbox/templatetags/soapbox.py | from django import template
from soapbox.models import Message
register = template.Library()
class MessagesForPageNode(template.Node):
def __init__(self, url, varname):
self.url = template.Variable(url)
self.varname = varname
def render(self, context):
try:
url = self.u... | from django import template
from ..models import Message
register = template.Library()
class MessagesForPageNode(template.Node):
def __init__(self, url, varname):
self.url = template.Variable(url)
self.varname = varname
def render(self, context):
try:
url = self.url.res... | Clean up the template tags module a bit. | Clean up the template tags module a bit.
| Python | bsd-3-clause | ubernostrum/django-soapbox,ubernostrum/django-soapbox | ---
+++
@@ -1,6 +1,6 @@
from django import template
-from soapbox.models import Message
+from ..models import Message
register = template.Library()
@@ -20,8 +20,9 @@
return ''
+@register.tag
def get_messages_for_page(parser, token):
bits = token.split_contents()
if len(bits) != 4 or bi... |
5c43036e44e94d55c86567d4e98689acde0510e5 | app/py/cuda_sort/sort_sep.py | app/py/cuda_sort/sort_sep.py | from cudatext import *
def _sort(s, sep_k, sep_v):
if not sep_k in s:
return s
key, val = s.split(sep_k, 1)
vals = sorted(val.split(sep_v))
return key+sep_k+sep_v.join(vals)
def do_sort_sep_values():
while 1:
res = dlg_input_ex(2,
'Sort: separator chars',
... | from cudatext import *
def _sort(s, sep_k, sep_v):
if sep_k:
if not sep_k in s:
return s
key, val = s.split(sep_k, 1)
vals = sorted(val.split(sep_v))
return key+sep_k+sep_v.join(vals)
else:
vals = sorted(s.split(sep_v))
return sep_v.join(vals)
def ... | Sort new cmd: allow empty separator | Sort new cmd: allow empty separator
| Python | mpl-2.0 | Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText | ---
+++
@@ -2,24 +2,33 @@
def _sort(s, sep_k, sep_v):
- if not sep_k in s:
- return s
- key, val = s.split(sep_k, 1)
- vals = sorted(val.split(sep_v))
- return key+sep_k+sep_v.join(vals)
+ if sep_k:
+ if not sep_k in s:
+ return s
+ key, val = s.split(sep_k, 1)
+ ... |
5e80122c20e04b9208f6bc4ce13bc7ab7f757ff8 | web/impact/impact/v1/helpers/matching_criterion_helper.py | web/impact/impact/v1/helpers/matching_criterion_helper.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._t... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.db.models import Q
from impact.v1.helpers.criterion_helper import CriterionHelper
class MatchingCriterionHelper(CriterionHelper):
def __init__(self, subject):
super().__init__(subject)
self._app_ids_to_targets = {}
self._t... | Remove dead code and minor refactor | [AC-5625] Remove dead code and minor refactor
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -14,12 +14,6 @@
def app_count(self, apps, option_name):
return self.target_counts(apps).get(option_name, 0)
- def refine_feedbacks(self, feedbacks, target, refinement):
- if not target:
- return None
- query = Q(**{refinement: target})
- return feedbacks.f... |
ba8939167379633b5b572cd7b70c477f101b95dd | application.py | application.py | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
application = create_app(os.getenv('FLASH_CONFIG') or 'default')
manager = Manager(application)
manager.add_command("runserver", Server(port=5003))
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
application = create_app(
os.getenv('DM_SUPPLIER_FRONTEND_ENVIRONMENT') or 'default'
)
manager = Manager(application)
manager.add_command("runserver", Server(port=5003))
if __name__ == '__main__':
manager.... | Rename FLASH_CONFIG to match common convention | Rename FLASH_CONFIG to match common convention
| Python | mit | mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphag... | ---
+++
@@ -4,7 +4,9 @@
from app import create_app
from flask.ext.script import Manager, Server
-application = create_app(os.getenv('FLASH_CONFIG') or 'default')
+application = create_app(
+ os.getenv('DM_SUPPLIER_FRONTEND_ENVIRONMENT') or 'default'
+)
manager = Manager(application)
manager.add_command("runs... |
4ab6009a01f71abaff72db7311f3a74d88ec524c | examples/pax_mininet_node.py | examples/pax_mininet_node.py | # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __in... | # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __in... | Disable ip_forward in the Pax Mininet node class | Disable ip_forward in the Pax Mininet node class
| Python | apache-2.0 | niksu/pax,TMVector/pax,niksu/pax,TMVector/pax,niksu/pax | ---
+++
@@ -21,11 +21,14 @@
# to prevent the OS from handling them and responding.
print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man"
for intf in self.intfList():
- self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
+ sel... |
e042101c8f4c5ef06e590a47114778a0cf06d4f0 | oh_bot/lookup_discussion_topics.py | oh_bot/lookup_discussion_topics.py | import logging
import time
import os
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
def build_response(message):
topics = ""
for i, j in enumerate(message['Items']):
topics += "{0}: {1}\n".format(i + 1, j['topic'])
return {
"dialogActio... | import logging
import time
import os
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
def build_response(message):
topics = ""
for i, j in enumerate(message['Items']):
topics += "{0}: {1}\n".format(i + 1, j['topic'])
if not topics:
topics... | Add response if no topics are set | Add response if no topics are set
| Python | mit | silvermullet/oh-bot,silvermullet/oh-bot,silvermullet/oh-bot | ---
+++
@@ -11,6 +11,9 @@
topics = ""
for i, j in enumerate(message['Items']):
topics += "{0}: {1}\n".format(i + 1, j['topic'])
+
+ if not topics:
+ topics = "No topics for this date have been set"
return {
"dialogAction": { |
5d634511af87150cf1e1b57c52b2bb7136890eb4 | twilix/cmd.py | twilix/cmd.py | import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if path[0] == '~':
path[0] = os.path.expanduser(path[0])
os.chdir(path[0])
return run_pwd()
def cmd_mkdir(*args... | import os
import subprocess
import errno
def cmd_pwd(*args):
return subprocess.check_output(['pwd'])
def cmd_ls(*args):
return subprocess.check_output(*args)
def cmd_cd(*args):
if args[0][1] == '~':
args[0][1] = os.path.expanduser(args[0][1])
os.chdir(args[0][1])
return cmd_pwd()
def cmd... | Add option tu run piped commands | Add option tu run piped commands
| Python | mit | ueg1990/twilix,ueg1990/twilix | ---
+++
@@ -9,28 +9,35 @@
return subprocess.check_output(*args)
def cmd_cd(*args):
- if path[0] == '~':
- path[0] = os.path.expanduser(path[0])
- os.chdir(path[0])
- return run_pwd()
+ if args[0][1] == '~':
+ args[0][1] = os.path.expanduser(args[0][1])
+ os.chdir(args[0][1])
+ ... |
c5467b2ad4fbb0dbc37809df077e5c69915489c9 | go_cli/send.py | go_cli/send.py | """ Send messages via an HTTP API (nostream) conversation. """
import click
from go_http.send import HttpApiSender
@click.option(
'--conversation', '-c',
help='HTTP API conversation key')
@click.option(
'--token', '-t',
help='HTTP API conversation token')
@click.option(
'--csv', type=click.File(... | """ Send messages via an HTTP API (nostream) conversation. """
import csv
import json
import click
from go_http.send import HttpApiSender
@click.option(
'--conversation', '-c',
help='HTTP API conversation key')
@click.option(
'--token', '-t',
help='HTTP API conversation token')
@click.option(
'... | Add CSV and JSON parsing. | Add CSV and JSON parsing.
| Python | bsd-3-clause | praekelt/go-cli,praekelt/go-cli | ---
+++
@@ -1,4 +1,7 @@
""" Send messages via an HTTP API (nostream) conversation. """
+
+import csv
+import json
import click
@@ -23,7 +26,33 @@
def send(ctx, conversation, token, csv, json):
""" Send messages via an HTTP API (nostream) conversation.
"""
+ if not any((csv, json)):
+ click.... |
a154db2de427a31746c51c39077c6020f70478b6 | export.py | export.py | #! /usr/bin/env python3
import sqlite3
import bcrypt
import hashlib
from Crypto.Cipher import AES
import codecs
import json
from password import encrypt, decrypt, toHex, fromHex
pwdatabase = 'passwords.db'
jsonfile = open('passwords.json', mode='w')
password = input('Enter password: ')
conn = sqlite3.connect(pwdata... | #! /usr/bin/env python3
import sqlite3
import bcrypt
import hashlib
from Crypto.Cipher import AES
import codecs
import json
from password import encrypt, decrypt, toHex, fromHex
pwdatabase = 'passwords.db'
jsonfile = open('passwords.json', mode='w')
password = input('Enter password: ')
conn = sqlite3.connect(pwdata... | Print encrypted records for debugging. | Print encrypted records for debugging.
| Python | mit | tortxof/cherry-password,tortxof/cherry-password,tortxof/cherry-password | ---
+++
@@ -20,6 +20,7 @@
print('Password is correct.')
aes_key = toHex(bcrypt.kdf(password, salt, 16, 32))
records = [list(i) for i in conn.execute('select * from passwords')]
+ print(records)
for i in range(len(records)):
records[i][3] = decrypt(aes_key, records[i][3]).decode()
... |
24f198ce9a5558627b004a38eb81ae91ae749116 | examples/connection.py | examples/connection.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Rename list_flavors flavors in example | Rename list_flavors flavors in example
Change-Id: Idf699774484a29fa9e9bb1bf654ed00d6ca9907d
| Python | apache-2.0 | dtroyer/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openstacksdk,dudymas/python-openstacksdk,dudymas/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-opens... | ---
+++
@@ -38,7 +38,7 @@
def run_connection(opts):
conn = make_connection(opts)
print("Connection: %s" % conn)
- for flavor in conn.compute.list_flavors():
+ for flavor in conn.compute.flavors():
print(flavor.id + " " + flavor.name)
return
|
b60f74bfa84d02d7a868905de12f16e715dfca98 | iacli/argparser.py | iacli/argparser.py | from collections import defaultdict
# get_args_dict()
#_________________________________________________________________________________________
def get_args_dict(args):
metadata = defaultdict(list)
for md in args:
key, value = md.split(':')
metadata[key].append(value)
# Flatten single it... | from collections import defaultdict
# get_args_dict()
#_________________________________________________________________________________________
def get_args_dict(args):
metadata = defaultdict(list)
for md in args:
key, value = md.split(':', 1)
metadata[key].append(value)
# Flatten single... | Allow for ":" in argument values (only split args on first occurence of ":". | Allow for ":" in argument values (only split args on first occurence of ":".
| Python | agpl-3.0 | dattasaurabh82/internetarchive,wumpus/internetarchive,brycedrennan/internetarchive,JesseWeinstein/internetarchive,jjjake/internetarchive | ---
+++
@@ -7,7 +7,7 @@
def get_args_dict(args):
metadata = defaultdict(list)
for md in args:
- key, value = md.split(':')
+ key, value = md.split(':', 1)
metadata[key].append(value)
# Flatten single item lists.
for key, value in metadata.items(): |
bd1ebf9dd9678c6c17826487f43e9c762b9bd1f0 | plumbium/recorders/csvfile.py | plumbium/recorders/csvfile.py | import os
import csv
class CSVFile(object):
def __init__(self, path, values):
self.path = path
self.values = values
def write(self, results):
field_names = self.values.keys()
write_header = not os.path.exists(self.path)
with open(self.path, 'a') as output_file:
... | import os
import csv
class CSVFile(object):
def __init__(self, path, values):
self.path = path
self.values = values
def write(self, results):
field_names = self.values.keys()
write_header = not os.path.exists(self.path)
with open(self.path, 'a') as output_file:
... | Fix a couple of PEP8 issues | Fix a couple of PEP8 issues
| Python | mit | jstutters/Plumbium | ---
+++
@@ -1,5 +1,6 @@
import os
import csv
+
class CSVFile(object):
def __init__(self, path, values):
@@ -15,5 +16,5 @@
writer.writeheader()
row = {}
for field in self.values:
- row[field]= self.values[field](results)
+ row[field] = ... |
7244f571d3c03cbf89d67a44c8c21b7ace893362 | mediacloud/mediawords/db/schema/test_version.py | mediacloud/mediawords/db/schema/test_version.py | from nose.tools import assert_raises
from mediawords.db.schema.version import *
def test_schema_version_from_lines():
assert_raises(SchemaVersionFromLinesException, schema_version_from_lines, 'no version')
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
assert schema_version_from_lines("""... | from nose.tools import assert_raises
from mediawords.db.schema.version import *
def test_schema_version_from_lines():
assert_raises(McSchemaVersionFromLinesException, schema_version_from_lines, 'no version')
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
assert schema_version_from_lines("... | Prepend “Mc” to expected exception name | Prepend “Mc” to expected exception name
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | ---
+++
@@ -4,7 +4,7 @@
def test_schema_version_from_lines():
- assert_raises(SchemaVersionFromLinesException, schema_version_from_lines, 'no version')
+ assert_raises(McSchemaVersionFromLinesException, schema_version_from_lines, 'no version')
# noinspection SqlDialectInspection,SqlNoDataSourceInspe... |
dfdc59e0203aadb96984fb155acea34fdca2b548 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Tomas Krehlik
# Copyright (c) 2014 Tomas Krehlik
#
# License: MIT
#
"""This module exports the Julialint plugin class."""
from SublimeLinter.lint import Linter, util
class Julialint(Linter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Tomas Krehlik
# Copyright (c) 2014 Tomas Krehlik
#
# License: MIT
#
"""This module exports the Julialint plugin class."""
from SublimeLinter.lint import Linter, util
class Julialint(Linter):
"""Provides an in... | Fix the travis issues 2 | Fix the travis issues 2
| Python | mit | tomaskrehlik/SublimeLinter-contrib-julialint,tomaskrehlik/SublimeLinter-contrib-julialint | ---
+++
@@ -12,11 +12,10 @@
from SublimeLinter.lint import Linter, util
+
class Julialint(Linter):
-
"""Provides an interface to julialint."""
-
syntax = 'julia'
cmd = ['julia', '-e', 'using Lint; lintfile(ARGS[1])'] |
6663f7baefd68a059c963d464afaf3fcbfbdf2db | tests/markdown/MarkdownBearTest.py | tests/markdown/MarkdownBearTest.py | from bears.markdown.MarkdownBear import MarkdownBear
from coalib.testing.LocalBearTestHelper import verify_local_bear
test_file1 = """1. abc
1. def
"""
test_file2 = """1. abc
2. def
"""
test_file3 = """1. abcdefghijklm
2. nopqrstuvwxyz
"""
MarkdownBearTest = verify_local_bear(MarkdownBear,
... | import unittest
from queue import Queue
from bears.markdown.MarkdownBear import MarkdownBear
from coalib.testing.BearTestHelper import generate_skip_decorator
from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
from coalib.settings.S... | Add test to check message for error | MarkdownBear: Add test to check message for error
A better test for MarkdownBear to check the exact message
of the result for a maximum line length error.
Related to https://github.com/coala/coala-bears/issues/1235
| Python | agpl-3.0 | Asnelchristian/coala-bears,damngamerz/coala-bears,aptrishu/coala-bears,srisankethu/coala-bears,incorrectusername/coala-bears,yash-nisar/coala-bears,Shade5/coala-bears,madhukar01/coala-bears,naveentata/coala-bears,shreyans800755/coala-bears,damngamerz/coala-bears,Vamshi99/coala-bears,shreyans800755/coala-bears,horczech/... | ---
+++
@@ -1,5 +1,13 @@
+import unittest
+from queue import Queue
+
from bears.markdown.MarkdownBear import MarkdownBear
-from coalib.testing.LocalBearTestHelper import verify_local_bear
+from coalib.testing.BearTestHelper import generate_skip_decorator
+from coalib.testing.LocalBearTestHelper import verify_local_b... |
2b4ab7d50ae200afd47310c88f1e59977ef8f1e3 | flask_nav/renderers.py | flask_nav/renderers.py | from flask import current_app
from dominate import tags
from visitor import Visitor
class BaseRenderer(Visitor):
def visit_object(self, node):
if current_app.debug:
return '<!-- no implementation in {} to render {} -->'.format(
self.__class__.__name__, node.__class__.__name__,... | from flask import current_app
from dominate import tags
from visitor import Visitor
class BaseRenderer(Visitor):
def visit_object(self, node):
if current_app.debug:
return tags.comment(
'no implementation in {} to render {}'.format(
self.__class__.__name__,... | Use dominate to render comments as well. | Use dominate to render comments as well.
| Python | mit | mbr/flask-nav,mbr/flask-nav | ---
+++
@@ -7,9 +7,10 @@
class BaseRenderer(Visitor):
def visit_object(self, node):
if current_app.debug:
- return '<!-- no implementation in {} to render {} -->'.format(
- self.__class__.__name__, node.__class__.__name__,
- )
+ return tags.comment(
+ ... |
deadcc641c0ff544e8074ad79808d3ce292892a3 | open_folder.py | open_folder.py | import os, platform
# I intend to hide the Operating Specific details of opening a folder
# here in this module.
#
# On Mac OS X you do this with "open"
# e.g. "open '\Users\golliher\Documents\Tickler File'"
# On Windows you do this with "explorer"
# e.g. "explorer c:\Documents and Settings\Tickler File"
def op... | import os, platform
# I intend to hide the Operating Specific details of opening a folder
# here in this module.
#
# On Mac OS X you do this with "open"
# e.g. "open '\Users\golliher\Documents\Tickler File'"
# On Windows you do this with "explorer"
# e.g. "explorer c:\Documents and Settings\Tickler File"
# On Lin... | Raise exception if we don't know how to handle users operating system | Raise exception if we don't know how to handle users operating system | Python | mit | golliher/dg-tickler-file | ---
+++
@@ -6,13 +6,21 @@
# e.g. "open '\Users\golliher\Documents\Tickler File'"
# On Windows you do this with "explorer"
# e.g. "explorer c:\Documents and Settings\Tickler File"
+# On Linux xdg-open is a desktop-independant tool
+
+def open_folder(path):
+ '''Runs operating specific command to open a folde... |
e92b45ad68b665095cfce5daea7ff82550fcbfb1 | psqtraviscontainer/printer.py | psqtraviscontainer/printer.py | # /psqtraviscontainer/printer.py
#
# Utility functions for printing unicode text.
#
# See /LICENCE.md for Copyright information
"""Utility functions for printing unicode text."""
import sys
def unicode_safe(text):
"""Print text to standard output, handle unicode."""
# Don't trust non-file like replacements o... | # /psqtraviscontainer/printer.py
#
# Utility functions for printing unicode text.
#
# See /LICENCE.md for Copyright information
"""Utility functions for printing unicode text."""
import sys
def unicode_safe(text):
"""Print text to standard output, handle unicode."""
# If a replacement of sys.stdout doesn't h... | Check for the isatty property on sys.stdout. | Check for the isatty property on sys.stdout.
Previously we were checking to see if it was of type "file", but
the type changed between python 2 and 3. Really, all we want
to do is check if it is a tty and if we can't be sure of that,
don't enable utf8 output.
| Python | mit | polysquare/polysquare-travis-container | ---
+++
@@ -10,9 +10,8 @@
def unicode_safe(text):
"""Print text to standard output, handle unicode."""
- # Don't trust non-file like replacements of sys.stdout, assume
- # that they can only handle ascii.
- if sys.stdout.__class__ is not file or not sys.stdout.isatty():
+ # If a replacement of sys... |
4e584b66db979878d413cfae4e6e9d085d40f811 | main/modelx.py | main/modelx.py | # -*- coding: utf-8 -*-
import hashlib
class BaseX(object):
@classmethod
def retrieve_one_by(cls, name, value):
cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)
if cls_db_list:
return cls_db_list[0]
return None
class ConfigX(object):
@classmethod
def get_master_db(cls):
r... | # -*- coding: utf-8 -*-
import hashlib
class BaseX(object):
@classmethod
def retrieve_one_by(cls, name, value):
cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)
if cls_db_list:
return cls_db_list[0]
return None
class ConfigX(object):
@classmethod
def get_master_db(cls):
r... | Support for size of gravatar image | Support for size of gravatar image
Added support for the size (s) argument in the Gravatar API | Python | mit | tonyin/optionstg,gae-init/gae-init-babel,d4rr3ll/gae-init-docker,lipis/the-smallest-creature,lipis/the-smallest-creature,lipis/the-smallest-creature,gmist/alice-box,gae-init/gae-init-upload,mdxs/gae-init,mdxs/gae-init,lovesoft/gae-init,wilfriedE/gae-init,JoeyCodinja/INFO3180LAB3,topless/gae-init,gmist/five-studio2,geor... | ---
+++
@@ -20,7 +20,8 @@
class UserX(object):
@property
- def avatar_url(self):
- return '//gravatar.com/avatar/%s?d=identicon&r=x' % (
- hashlib.md5((self.email or self.name).encode('utf-8')).hexdigest().lower()
+ def avatar_url(self, size=80):
+ return '//gravatar.com/avatar/%s?d=identicon&r=x... |
edae0479d4de3c8c1d61f80ea5366c075b807125 | mooch/banktransfer.py | mooch/banktransfer.py | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals import post_charge
class BankTransf... | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals imp... | Set charged_at when confirming a bank transfer | Set charged_at when confirming a bank transfer
| Python | mit | matthiask/django-mooch,matthiask/django-mooch,matthiask/django-mooch | ---
+++
@@ -2,6 +2,7 @@
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
+from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
@@ -27,6 +28,... |
d63480d00206a08a3e41c6af7512181198aced05 | object_join.py | object_join.py | __author__ = 'stuart'
class JoinedObject(object):
def __init__(self, left, right):
self.left = left
self.right = right
def __getattr__(self, attr):
if attr == 'left':
return self.left
elif attr == 'right':
return self.right
else:
ret... | __author__ = 'stuart'
class JoinedObject(object):
def __init__(self, left, right):
self.left = left
self.right = right
def __getattr__(self, attr):
if attr == 'left':
return self.left
elif attr == 'right':
return self.right
else:
ret... | Add proper `__dir__` reporting, fix bug in AttributeError | Add proper `__dir__` reporting, fix bug in AttributeError
| Python | mit | StuartAxelOwen/datastreams | ---
+++
@@ -19,6 +19,10 @@
self.left.__class__.__name__ + self.right.__class__.__name__,
id(self))
+ def __dir__(self):
+ attrs = list(set(dir(self.left) + dir(self.right) + ['left', 'right']))
+ return sorted(attrs)
+
def get_from_sources(self, attr):
if has... |
403250e91905079c7480bb8ea54cf2d2a301022f | moto/s3/urls.py | moto/s3/urls.py | from .responses import S3ResponseInstance
url_bases = [
"https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3.amazonaws.com"
]
url_paths = {
'{0}/$': S3ResponseInstance.bucket_response,
'{0}/(?P<key_name>[a-zA-Z0-9\-_.]+)': S3ResponseInstance.key_response,
}
| from .responses import S3ResponseInstance
url_bases = [
"https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3.amazonaws.com"
]
url_paths = {
'{0}/$': S3ResponseInstance.bucket_response,
'{0}/(?P<key_name>.+)': S3ResponseInstance.key_response,
}
| Fix S3 URL Regex to allow slashes in key names. | Fix S3 URL Regex to allow slashes in key names.
| Python | apache-2.0 | heddle317/moto,gjtempleton/moto,rocky4570/moto,jszwedko/moto,dbfr3qs/moto,okomestudio/moto,whummer/moto,2rs2ts/moto,Brett55/moto,ZuluPro/moto,whummer/moto,kefo/moto,ZuluPro/moto,botify-labs/moto,rocky4570/moto,rocky4570/moto,whummer/moto,spulec/moto,Brett55/moto,william-richard/moto,2rs2ts/moto,rocky4570/moto,jrydberg/... | ---
+++
@@ -6,5 +6,5 @@
url_paths = {
'{0}/$': S3ResponseInstance.bucket_response,
- '{0}/(?P<key_name>[a-zA-Z0-9\-_.]+)': S3ResponseInstance.key_response,
+ '{0}/(?P<key_name>.+)': S3ResponseInstance.key_response,
} |
802bed896c147fc6bb6dc72f62a80236bc3cd263 | soccermetrics/rest/resources/personnel.py | soccermetrics/rest/resources/personnel.py | from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on all personnel involved in a football match – players,
managers, and matc... | from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on the following personnel involved in a football match:
* Players,
... | Remove stray non-ASCII character in docstring | Remove stray non-ASCII character in docstring
| Python | mit | soccermetrics/soccermetrics-client-py | ---
+++
@@ -5,8 +5,11 @@
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
- data on all personnel involved in a football match – players,
- managers, and match referees.
+ data on the following personnel invol... |
8068afed19a6596a5fbed364c19571c44970fc67 | src/poliastro/tests/test_jit.py | src/poliastro/tests/test_jit.py | from poliastro import jit
def _fake_numba_import():
# Black magic, beware
# https://stackoverflow.com/a/2484402/554319
import sys
class FakeImportFailure:
def __init__(self, modules):
self.modules = modules
def find_module(self, fullname, *args, **kwargs):
if ... | from contextlib import contextmanager
from poliastro import jit
@contextmanager
def _fake_numba_import():
# Black magic, beware
# https://stackoverflow.com/a/2484402/554319
import sys
class FakeImportFailure:
def __init__(self, modules):
self.modules = modules
def find_m... | Make numba fake import robust | Make numba fake import robust
| Python | mit | anhiga/poliastro,newlawrence/poliastro,Juanlu001/poliastro,newlawrence/poliastro,Juanlu001/poliastro,anhiga/poliastro,poliastro/poliastro,Juanlu001/poliastro,anhiga/poliastro,newlawrence/poliastro | ---
+++
@@ -1,6 +1,9 @@
+from contextlib import contextmanager
+
from poliastro import jit
+@contextmanager
def _fake_numba_import():
# Black magic, beware
# https://stackoverflow.com/a/2484402/554319
@@ -26,6 +29,12 @@
sys.meta_path.insert(0, fail_loader)
+ yield
+
+ sys.meta_path.remo... |
4a62214f0c9e8789b8453a48c0a880c4ac6236cb | saleor/product/migrations/0123_auto_20200904_1251.py | saleor/product/migrations/0123_auto_20200904_1251.py | # Generated by Django 3.1 on 2020-09-04 12:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("product", "0122_auto_20200828_1135"),
]
operations = [
migrations.AlterUniqueTogether(
name="variantimage", unique_together={("variant", "... | # Generated by Django 3.1 on 2020-09-04 12:51
from django.db import migrations
from django.db.models import Count
def remove_variant_image_duplicates(apps, schema_editor):
ProductImage = apps.get_model("product", "ProductImage")
VariantImage = apps.get_model("product", "VariantImage")
duplicated_images ... | Drop duplicated VariantImages before migration to unique together | Drop duplicated VariantImages before migration to unique together
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -1,6 +1,27 @@
# Generated by Django 3.1 on 2020-09-04 12:51
from django.db import migrations
+from django.db.models import Count
+
+
+def remove_variant_image_duplicates(apps, schema_editor):
+ ProductImage = apps.get_model("product", "ProductImage")
+ VariantImage = apps.get_model("product", "Va... |
874acdfcca178759e39c154f5f2c844710db7ab0 | json_field/__init__.py | json_field/__init__.py | try:
from json_field.fields import JSONField
except ImportError:
pass # fails when imported by setup.py, no worries
__version__ = '0.4.2'
| from django.core.exceptions import ImproperlyConfigured
try:
from json_field.fields import JSONField
except (ImportError, ImproperlyConfigured):
pass # fails when imported by setup.py, no worries
__version__ = '0.4.2'
| Fix install with Django 1.5. | Fix install with Django 1.5.
| Python | bsd-3-clause | doordash/django-json-field,hoh/django-json-field,EyePulp/django-json-field,derek-schaefer/django-json-field,matllubos/django-json-field | ---
+++
@@ -1,6 +1,7 @@
+from django.core.exceptions import ImproperlyConfigured
try:
from json_field.fields import JSONField
-except ImportError:
+except (ImportError, ImproperlyConfigured):
pass # fails when imported by setup.py, no worries
__version__ = '0.4.2' |
770c898e205e1c927e3371402a3ebba32471d4a7 | actions/run.py | actions/run.py | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... | Remove extraneous logging and bad param | Remove extraneous logging and bad param
| Python | apache-2.0 | DoriftoShoes/activecampaign | ---
+++
@@ -20,14 +20,13 @@
params = self._format_params(params)
data = urllib.urlencode(params)
- self.logger.info(data)
response = requests.get(url=url,
headers=headers, params=data)
results = response.json()
if results['result... |
cf248e9c5ea0091ea8262c865d65bde9be267d89 | backend/uclapi/uclapi/urls.py | backend/uclapi/uclapi/urls.py | """uclapi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """uclapi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | Remove versioning from URL scheme | Remove versioning from URL scheme
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | ---
+++
@@ -19,5 +19,5 @@
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^dashboard/', include('dashboard.urls')),
- url(r'^v0/roombookings/', include('roombookings.urls')),
+ url(r'^roombookings/', include('roombookings.urls')),
] |
13173bffbffeb5e7b30f5b14351a7d33f0a3b110 | examples/translations/portuguese_test_1.py | examples/translations/portuguese_test_1.py | # Portuguese Language Test
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
... | # Portuguese Language Test
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
... | Update the Portuguese example test | Update the Portuguese example test
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -7,17 +7,17 @@
self.abrir("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
- self.js_digitar("#searchform input", "João Pessoa")
+ self.digitar("#searchform input", "João Pessoa")
sel... |
615d036c6735d94609d6398dff676cd8e3a8f58a | app/__init__.py | app/__init__.py | import os
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
applic... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
... | Set static path for the Flask app | Set static path for the Flask app
| Python | mit | alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace... | ---
+++
@@ -1,4 +1,3 @@
-import os
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
@@ -11,7 +10,10 @@
def create_app(config_name):
- application = Flask(__name__)
+ application = Flask(__name__,
+ static_folder='static/',
+ ... |
c86c90f5be35359b5bd87b956bdd0d7d0021cfea | busstops/management/commands/import_scotch_operator_contacts.py | busstops/management/commands/import_scotch_operator_contacts.py | """
Usage:
./manage.py import_scotch_operator_contacts < NOC_DB.csv
"""
import requests
from ..import_from_csv import ImportFromCSVCommand
from ...models import Operator
class Command(ImportFromCSVCommand):
scotch_operators = {
operator['code']: operator
for operator in requests.get('http://... | """
Usage:
./manage.py import_scotch_operator_contacts < NOC_DB.csv
"""
import requests
from ..import_from_csv import ImportFromCSVCommand
from ...models import Operator
class Command(ImportFromCSVCommand):
scotch_operators = {
operator['code']: operator
for operator in requests.get('http://... | Fix scotch operator contact import | Fix scotch operator contact import
| Python | mpl-2.0 | stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | ---
+++
@@ -20,7 +20,9 @@
if row['SC']:
scotch = cls.scotch_operators.get(row['SC'])
if scotch and len(row['NOCCODE']) == 4:
- operator = Operator.objects.get(pk=row['NOCCODE'])
+ operator = Operator.objects.filter(pk=row['NOCCODE']).first()
+ ... |
582428262daa447d3c4cc06c1b7961fdafd96b59 | src/zeit/content/volume/tests/test_reference.py | src/zeit/content/volume/tests/test_reference.py | import zeit.cms.content.interfaces
import zeit.content.article.edit.volume
import zeit.content.volume.testing
import zope.component
class VolumeReferenceTest(zeit.content.volume.testing.FunctionalTestCase):
def setUp(self):
from zeit.content.volume.volume import Volume
super(VolumeReferenceTest, ... | import lxml.objectify
import zeit.cms.content.interfaces
import zeit.content.article.edit.volume
import zeit.content.volume.testing
import zope.component
class VolumeReferenceTest(zeit.content.volume.testing.FunctionalTestCase):
def setUp(self):
from zeit.content.volume.volume import Volume
super... | Rewrite test to how IReference actually works | BUG-633: Rewrite test to how IReference actually works
| Python | bsd-3-clause | ZeitOnline/zeit.content.volume,ZeitOnline/zeit.content.volume | ---
+++
@@ -1,3 +1,4 @@
+import lxml.objectify
import zeit.cms.content.interfaces
import zeit.content.article.edit.volume
import zeit.content.volume.testing
@@ -9,11 +10,8 @@
def setUp(self):
from zeit.content.volume.volume import Volume
super(VolumeReferenceTest, self).setUp()
-
se... |
8be5e7f7945a47dd0cc6efb57d882f10c9686f2f | pava/demo.py | pava/demo.py | import pava
# Tell pava where it can find Java user-defined classes
pava.set_classpath(['c:/Users/laffr/PycharmProjects/pava/pava'])
try:
import java
class Out(object):
def println(self, s):
print s
java.lang.System.out = Out()
except ImportError:
pass
# Load a Java class and ca... | import os
import pava
# Tell pava where it can find Java user-defined classes
print '1. Loading Java...'
pava.set_classpath([os.path.dirname(__file__)])
try:
import java
class Out(object):
def println(self, s):
print s
java.lang.System.out = Out()
except ImportError:
pass
#
# Loa... | Make the classpath relative, not absolute and add some steps. | Make the classpath relative, not absolute and add some steps.
| Python | mit | laffra/pava,laffra/pava | ---
+++
@@ -1,8 +1,10 @@
+import os
import pava
# Tell pava where it can find Java user-defined classes
-pava.set_classpath(['c:/Users/laffr/PycharmProjects/pava/pava'])
+print '1. Loading Java...'
+pava.set_classpath([os.path.dirname(__file__)])
try:
import java
@@ -13,9 +15,30 @@
except ImportError:
... |
3a98e416f844bf9be93d704a8f7fb9caf3bf1723 | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/settings/dev.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/settings/dev.py | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Process all tasks synchronously.... | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Process all ta... | Update TEMPLATE_DEBUG to Django 1.8 version | Update TEMPLATE_DEBUG to Django 1.8 version | Python | bsd-3-clause | torchbox/cookiecutter-wagtail,torchbox/cookiecutter-wagtail,torchbox/wagtail-cookiecutter,torchbox/cookiecutter-wagtail,torchbox/cookiecutter-wagtail,torchbox/wagtail-cookiecutter,torchbox/wagtail-cookiecutter,torchbox/wagtail-cookiecutter | ---
+++
@@ -3,7 +3,7 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
-TEMPLATE_DEBUG = True
+TEMPLATES[0]['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!' |
d08973c3854d10755e156b1457972a8aaebb251b | bottle_utils/form/__init__.py | bottle_utils/form/__init__.py | """
.. module:: bottle_utils.form
:synopsis: Form processing and validation library
.. moduleauthor:: Outernet Inc <hello@outernet.is>
"""
from .exceptions import ValidationError
from .fields import (DormantField,
Field,
StringField,
PasswordField,
... | """
.. module:: bottle_utils.form
:synopsis: Form processing and validation library
.. moduleauthor:: Outernet Inc <hello@outernet.is>
"""
from .exceptions import ValidationError
from .fields import (DormantField,
Field,
StringField,
PasswordField,
... | Include LengthValidator in list of exporeted objects | Include LengthValidator in list of exporeted objects
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>
| Python | bsd-2-clause | Outernet-Project/bottle-utils | ---
+++
@@ -18,7 +18,8 @@
BooleanField,
SelectField)
from .forms import Form
-from .validators import Validator, Required, DateValidator, InRangeValidator
+from .validators import (Validator, Required, DateValidator, InRangeValidator,
+ LengthValida... |
039f6fa4b26b747432138a8bf9e2754c6daafec3 | byceps/blueprints/api/decorators.py | byceps/blueprints/api/decorators.py | """
byceps.blueprints.api.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
fro... | """
byceps.blueprints.api.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
fro... | Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended | Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -13,6 +13,7 @@
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
+from ...services.authentication.api.transfer.models import ApiToken
def api_token_required(func):
@@ -20,21 +21,28 @@
@wraps(func)
def wrapper(*args, **... |
ed4fea914435b934cf8f0539cfbf31ece15130b9 | trunk/bdp_fe/src/bdp_fe/jobconf/models.py | trunk/bdp_fe/src/bdp_fe/jobconf/models.py | from django.db import models
# Create your models here.
| """
Module bdp_fe.jobconf.models
Create your models here.
"""
from django.db import models
class Job(models.Model):
"""
A Job is a calculation to be run on the BDP
"""
date = models.DateTimeField('date created')
| Include a first model, Job | Include a first model, Job
| Python | apache-2.0 | telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform | ---
+++
@@ -1,3 +1,13 @@
+"""
+Module bdp_fe.jobconf.models
+
+Create your models here.
+"""
+
from django.db import models
-# Create your models here.
+class Job(models.Model):
+ """
+ A Job is a calculation to be run on the BDP
+ """
+ date = models.DateTimeField('date created') |
3356cd0c5c85a09107a6ba48e028a54eb5ca076c | script.py | script.py | import ast
import click
from parsing.parser import FileVisitor
@click.command()
@click.argument('code', type=click.File('rb'))
@click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file')
@click.option('--remove-builtins', default=False, is_flag=True, help='... | import ast
import click
from graphing.graph import FunctionGrapher
from parsing.parser import FileVisitor
@click.command()
@click.argument('code', type=click.File('rb'))
@click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file')
@click.option('--remove-bui... | Add graphviz file output argument | Add graphviz file output argument
| Python | mit | LaurEars/codegrapher | ---
+++
@@ -2,6 +2,7 @@
import click
+from graphing.graph import FunctionGrapher
from parsing.parser import FileVisitor
@@ -9,7 +10,8 @@
@click.argument('code', type=click.File('rb'))
@click.option('--printed', default=False, is_flag=True, help='Pretty prints the call tree for each class in the file')
@c... |
fd7eef57a562f2963500d34cbbeb607913b5bb21 | txircd/modules/extra/extban_registered.py | txircd/modules/extra/extban_registered.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class RExtbans(ModuleData):
implements(IPlugin, IModuleData)
name = "RExtbans"
# R extbans take the following forms:
# "R:*" Match any... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class RExtbans(ModuleData):
implements(IPlugin, IModuleData)
name = "RExtbans"
# R extbans take the following forms:
# "R:*" Match any... | Remove a user's statuses in all channels when they logout | Remove a user's statuses in all channels when they logout
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd | ---
+++
@@ -18,8 +18,8 @@
def actions(self):
return [
("usermatchban-R", 10, self.matchUser),
- ("user-login", 10, self.refreshUser),
- ("user-logout", 10, self.refreshUser),
+ ("user-login", 10, self.loginUser),
+ ("user-logout", 10, self.logoutU... |
b1271aed5f6f5d465fe9d250737d5074dac9d45a | tests/integration/test_mmhint.py | tests/integration/test_mmhint.py | from __future__ import print_function, division, absolute_import
import glob
import pytest
from psautohint.autohint import ACOptions, hintFiles
from .differ import main as differ
from . import make_temp_copy, DATA_DIR
class Options(ACOptions):
def __init__(self, reference, inpaths, outpaths):
super(Op... | from __future__ import print_function, division, absolute_import
import glob
import pytest
from psautohint.autohint import ACOptions, ACHintError, hintFiles
from .differ import main as differ
from . import make_temp_copy, DATA_DIR
class Options(ACOptions):
def __init__(self, reference, inpaths, outpaths):
... | Add test for incompatible masters | Add test for incompatible masters
| Python | apache-2.0 | khaledhosny/psautohint,khaledhosny/psautohint | ---
+++
@@ -3,7 +3,7 @@
import glob
import pytest
-from psautohint.autohint import ACOptions, hintFiles
+from psautohint.autohint import ACOptions, ACHintError, hintFiles
from .differ import main as differ
from . import make_temp_copy, DATA_DIR
@@ -33,3 +33,16 @@
for inpath, outpath in zip(inpaths, out... |
0aa0d4658518417f15cb58e80c5099e22ef9b806 | app/models.py | app/models.py | from flask_login import UserMixin
import spotify
import spotipy
import db_utils
import application as app
class User(UserMixin):
''' User class for Flask-Login '''
def __init__(self, user_id, username=None):
self.id = int(user_id)
self.username = username
self._spotify = None
@pro... | from flask_login import UserMixin
import spotify
import spotipy
import db_utils
import application as app
class User(UserMixin):
''' User class for Flask-Login '''
def __init__(self, user_id, username=None):
self.id = int(user_id)
self.username = username
self._spotify = None
@pro... | Fix Spotify api object creation | Fix Spotify api object creation
| Python | mit | DropMuse/DropMuse,DropMuse/DropMuse | ---
+++
@@ -28,7 +28,7 @@
db_utils.spotify_credentials_upsert(app.engine,
self.id,
self._spotify)
- return spotipy.Spotify(auth=self._spotify)
+ return spotipy.Spotify(auth=self._spotify['acces... |
9ff59c13f0c1295e9a0acd45913f00d8c9a5c0af | mongoctl/errors.py | mongoctl/errors.py | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message,cause=None):
self.message = messag... | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message, cause=None):
super(MongoctlExcepti... | Remove ref to deprecated "message" property of BaseException | Remove ref to deprecated "message" property of BaseException
| Python | mit | mongolab/mongoctl | ---
+++
@@ -5,9 +5,6 @@
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
- def __init__(self, message,cause=None):
- self.message = message
- self.cause = cause
-
- def __str__(self):
- return ... |
3a7b1ff25c5ff3a1bd86efc7f70582c8268a968d | application.py | application.py | from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h... | from flask import Flask
from flask import jsonify
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def defa... | Add /movies/<year> endpoint for dynamoDB | Add /movies/<year> endpoint for dynamoDB
| Python | mit | data-north/datanorth-api | ---
+++
@@ -1,13 +1,41 @@
from flask import Flask
-application = Flask(__name__)
+from flask import jsonify
+import boto3
+import json
+import decimal
+from boto3.dynamodb.conditions import Key, Attr
+import logging
+
+app = Flask(__name__)
+logging.basicConfig(level=logging.INFO)
+
+# Helper class to convert a Dyna... |
cf1454686a9e7e00fa11d04bc4cfe443a3ad7c96 | examples/end2end/firstserver.py | examples/end2end/firstserver.py | # Topic server
import time
import flask
app = flask.Flask(__name__)
data = []
sessions = {} # session ID -> current index # FIXME No cleanup!
@app.route("/simple/newsession")
def new_session():
session_id = "session" + hex(int(time.time() * 1000))[2:]
sessions[session_id] = 0
return session_id
@app... | # Topic server
import time
import flask
app = flask.Flask(__name__)
data = []
sessions = {} # session ID -> current index # FIXME No cleanup!
@app.route("/simple/newsession")
def new_session():
session_id = "session" + hex(int(time.time() * 1000))[2:]
sessions[session_id] = 0
return session_id
@app... | Return failure on pop() from an empty queue | Return failure on pop() from an empty queue | Python | apache-2.0 | bozzzzo/quark,datawire/quark,datawire/quark,datawire/quark,datawire/datawire-connect,bozzzzo/quark,datawire/datawire-connect,datawire/datawire-connect,bozzzzo/quark,datawire/quark,bozzzzo/quark,datawire/quark,datawire/quark,datawire/datawire-connect | ---
+++
@@ -18,17 +18,15 @@
@app.route("/simple/push/<session_id>/<value>")
def push(session_id, value):
- assert session_id in sessions
+ assert session_id in sessions # Or crash, aka return error
data.append(value)
return str(len(data) - 1)
@app.route("/simple/pop/<session_id>")
def po... |
a552697d3fb830e59720276b111996e717186842 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| Fix bug where n is the square of a prime | Fix bug where n is the square of a prime
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -6,5 +6,5 @@
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
- not_prime.update(range(i*i, n, i))
+ not_prime.update(range(i*i, n+1, i))
return prime |
6acdef03da862c6daa7d2b4cc333933afb3f912a | piper/utils.py | piper/utils.py | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | Make DotDict dict methods return those objects | Make DotDict dict methods return those objects
| Python | mit | thiderman/piper | ---
+++
@@ -14,15 +14,16 @@
return '<DotDict {}>'.format(self.data)
def __getattr__(self, key):
+ if key in ('values', 'keys', 'items'):
+ # Dict methods, just return and run them.
+ return getattr(self.data, key)
+
val = self.data[key]
if isinstance(va... |
17a28964785f3eb39f96d07968358b20be12e30e | marathon/exceptions.py | marathon/exceptions.py | class MarathonError(Exception):
pass
class MarathonHttpError(MarathonError):
def __init__(self, response):
"""
:param :class:`requests.Response` response: HTTP response
"""
content = response.json()
self.status_code = response.status_code
self.error_message = c... | class MarathonError(Exception):
pass
class MarathonHttpError(MarathonError):
def __init__(self, response):
"""
:param :class:`requests.Response` response: HTTP response
"""
self.error_message = response.reason or ''
if response.content:
content = response.j... | Handle HTTP errors without content graceful | Handle HTTP errors without content graceful
HTTP errors like 503 do not have a content set by Marathon. Try to use
the response reason string as an alternative error message.
| Python | mit | thefactory/marathon-python,thefactory/marathon-python | ---
+++
@@ -8,9 +8,11 @@
"""
:param :class:`requests.Response` response: HTTP response
"""
- content = response.json()
+ self.error_message = response.reason or ''
+ if response.content:
+ content = response.json()
+ self.error_message = content.ge... |
dabc1f4a869f8da5106248dcf860c75d1fe9f538 | geotrek/common/management/commands/update_permissions.py | geotrek/common/management/commands/update_permissions.py | import logging
from django.conf import settings
from django.utils.importlib import import_module
from django.db.models import get_apps
from django.contrib.auth.management import create_permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.c... | import logging
from django.conf import settings
from django.utils.importlib import import_module
from django.db.models import get_apps
from django.contrib.auth.management import create_permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.c... | Fix update_permission command for legacy content types | Fix update_permission command for legacy content types
| Python | bsd-2-clause | johan--/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,makinacorpus/Geotrek,mabhub/Geotrek,Anaethelion/Geot... | ---
+++
@@ -42,7 +42,8 @@
logger.info("Synchronize geotrek permissions")
for content_type in ContentType.objects.all():
- if issubclass(content_type.model_class(), BasePublishableMixin):
+ model = content_type.model_class()
+ if model and issubclass(model, BasePubl... |
60bdc3cb6d503e675f029a6d2bbf4941267a2087 | pysswords/__main__.py | pysswords/__main__.py | import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_init = parser.add_argument_group("Init options")
group_init.add_argument("-I", "--init", action="store_true")
g... | import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_db = parser.add_argument_group("Databse options")
group_db.add_argument("-I", "--init", action="store_true")
gr... | Refactor parse args db options | Refactor parse args db options
| Python | mit | scorphus/passpie,eiginn/passpie,marcwebbie/passpie,marcwebbie/pysswords,eiginn/passpie,scorphus/passpie,marcwebbie/passpie | ---
+++
@@ -9,9 +9,9 @@
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
- group_init = parser.add_argument_group("Init options")
- group_init.add_argument("-I", "--init", action="store_true")
- group_init.add_argument("-D", "--database", default=default_db())
+ group_db = ... |
b371ec9e8d1fc15c2d3e1093b305b4c8e0944694 | corehq/apps/locations/middleware.py | corehq/apps/locations/middleware.py | from .permissions import is_location_safe, location_restricted_response
class LocationAccessMiddleware(object):
"""
Many large projects want to restrict data access by location.
Views which handle that properly are called "location safe". This
middleware blocks access to any non location safe features... | from .permissions import is_location_safe, location_restricted_response
class LocationAccessMiddleware(object):
"""
Many large projects want to restrict data access by location.
Views which handle that properly are called "location safe". This
middleware blocks access to any non location safe features... | Clarify usage in docstring | Clarify usage in docstring [ci skip]
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -8,6 +8,11 @@
middleware blocks access to any non location safe features by users who
have such a restriction. If these users do not have an assigned location,
they cannot access anything.
+
+ This middleware also sets the property can_access_all_locations. This
+ property does not imp... |
2c56f31d3f730d530a0d00f8e18788671e6934b8 | kazoo/tests/test_security.py | kazoo/tests/test_security.py | import unittest
from nose.tools import eq_
import zookeeper
class TestACL(unittest.TestCase):
def _makeOne(self, *args, **kwargs):
from kazoo.security import make_acl
return make_acl(*args, **kwargs)
def test_read_acl(self):
acl = self._makeOne("digest", ":", read=True)
eq_(a... | import unittest
from nose.tools import eq_
import zookeeper
class TestACL(unittest.TestCase):
def _makeOne(self, *args, **kwargs):
from kazoo.security import make_acl
return make_acl(*args, **kwargs)
def test_read_acl(self):
acl = self._makeOne("digest", ":", read=True)
eq_(a... | Read perms off the ACL object properly | Read perms off the ACL object properly
| Python | apache-2.0 | rockerbox/kazoo,Asana/kazoo,bsanders/kazoo,rgs1/kazoo,python-zk/kazoo,rockerbox/kazoo,AlexanderplUs/kazoo,max0d41/kazoo,pombredanne/kazoo,max0d41/kazoo,harlowja/kazoo,kormat/kazoo,rgs1/kazoo,pombredanne/kazoo,tempbottle/kazoo,harlowja/kazoo,jacksontj/kazoo,bsanders/kazoo,rackerlabs/kazoo,tempbottle/kazoo,kormat/kazoo,p... | ---
+++
@@ -11,11 +11,11 @@
def test_read_acl(self):
acl = self._makeOne("digest", ":", read=True)
- eq_(acl['perms'] & zookeeper.PERM_READ, zookeeper.PERM_READ)
+ eq_(acl.perms & zookeeper.PERM_READ, zookeeper.PERM_READ)
def test_all_perms(self):
acl = self._makeOne("dig... |
b7ea2db86ad67410330d412a8733cb4dab2c4109 | partner_academic_title/models/partner_academic_title.py | partner_academic_title/models/partner_academic_title.py | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of partner_academic_title,
# an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# partner_academic_title is free software:
# you can redistribute it an... | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of partner_academic_title,
# an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# partner_academic_title is free software:
# you can redistribute it an... | Add translate=True on academic title name | Add translate=True on academic title name
| Python | agpl-3.0 | sergiocorato/partner-contact | ---
+++
@@ -29,7 +29,7 @@
class PartnerAcademicTitle(models.Model):
_name = 'partner.academic.title'
- name = fields.Char(required=True)
+ name = fields.Char(required=True, translate=True)
sequence = fields.Integer(required=True,
help="""defines the order to display t... |
bbf3e1bbb8ccd7f0408b24dd7575588f6567c807 | gastosabertos/receita/models.py | gastosabertos/receita/models.py | # -*- coding: utf-8 -*-
from sqlalchemy import Column, types
from ..extensions import db
class Revenue(db.Model):
__tablename__ = 'revenue'
id = Column(db.Integer, primary_key=True)
code = Column(db.String(), nullable=False)
description = Column(db.String(), nullable=False)
date = Column(db.Da... | # -*- coding: utf-8 -*-
from sqlalchemy import Column, types
from ..extensions import db
class Revenue(db.Model):
__tablename__ = 'revenue'
id = Column(db.Integer, primary_key=True)
code = Column(db.String(30), nullable=False)
description = Column(db.Text(), nullable=False)
date = Column(db.Da... | Change Revenu model column types for 'code' column and 'description' for MySQL | Change Revenu model column types for 'code' column and 'description' for MySQL
| Python | agpl-3.0 | nucleo-digital/gastos_abertos,andresmrm/gastos_abertos,LuizArmesto/gastos_abertos,LuizArmesto/gastos_abertos,okfn-brasil/gastos_abertos,andresmrm/gastos_abertos,okfn-brasil/gastos_abertos | ---
+++
@@ -10,8 +10,8 @@
__tablename__ = 'revenue'
id = Column(db.Integer, primary_key=True)
- code = Column(db.String(), nullable=False)
- description = Column(db.String(), nullable=False)
+ code = Column(db.String(30), nullable=False)
+ description = Column(db.Text(), nullable=False)
d... |
675b7acc6d04c6f3764f1fd148afd0a2b2134d7e | civictechprojects/sitemaps.py | civictechprojects/sitemaps.py | from common.helpers.constants import FrontEndSection
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from .models import Project
from datetime import date
class SectionSitemap(Sitemap):
protocol = "https"
changefreq = "monthly"
priority = 0.5
# TODO: Update this date for e... | from common.helpers.constants import FrontEndSection
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from .models import Project
from datetime import date
class SectionSitemap(Sitemap):
protocol = "https"
changefreq = "monthly"
priority = 0.5
# TODO: Update this date for e... | Add splash page to sitemap | Add splash page to sitemap
| Python | mit | DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange | ---
+++
@@ -11,14 +11,21 @@
priority = 0.5
# TODO: Update this date for each release
lastmod = settings.SITE_LAST_UPDATED
- sections = [FrontEndSection.AboutUs, FrontEndSection.FindProjects, FrontEndSection.PartnerWithUs, FrontEndSection.Donate,
- FrontEndSection.Press, FrontEndSectio... |
364cb2307021cc11de5a31f577e12a5f3e1f6bf6 | openpathsampling/engines/toy/snapshot.py | openpathsampling/engines/toy/snapshot.py | """
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
import openpathsampling.engines.features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature... | """
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temper... | Fix for bad merge decision | Fix for bad merge decision
| Python | mit | openpathsampling/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,openpathsampling/openpathsampling,openpathsampling/openpathsampling,choderalab/openp... | ---
+++
@@ -5,7 +5,7 @@
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
-import openpathsampling.engines.features as feats
+from openpathsampling.engines import features as feats
from . import features as toy_feats
|
7eb580d11dc8506cf656021d12884562d1a1b823 | dumper/site.py | dumper/site.py | from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
... | from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
... | Use keyword based `format` to maintain 2.6 compatibility | Use keyword based `format` to maintain 2.6 compatibility
| Python | mit | saulshanabrook/django-dumper | ---
+++
@@ -23,8 +23,8 @@
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
- ('dependent_paths on {} should return a list of paths, not a'
- 'string'.format(model_name))
+ ('dependent_paths on {model_name} should return... |
91c33bdeea9214c9594d2d3f9bd1255403d62034 | notify_levure_app_of_save.py | notify_levure_app_of_save.py | import sublime
import sublime_plugin
import re
class LevureAppNotify(sublime_plugin.EventListener):
def on_post_save(self, view):
# 1. Get script only stack name. line 1: script "Name" [done]
# 2. Get project key from project settings
# 3. Send notification over socket with project key, scr... | import sublime
import sublime_plugin
import re
import socket
import urllib
class LevureAppNotify(sublime_plugin.EventListener):
def on_post_save(self, view):
# 1. Get script only stack name. line 1: script "Name" [done]
# 2. Get project key from project settings
# 3. Send notification over ... | Send update notification to server | Send update notification to server
| Python | mit | trevordevore/livecode-sublimetext | ---
+++
@@ -1,6 +1,8 @@
import sublime
import sublime_plugin
import re
+import socket
+import urllib
class LevureAppNotify(sublime_plugin.EventListener):
def on_post_save(self, view):
@@ -19,4 +21,17 @@
if region.a >= 0:
stack_name = re.search('"([-a-zA-Z0-9_\s\?!]+)"', view.s... |
881ceeb7f814bf640caf2d7a803bfc2d350b082d | plumeria/storage/__init__.py | plumeria/storage/__init__.py | import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.cre... | import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.cre... | Make sure to set MySQL charset. | Make sure to set MySQL charset.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria | ---
+++
@@ -25,5 +25,6 @@
@bus.event('preinit')
async def preinit():
- pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True)
+ pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(),
+ ... |
89b9fb1cb14aeb99cb7c96717830898aead4fef1 | src/waldur_core/core/management/commands/createstaffuser.py | src/waldur_core/core/management/commands/createstaffuser.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... | Allow setting email when creating a staff account. | Allow setting email when creating a staff account.
Otherwise makes it hard to start using HomePort as it requires email validation.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | ---
+++
@@ -9,15 +9,19 @@
def add_arguments(self, parser):
parser.add_argument('-u', '--username', dest='username', required=True)
parser.add_argument('-p', '--password', dest='password', required=True)
+ parser.add_argument('-e', '--email', dest='email', required=True)
def handle... |
5c9e9d33113c7fcf49223853abf52f1e91b17687 | frappe/integrations/doctype/google_maps_settings/google_maps_settings.py | frappe/integrations/doctype/google_maps_settings/google_maps_settings.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
import googlemaps
import datetime
class GoogleMapsSettings(Document... | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import googlemaps
import frappe
from frappe import _
from frappe.model.document import Document
class GoogleMapsSettings(Document):
def valid... | Check if Google Maps is enabled when trying to get the client | Check if Google Maps is enabled when trying to get the client
| Python | mit | adityahase/frappe,adityahase/frappe,ESS-LLP/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,yashodhank/frappe,RicardoJohann/frappe,yashodhank/frappe,ESS-LLP/frappe,frappe/frappe,mhbu50/frappe,saurabh6790/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,yashodhank/frappe,mhbu50/frappe,vjFaLk/frappe,almeidapaul... | ---
+++
@@ -3,11 +3,13 @@
# For license information, please see license.txt
from __future__ import unicode_literals
+
+import googlemaps
+
import frappe
from frappe import _
from frappe.model.document import Document
-import googlemaps
-import datetime
+
class GoogleMapsSettings(Document):
def validate(se... |
cfc4b9d10d43da3c68503d544d96a0ea8bb5d543 | bpython/__init__.py | bpython/__init__.py | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | Bump version number and tag release | Bump version number and tag release
| Python | mit | 5monkeys/bpython | ---
+++
@@ -22,7 +22,7 @@
import os.path
-__version__ = 'mercurial'
+__version__ = '0.11'
package_dir = os.path.abspath(os.path.dirname(__file__))
|
7f0121b4ade7a14f47cbf3d1573134dffaaf86ee | src/nodeconductor_assembly_waldur/slurm_invoices/apps.py | src/nodeconductor_assembly_waldur/slurm_invoices/apps.py | from django.apps import AppConfig
from django.db.models import signals
class SlurmInvoicesConfig(AppConfig):
name = 'nodeconductor_assembly_waldur.slurm_invoices'
verbose_name = 'SLURM invoices'
def ready(self):
from nodeconductor_assembly_waldur.invoices import registrators
from waldur_s... | from django.apps import AppConfig
from django.db.models import signals
class SlurmInvoicesConfig(AppConfig):
name = 'nodeconductor_assembly_waldur.slurm_invoices'
verbose_name = 'Batch packages'
def ready(self):
from nodeconductor_assembly_waldur.invoices import registrators
from waldur_s... | Rename SLURM invoices application for better Django dashoard menu item. | Rename SLURM invoices application for better Django dashoard menu item.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -4,7 +4,7 @@
class SlurmInvoicesConfig(AppConfig):
name = 'nodeconductor_assembly_waldur.slurm_invoices'
- verbose_name = 'SLURM invoices'
+ verbose_name = 'Batch packages'
def ready(self):
from nodeconductor_assembly_waldur.invoices import registrators |
ecd7f5f46146fa9378000ac469f6eca8f64ac31d | stoq/tests/data/plugins/archiver/dummy_archiver/dummy_archiver.py | stoq/tests/data/plugins/archiver/dummy_archiver/dummy_archiver.py | #!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# Un... | #!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# Un... | Fix test signature value type for task | Fix test signature value type for task
| Python | apache-2.0 | PUNCH-Cyber/stoq | ---
+++
@@ -16,8 +16,8 @@
from typing import Optional
+from stoq.plugins import ArchiverPlugin
from stoq.data_classes import ArchiverResponse, Payload, RequestMeta
-from stoq.plugins import ArchiverPlugin
class DummyArchiver(ArchiverPlugin):
@@ -26,5 +26,5 @@
) -> Optional[ArchiverResponse]:
... |
a7337c249fef106c74b5d83684311b1be7657169 | website/settings/local-travis.py | website/settings/local-travis.py | # -*- coding: utf-8 -*-
'''Example settings/local.py file.
These settings override what's in website/settings/defaults.py
NOTE: local.py will not be added to source control.
'''
from . import defaults
DB_PORT = 27017
DEV_MODE = True
DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc.
SEAR... | # -*- coding: utf-8 -*-
'''Example settings/local.py file.
These settings override what's in website/settings/defaults.py
NOTE: local.py will not be added to source control.
'''
from . import defaults
DB_PORT = 27017
DEV_MODE = True
DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc.
SEAR... | Add ENABLE_VARNISH setting to travis settings | Add ENABLE_VARNISH setting to travis settings
| Python | apache-2.0 | brandonPurvis/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,Johnetordoff/osf.io,sloria/osf.io,asanfilippo7/osf.io,binoculars/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,RomanZWang/osf.io,emetsger/osf.io,adlius/osf.io,alexschiller/osf.io,wearpants/osf.io,CenterForOpenScience/osf.io,kwierman/osf.io,d... | ---
+++
@@ -41,3 +41,5 @@
TEST_DB_NAME = DB_NAME = 'osf_test'
VARNISH_SERVERS = ['http://localhost:8080']
+
+ENABLE_VARNISH = True |
533bb1a3e3d845a84c3f897cb490df02fb11a71f | stock_cancel/__openerp__.py | stock_cancel/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2014 Andrea Cometa All Rights Reserved.
# www.andreacometa.it
# openerp@andreacometa.it
#
# This progra... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2014 Andrea Cometa All Rights Reserved.
# www.andreacometa.it
# openerp@andreacometa.it
#
# This progra... | Set as not installable because it's broken | [FIX] stock_cancel: Set as not installable because it's broken
| Python | agpl-3.0 | archetipo/stock-logistics-workflow,damdam-s/stock-logistics-workflow,grap/stock-logistics-workflow,Endika/stock-logistics-workflow,raycarnes/stock-logistics-workflow,xpansa/stock-logistics-workflow,Antiun/stock-logistics-workflow,acsone/stock-logistics-workflow,open-synergy/stock-logistics-workflow,brain-tec/stock-logi... | ---
+++
@@ -33,6 +33,6 @@
'data': [
'stock_view.xml',
],
- 'installable': True,
+ 'installable': False,
'images': ['images/stock_picking.jpg'],
} |
aadcb7f700391d1e1b8a6442198a9a2131e6f407 | asyncio_irc/connection.py | asyncio_irc/connection.py | import asyncio
from .message import Message
class Connection:
"""
Communicates with an IRC network.
Incoming data is transformed into Message objects, and sent to `listeners`.
"""
def __init__(self, listeners, host, port, ssl=True):
self.listeners = listeners
self.host = host
... | import asyncio
from .message import Message
class Connection:
"""
Communicates with an IRC network.
Incoming data is transformed into Message objects, and sent to `listeners`.
"""
def __init__(self, listeners, host, port, ssl=True):
self.listeners = listeners
self.host = host
... | Move disconnect decision into Connection.handle | Move disconnect decision into Connection.handle
| Python | bsd-2-clause | meshy/framewirc | ---
+++
@@ -27,9 +27,6 @@
self._connected = True
while self._connected:
message = yield from self.reader.readline()
- if not message:
- self.disconnect()
- return
self.handle(message)
def disconnect(self):
@@ -40,6 +37,10 @@
... |
eb7e36629a61515778029096370ccfb41399590f | bluebottle/activities/migrations/0018_auto_20200212_1025.py | bluebottle/activities/migrations/0018_auto_20200212_1025.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-02-12 09:25
from __future__ import unicode_literals
from django.db import migrations, connection
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
from django.contrib.au... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-02-12 09:25
from __future__ import unicode_literals
from django.db import migrations, connection
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
from django.contrib.au... | Fix migration for new tenants | Fix migration for new tenants
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -26,13 +26,15 @@
anonymous = Group.objects.get(name='Anonymous')
for (app, codename) in permissions:
- permission = Permission.objects.get(
- content_type__app_label=app,
- codename=codename
- )
+ ... |
b966f81af56d9f68414e72d30b0e3b3a49011ac4 | node/lookup.py | node/lookup.py | import zmq
class QueryIdent:
def __init__(self):
self._ctx = zmq.Context()
self._socket = self._ctx.socket(zmq.REQ)
# Point to OpenBazaar Identity server for now
self._socket.connect("tcp://seed.openbazaar.org:5558")
def lookup(self, user):
self._socket.send(u... | import zmq
class QueryIdent:
def __init__(self):
self._ctx = zmq.Context()
self._socket = self._ctx.socket(zmq.REQ)
# Point to OpenBazaar Identity server for now
self._socket.connect("tcp://seed.openbazaar.org:5558")
def lookup(self, user):
self._socket.send(u... | Remove default cedes pointless search | Remove default cedes pointless search
| Python | mit | yagoulas/OpenBazaar,tortxof/OpenBazaar,im0rtel/OpenBazaar,tortxof/OpenBazaar,akhavr/OpenBazaar,saltduck/OpenBazaar,dlcorporation/openbazaar,rllola/OpenBazaar,STRML/OpenBazaar,must-/OpenBazaar,kordless/OpenBazaar,bankonme/OpenBazaar,kujenga/OpenBazaar,tortxof/OpenBazaar,freebazaar/FreeBazaar,dlcorporation/openbazaar,Ren... | ---
+++
@@ -19,5 +19,4 @@
if __name__ == "__main__":
query = QueryIdent()
- print query.lookup("caedes").encode("hex")
|
dce249d7b14c8d6438f336a3f6e34c6c62b29533 | cla_backend/urls.py | cla_backend/urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.ADMIN_ENABLED:
# Uncomment the ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.ADMIN_ENABLED:
# Uncomment the ... | Add status endpoint to admin server | Add status endpoint to admin server
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -16,6 +16,7 @@
urlpatterns += patterns(
'',
+ url(r'^status/', include('status.urls', namespace='status')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/reports/', include('reports.urls', namespace='reports')),
) |
e93fa13dc27e0590786d9b12d40145c19dbd3794 | podium/talks/models.py | podium/talks/models.py | from django.db import models
TALK_STATUS_CHOICES = (
('S', 'Submitted'),
('A', 'Approved'),
('R', 'Rejected'),
('C', 'Confirmed'),
)
class Talk(models.Model):
speaker_name = models.CharField(max_length=1000)
speaker_email = models.CharField(max_length=1000)
title = models.CharField(max_le... | from django.db import models
from django.urls import reverse
TALK_STATUS_CHOICES = (
('S', 'Submitted'),
('A', 'Approved'),
('R', 'Rejected'),
('C', 'Confirmed'),
)
class Talk(models.Model):
speaker_name = models.CharField(max_length=1000)
speaker_email = models.CharField(max_length=1000)
... | Use reverse to implement get_absolute_url. | Use reverse to implement get_absolute_url.
| Python | mit | pyatl/podium-django,pyatl/podium-django,pyatl/podium-django | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.urls import reverse
TALK_STATUS_CHOICES = (
('S', 'Submitted'),
@@ -20,7 +21,7 @@
default='S')
def get_absolute_url(self):
- return f'/talks/talks/{self.id}/'
+ return reverse('talks-talks-id', args=[self.id])
... |
77492f53bf718d01fe6166f2a2e1f57203ce6852 | class4/exercise5.py | class4/exercise5.py | from getpass import getpass
import time
from netmiko import ConnectHandler
password = getpass()
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022}
ssh_connection = ConnectHandler(**pynet_rtr2)
time.sleep(2)
ssh_connection.config_mode()
output = ... | # Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode).
from getpass import getpass
import time
from netmiko import ConnectHandler
password = getpass()
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'usern... | Use PExpect to change the logging buffer size (logging buffered <size>) on pynet-rtr2. Verify this change by examining the output of 'show run'. | Use PExpect to change the logging buffer size (logging buffered <size>) on pynet-rtr2. Verify this change by examining the output of 'show run'.
| Python | apache-2.0 | linkdebian/pynet_course | ---
+++
@@ -1,3 +1,4 @@
+# Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode).
from getpass import getpass
import time
from netmiko import ConnectHandler |
bd0c2f19558033e68a5272dd84b153ff3f6fc9b3 | py_controller_client/src/py_controller_client/waypoint_client.py | py_controller_client/src/py_controller_client/waypoint_client.py | #! /usr/bin/env python
import rospy
import actionlib
import cpp_controller_msgs.msg
def waypoint_client():
pass
if __name__ == '__main__':
try:
rospy.init_node("waypoint_client_py")
result = waypoint_client()
print "Result:", result
except rospy.ROSInterruptException as e:
... | #! /usr/bin/env python
import rospy
import actionlib
from cpp_controller_msgs.msg import *
from geometry_msgs.msg import Pose2D
def waypoint_client(waypoints = []):
# Create the client, passing the type of the action to the constructor.
client = actionlib.SimpleActionClient("waypoint_following",
... | Add a simple Python action client | [py_controller_client] Add a simple Python action client
| Python | bsd-3-clause | spmaniato/cs2024_ros_cpp_project,spmaniato/cs2024_ros_cpp_project | ---
+++
@@ -2,16 +2,46 @@
import rospy
import actionlib
-import cpp_controller_msgs.msg
-def waypoint_client():
- pass
+from cpp_controller_msgs.msg import *
+from geometry_msgs.msg import Pose2D
+def waypoint_client(waypoints = []):
+
+ # Create the client, passing the type of the action to the constru... |
6c29585d1d47ff7cafc7f4fbc03abc977211e885 | jasylibrary.py | jasylibrary.py | # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profil... | # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profil... | Fix detecting css output folder in different jasy versions | Fix detecting css output folder in different jasy versions
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur | ---
+++
@@ -15,7 +15,12 @@
def getPartUrl(part, type):
folder = ""
if type == "css":
- folder = profile.getCssFolder()
+ if hasattr(profile, "getCssFolder"):
+ # Old jasy < 1.5-beta4
+ folder = profile.getCssFolder()
+ else:
+ # New jasy >= 1.5-beta4
+ folder = profile.getCssOutputFolder()
... |
0f68cbe43506db577e08a18f97cc8cba6f7367cf | combine/manifest.py | combine/manifest.py | # Copyright (c) 2010 John Reese
# Licensed under the MIT license
import yaml
from combine import CombineError
MANIFEST_FORMAT = 1
class Manifest:
def __init__(self):
self.properties = {"manifest-format": MANIFEST_FORMAT}
self.actions = []
def add_property(self, name, value):
self.p... | # Copyright (c) 2010 John Reese
# Licensed under the MIT license
import yaml
from combine import CombineError
MANIFEST_FORMAT = 1
class Manifest:
def __init__(self):
self.properties = {"manifest-format": MANIFEST_FORMAT}
self.actions = []
def add_property(self, name, value):
self.p... | Fix issues with loading from dict | Fix issues with loading from dict
| Python | mit | redmatter/combine | ---
+++
@@ -41,11 +41,9 @@
for key, value in data.items():
if key == "actions":
for action in value:
- mft.add_action(action)
+ mft.add_action(dict(action))
else:
mft.add_property(key, value)
- for action... |
c7511d81236f2a28019d8d8e103b03e0d1150e32 | django_website/blog/admin.py | django_website/blog/admin.py | from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
admin.site.register(Entry,
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author'),
list_filter = ('is_active',),
exclude = ('summary_html', 'body_html'),
prepopulated_fields = {"s... | from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
class EntryAdmin(admin.ModelAdmin):
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author')
list_filter = ('is_active',)
exclude = ('summary_html', 'body_html')
prepopulated_fields... | Use proper ModelAdmin for blog entry | Use proper ModelAdmin for blog entry | Python | bsd-3-clause | khkaminska/djangoproject.com,nanuxbe/django,rmoorman/djangoproject.com,gnarf/djangoproject.com,relekang/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,alawnchen/djangoproject.com,vxvinh1511/djangoproject.com,nanuxbe/django,nanuxbe/django,django/djangoproject.com,xavierdutreilh/djangoproject.com,g... | ---
+++
@@ -4,9 +4,10 @@
from .models import Entry
-admin.site.register(Entry,
- list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author'),
- list_filter = ('is_active',),
- exclude = ('summary_html', 'body_html'),
+class EntryAdmin(admin.ModelAdmin):
+ list_display = ('headline'... |
3df68935d0c93135f6cf1749a6d730e3914156e1 | mint/lib/proxiedtransport.py | mint/lib/proxiedtransport.py | #
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
import urllib
from conary.repository import transport
class ProxiedTransport(transport.Transport):
"""
Transport class for contacting rUS through a proxy
"""
def __init__(self, *args, **kw):
# Override transport.XMLOpener with o... | #
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
import urllib
from conary.repository import transport
class ProxiedTransport(transport.Transport):
"""
Transport class for contacting rUS through a proxy
"""
def __init__(self, *args, **kw):
# Override transport.XMLOpener with o... | Fix latent bug in proxied XMLRPC that broke adding 5.8.x rUS (RBL-7945) | Fix latent bug in proxied XMLRPC that broke adding 5.8.x rUS (RBL-7945)
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -26,7 +26,7 @@
def request(self, *args, **kw):
resp = transport.Transport.request(self, *args, **kw)
# Return just the value.
- return resp[0][1][0]
+ return resp[0][1]
class ProxiedXMLOpener(transport.XMLOpener):
def createConnection(self, *args, **kw): |
d6c493df4df06f5195c1f964224728ca4e5ace06 | django_project/realtime/management/commands/loadfloodtestdata.py | django_project/realtime/management/commands/loadfloodtestdata.py | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | Fix wrong path to flood data to push. | Fix wrong path to flood data to push.
| Python | bsd-2-clause | AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django | ---
+++
@@ -32,6 +32,6 @@
flood_id=flood_id,
data_source='hazard_file',
data_source_args={
- 'filename': flood_layer_uri
+ 'filename': hazard_drop_path
}
) |
5709a160e6aad62bcdd8ae35c1b8bf9e8a6f7b6c | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | from django.db import models
from django.db.models.signals import post_save, post_delete
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def post_save_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def post_delete_si... | from django.db import models
from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
pur... | Use page_published signal for cache invalidation instead of post_save | Use page_published signal for cache invalidation instead of post_save
| Python | bsd-3-clause | nrsimha/wagtail,nrsimha/wagtail,kurtrwall/wagtail,quru/wagtail,tangentlabs/wagtail,nutztherookie/wagtail,hanpama/wagtail,kaedroho/wagtail,Klaudit/wagtail,marctc/wagtail,mixxorz/wagtail,stevenewey/wagtail,taedori81/wagtail,willcodefortea/wagtail,Klaudit/wagtail,rsalmaso/wagtail,serzans/wagtail,nealtodd/wagtail,Tivix/wag... | ---
+++
@@ -1,12 +1,13 @@
from django.db import models
-from django.db.models.signals import post_save, post_delete
+from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
+from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.uti... |
9e513650f166e3ec85363da61ea1d36b601f0b72 | throughput/experiment.py | throughput/experiment.py | from time import time, sleep
from subprocess import call
from argparse import ArgumentParser
from atexit import register
from pyadtn.aDTN import aDTN
from pyadtn.utils import info, debug
EXPERIMENT_DURATION = 5 * 60 + 10 # 5 minutes and 5 seconds (in seconds)
IFACE = "wlan0"
FREQ = str(2432) # 802.11 channel 1
if _... | from time import time, sleep
from subprocess import call
from argparse import ArgumentParser
from atexit import register
from pyadtn.aDTN import aDTN
from pyadtn.utils import info, debug
EXPERIMENT_DURATION = 5 * 60 + 10 # 5 minutes and 5 seconds (in seconds)
IFACE = "wlan0"
FREQ = str(2432) # 802.11 channel 5
if _... | Fix channel number in the comment | Fix channel number in the comment | Python | agpl-3.0 | megfault/aDTN-python-experiment,megfault/aDTN-python-experiment | ---
+++
@@ -8,7 +8,7 @@
EXPERIMENT_DURATION = 5 * 60 + 10 # 5 minutes and 5 seconds (in seconds)
IFACE = "wlan0"
-FREQ = str(2432) # 802.11 channel 1
+FREQ = str(2432) # 802.11 channel 5
if __name__ == "__main__":
parser = ArgumentParser() |
bf042cbe47c9fcfc0e608ff726a73d0e562027d0 | tests/test_with_hypothesis.py | tests/test_with_hypothesis.py | import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(bytes, bytes)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct... | import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(
hypothesis.strategies.binary(),
hypothesis.strategies.binary()
)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext,... | Fix the Hypothesis test to work with new API. | Fix the Hypothesis test to work with new API.
The Hypothesis API has since moved on from the last time we pushed
a change. Fix the test suite to work with the new API.
| Python | apache-2.0 | Ayrx/python-aead,Ayrx/python-aead | ---
+++
@@ -6,7 +6,10 @@
hypothesis = pytest.importorskip("hypothesis")
-@hypothesis.given(bytes, bytes)
+@hypothesis.given(
+ hypothesis.strategies.binary(),
+ hypothesis.strategies.binary()
+)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
... |
5520ebc1c232a69994d0941b7563f567d8defd0b | telemetry/telemetry/core/cast_interface.py | telemetry/telemetry/core/cast_interface.py | # Copyright 2022 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.
"""A wrapper for common operations on a device with Cast capabilities."""
import os
from telemetry.core import util
CAST_BROWSERS = [
'platform_app'
]
... | # Copyright 2022 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.
"""A wrapper for common operations on a device with Cast capabilities."""
import os
from telemetry.core import util
CAST_BROWSERS = [
'platform_app'
]
... | Change user and password used for Cast hardware devices | [cast3p] Change user and password used for Cast hardware devices
Change-Id: Id636d40afea79d08ce9af952438d5396add505e3
Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3602946
Commit-Queue: Chong Gu <2b40eb872a3eb33d1a32a10811f471f8a41ba08b@google.com>
Auto-Submit: Chong Gu <2b40eb872a3eb33d1a32a10811... | Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | ---
+++
@@ -10,8 +10,8 @@
CAST_BROWSERS = [
'platform_app'
]
-SSH_PWD = "user"
-SSH_USER = "user"
DEFAULT_CAST_CORE_DIR = os.path.join(util.GetCatapultDir(), '..', 'cast_core',
'prebuilts')
DEFAULT_CWR_EXE = os.path.join(util.GetCatapultDir(), '..', 'cast_web_runtime')
+... |
2b46bee644222c2e1c29d20ffc23768ed11006d6 | VMEncryption/main/oscrypto/encryptstates/SelinuxState.py | VMEncryption/main/oscrypto/encryptstates/SelinuxState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | Disable SELinux before OS disk encryption | Disable SELinux before OS disk encryption
| Python | apache-2.0 | vityagi/azure-linux-extensions,vityagi/azure-linux-extensions,andyliuliming/azure-linux-extensions,andyliuliming/azure-linux-extensions,soumyanishan/azure-linux-extensions,bpramod/azure-linux-extensions,krkhan/azure-linux-extensions,vityagi/azure-linux-extensions,jasonzio/azure-linux-extensions,andyliuliming/azure-linu... | ---
+++
@@ -31,6 +31,11 @@
self.context.logger.log("Entering selinux state")
+ se_linux_status = self.context.encryption_environment.get_se_linux()
+ if(se_linux_status.lower() == 'enforcing'):
+ self.context.logger.log("SELinux is in enforcing mode, disabling")
+ self... |
0128a0cc3c266848181ed2f6af3db34cc9c99b5d | terroroftinytown/services/googl.py | terroroftinytown/services/googl.py |
from terroroftinytown.services.base import BaseService
from terroroftinytown.services.status import URLStatus
import re
class GooglService(BaseService):
def process_response(self, response):
status_code = response.status_code
if status_code in self.params['redirect_codes']:
if self.ratelimited(response):
... | from terroroftinytown.services.base import BaseService
from terroroftinytown.services.status import URLStatus
import re
class GooglService(BaseService):
def process_response(self, response):
status_code = response.status_code
if status_code in self.params['redirect_codes']:
if self.rat... | Use spaces instead of tabs | Use spaces instead of tabs
| Python | mit | ArchiveTeam/terroroftinytown,ArchiveTeam/terroroftinytown,ArchiveTeam/terroroftinytown | ---
+++
@@ -1,28 +1,27 @@
-
from terroroftinytown.services.base import BaseService
from terroroftinytown.services.status import URLStatus
import re
class GooglService(BaseService):
- def process_response(self, response):
- status_code = response.status_code
+ def process_response(self, response):
+ s... |
ba4b348e03f5f875bb170a8b7d5c560ba7c6968f | features/groups/migrations/0002_auto_20160922_1108.py | features/groups/migrations/0002_auto_20160922_1108.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-22 09:08
from __future__ import unicode_literals
from django.db import migrations
def copy_groups(apps, schema_editor):
Group1 = apps.get_model('entities.Group')
Group2 = apps.get_model('groups.Group')
for g in Group1.objects.all():
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-22 09:08
from __future__ import unicode_literals
from django.db import migrations
def copy_groups(apps, schema_editor):
Group1 = apps.get_model('entities.Group')
Group2 = apps.get_model('groups.Group')
for g in Group1.objects.order_by('id'):... | Order groups by id when copying | Order groups by id when copying
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten | ---
+++
@@ -8,7 +8,7 @@
def copy_groups(apps, schema_editor):
Group1 = apps.get_model('entities.Group')
Group2 = apps.get_model('groups.Group')
- for g in Group1.objects.all():
+ for g in Group1.objects.order_by('id'):
g2 = Group2.objects.create(
name=g.name,
... |
25db9110d34760118b47b2bdf637cf6947154c2c | tests/unit/distributed/test_objectstore.py | tests/unit/distributed/test_objectstore.py | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | import pytest
from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive
@pytest.fixture
def mock_api(mocker):
mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
mocker.patch('bcbio.distributed.objectstore.Http')
mocker.patch('bcbio.distributed.ob... | Test json file with api key is in API service class | Test json file with api key is in API service class
| Python | mit | a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,vladsaveliev/bcbio-nextgen,cha... | ---
+++
@@ -28,3 +28,8 @@
def test_api_scope_includes_google_drive(mock_api):
drive_scope = 'https://www.googleapis.com/auth/drive'
assert drive_scope in GoogleDrive.SCOPES
+
+
+def test_filename_with_json_key_is_present(mock_api):
+ assert GoogleDrive.GOOGLE_API_KEY_FILE
+ assert GoogleDrive.GOOGLE_... |
68812938503901df48b9f3c7cd3b3160d51a52fa | txaws/client/_validators.py | txaws/client/_validators.py | # Licenced under the txaws licence available at /LICENSE in the txaws source.
"""
attrs validators for internal use.
"""
import attr
from attr import validators
def list_of(validator):
"""
Require a value which is a list containing elements which the
given validator accepts.
"""
return _ListOf(v... | # Licenced under the txaws licence available at /LICENSE in the txaws source.
"""
attrs validators for internal use.
"""
import attr
from attr import validators
def list_of(validator):
"""
Require a value which is a list containing elements which the
given validator accepts.
"""
return _Containe... | Introduce set_of (similar to list_of validator) | Introduce set_of (similar to list_of validator)
| Python | mit | oubiwann/txaws,mithrandi/txaws,mithrandi/txaws,twisted/txaws,twisted/txaws,oubiwann/txaws | ---
+++
@@ -13,24 +13,33 @@
Require a value which is a list containing elements which the
given validator accepts.
"""
- return _ListOf(validator)
+ return _ContainerOf(list, validator)
+
+
+def set_of(validator):
+ """
+ Require a value which is a set containing elements which the given
+ ... |
6dab7ceeb4de601c47b4d370c6184ddcd0110e89 | doc/conf.py | doc/conf.py | # -*- coding: utf-8 -*-
import os
import sys
import sphinx_rtd_theme
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import sphinxcontrib; reload(sphinxcontrib)
extensions = ['sphinxcontrib.ros']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinxcontr... | # -*- coding: utf-8 -*-
import os
import sys
import sphinx_rtd_theme
import pkg_resources
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import sphinxcontrib; reload(sphinxcontrib)
extensions = ['sphinxcontrib.ros']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
pr... | Use the source version as a doc version | Use the source version as a doc version
| Python | bsd-2-clause | otamachan/sphinxcontrib-ros,otamachan/sphinxcontrib-ros | ---
+++
@@ -2,6 +2,7 @@
import os
import sys
import sphinx_rtd_theme
+import pkg_resources
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import sphinxcontrib; reload(sphinxcontrib)
extensions = ['sphinxcontrib.ros']
@@ -10,8 +11,8 @@
master_doc = 'index'
project = u'sphinxcontritb-r... |
d5fd80a02ca619655f0b6d470acb745ec4432ba5 | e2e_test.py | e2e_test.py | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software d... | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software d... | Add Print Statement For Easier Debugging | Add Print Statement For Easier Debugging
| Python | apache-2.0 | bshaffer/appengine-python-vm-hello,googlearchive/appengine-python-vm-hello,bshaffer/appengine-python-vm-hello,googlearchive/appengine-python-vm-hello | ---
+++
@@ -15,6 +15,7 @@
response = urllib2.urlopen("{}/get_author/ulysses".format(HOST))
html = response.read()
+print(html)
assert(html == "James Joyce")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.