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 |
|---|---|---|---|---|---|---|---|---|---|---|
8e0d28d23c7ceb6a200773dde035b85965273ac6 | inbox/events/actions/base.py | inbox/events/actions/base.py | from inbox.models.account import Account
from inbox.models.event import Event
from inbox.events.actions.backends import module_registry
def create_event(account_id, event_id, db_session):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_create_event = module_registry[account.provider].remote_create_event
remote_create_event(account, event, db_session)
def update_event(account_id, event_id, db_session):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_update_event = module_registry[account.provider].remote_update_event
remote_update_event(account, event, db_session)
def delete_event(account_id, event_id, db_session, args):
account = db_session.query(Account).get(account_id)
remote_delete_event = module_registry[account.provider].remote_delete_event
event_uid = args.get('event_uid')
calendar_name = args.get('calendar_name')
# The calendar_uid argument is required for some providers, like EAS.
calendar_uid = args.get('calendar_uid')
remote_delete_event(account, event_uid, calendar_name, calendar_uid,
db_session)
| from inbox.models.account import Account
from inbox.models.event import Event
from inbox.events.actions.backends import module_registry
def create_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_create_event = module_registry[account.provider].remote_create_event
remote_create_event(account, event, db_session)
def update_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_update_event = module_registry[account.provider].remote_update_event
remote_update_event(account, event, db_session)
def delete_event(account_id, event_id, db_session, args):
account = db_session.query(Account).get(account_id)
remote_delete_event = module_registry[account.provider].remote_delete_event
event_uid = args.get('event_uid')
calendar_name = args.get('calendar_name')
# The calendar_uid argument is required for some providers, like EAS.
calendar_uid = args.get('calendar_uid')
remote_delete_event(account, event_uid, calendar_name, calendar_uid,
db_session)
| Add args flexibility to event create to match EAS requirements | Add args flexibility to event create to match EAS requirements
| Python | agpl-3.0 | PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,closeio/nylas,nylas/sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,closeio/nylas,gale320/sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,closeio/nylas,gale320/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,ErinCall/sync-engine,nylas/sync-engine,gale320/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,Eagles2F/sync-engine,Eagles2F/sync-engine,closeio/nylas,wakermahmud/sync-engine,Eagles2F/sync-engine,gale320/sync-engine,Eagles2F/sync-engine | ---
+++
@@ -3,7 +3,7 @@
from inbox.events.actions.backends import module_registry
-def create_event(account_id, event_id, db_session):
+def create_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
@@ -12,7 +12,7 @@
remote_create_event(account, event, db_session)
-def update_event(account_id, event_id, db_session):
+def update_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
|
ea22f4bf62204805e698965300b6d8dfa637a662 | pybossa_discourse/globals.py | pybossa_discourse/globals.py | # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
app.jinja_env.globals.update(discourse=self)
def comments(self):
"""Return an HTML snippet used to embed Discourse comments."""
return Markup("""
<div id="discourse-comments"></div>
<script type="text/javascript">
DiscourseEmbed = {{
discourseUrl: '{0}/',
discourseEmbedUrl: '{1}'
}};
window.onload = function() {{
let d = document.createElement('script'),
head = document.getElementsByTagName('head')[0],
body = document.getElementsByTagName('body')[0];
d.type = 'text/javascript';
d.async = true;
d.src = '{0}/javascripts/embed.js';
(head || body).appendChild(d);
}}
</script>
""").format(self.url, request.base_url)
| # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
from . import discourse_client
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
app.jinja_env.globals.update(discourse=self)
def comments(self):
"""Return an HTML snippet used to embed Discourse comments."""
return Markup("""
<div id="discourse-comments"></div>
<script type="text/javascript">
DiscourseEmbed = {{
discourseUrl: '{0}/',
discourseEmbedUrl: '{1}'
}};
window.onload = function() {{
let d = document.createElement('script'),
head = document.getElementsByTagName('head')[0],
body = document.getElementsByTagName('body')[0];
d.type = 'text/javascript';
d.async = true;
d.src = '{0}/javascripts/embed.js';
(head || body).appendChild(d);
}}
</script>
""").format(self.url, request.base_url)
def notifications(self):
"""Return a count of unread notifications for the current user."""
notifications = discourse_client.user_notifications()
if not notifications:
return 0
return sum([1 for n in notifications['notifications']
if not n['read']])
| Add notifications count to global envar | Add notifications count to global envar
| Python | bsd-3-clause | alexandermendes/pybossa-discourse | ---
+++
@@ -2,6 +2,7 @@
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
+from . import discourse_client
class DiscourseGlobals(object):
@@ -32,3 +33,11 @@
}}
</script>
""").format(self.url, request.base_url)
+
+ def notifications(self):
+ """Return a count of unread notifications for the current user."""
+ notifications = discourse_client.user_notifications()
+ if not notifications:
+ return 0
+ return sum([1 for n in notifications['notifications']
+ if not n['read']]) |
1d292feebd2999eb042da1f606c0fdc33103225f | api/models.py | api/models.py | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_category
self.printed_times = 0
self.printed_once = False | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_category
self.printed_times = 0
self.printed_once = False
class AccountModel:
def __init__(self, account_type, account_number, name, first_name, address, birthdate):
# We will automatically generate the new id
self.id = 0
self.type = account_type
self.number = account_number
self.name = name
self.first_name = first_name
self.address = address
self.birthdate = birthdate
#We will automatically generate next 2 parameters based on client address.
self.longitude = 0;
self.latitude = 0; | Update model script to support task database schema | Update model script to support task database schema
| Python | mit | candidate48661/BEA | ---
+++
@@ -8,3 +8,18 @@
self.message_category = message_category
self.printed_times = 0
self.printed_once = False
+
+
+class AccountModel:
+ def __init__(self, account_type, account_number, name, first_name, address, birthdate):
+ # We will automatically generate the new id
+ self.id = 0
+ self.type = account_type
+ self.number = account_number
+ self.name = name
+ self.first_name = first_name
+ self.address = address
+ self.birthdate = birthdate
+ #We will automatically generate next 2 parameters based on client address.
+ self.longitude = 0;
+ self.latitude = 0; |
e0d8099e57fb890649490b9e9bb201b98b041212 | libcloud/__init__.py | libcloud/__init__.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
libcloud provides a unified interface to the cloud computing resources.
"""
| # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
libcloud provides a unified interface to the cloud computing resources.
"""
__version__ = "0.1.1-dev" | Add version string to libcloud | Add version string to libcloud
git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@895867 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | cloudkick/libcloud,cloudkick/libcloud | ---
+++
@@ -16,3 +16,5 @@
"""
libcloud provides a unified interface to the cloud computing resources.
"""
+
+__version__ = "0.1.1-dev" |
46a0caa1bc162d11b26a996379170b2fc49f2940 | mcbench/client.py | mcbench/client.py | import collections
import redis
BENCHMARK_FIELDS = [
'author', 'author_url', 'date_submitted', 'date_updated',
'name', 'summary', 'tags', 'title', 'url'
]
Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS))
class McBenchClient(object):
def __init__(self, redis):
self.redis = redis
def get_benchmark_by_id(self, benchmark_id):
return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id))
def get_benchmark_by_name(self, name):
benchmark_id = self.redis.get('benchmark:%s:id', name)
return self.get_benchmark_by_id(benchmark_id)
def insert_benchmark(self, benchmark):
benchmark_id = self.redis.incr('global:next_benchmark_id')
self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id)
self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict())
def from_redis_url(redis_url):
return McBenchClient(redis.from_url(redis_url))
| import redis
class Benchmark(object):
def __init__(self, author, author_url, date_submitted, date_updated,
name, summary, tags, title, url):
self.author = author
self.author_url = author_url
self.date_submitted = date_submitted
self.date_updated = date_updated
self.name = name
self.summary = summary
self.tags = tags
self.title = title
self.url = url
def __repr__(self):
return '<Benchmark: %s>' % self.name
class BenchmarkDoesNotExist(Exception):
pass
class BenchmarkAlreadyExists(Exception):
pass
class McBenchClient(object):
def __init__(self, redis):
self.redis = redis
def get_benchmark_by_id(self, benchmark_id):
data = self.redis.hgetall('benchmark:%s' % benchmark_id)
if not data:
raise BenchmarkDoesNotExist
return Benchmark(**data)
def get_benchmark_by_name(self, name):
benchmark_id = self.redis.get('name:%s:id' % name)
if benchmark_id is None:
raise BenchmarkDoesNotExist
return self.get_benchmark_by_id(benchmark_id)
def get_all_benchmarks(self):
return [self.get_benchmark_by_id(key[len('benchmark:'):])
for key in self.redis.keys('benchmark:*')]
def insert_benchmark(self, benchmark):
benchmark_id = self.redis.get('name:%s:id' % benchmark.name)
if benchmark_id is not None:
raise BenchmarkAlreadyExists
benchmark_id = self.redis.incr('global:next_benchmark_id')
self.redis.set('name:%s:id' % benchmark.name, benchmark_id)
self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark))
def from_redis_url(redis_url):
return McBenchClient(redis.from_url(redis_url))
| Make Benchmark a class, not a namedtuple. | Make Benchmark a class, not a namedtuple.
| Python | mit | isbadawi/mcbench,isbadawi/mcbench | ---
+++
@@ -1,13 +1,29 @@
-import collections
-
import redis
-BENCHMARK_FIELDS = [
- 'author', 'author_url', 'date_submitted', 'date_updated',
- 'name', 'summary', 'tags', 'title', 'url'
-]
-Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS))
+class Benchmark(object):
+ def __init__(self, author, author_url, date_submitted, date_updated,
+ name, summary, tags, title, url):
+ self.author = author
+ self.author_url = author_url
+ self.date_submitted = date_submitted
+ self.date_updated = date_updated
+ self.name = name
+ self.summary = summary
+ self.tags = tags
+ self.title = title
+ self.url = url
+
+ def __repr__(self):
+ return '<Benchmark: %s>' % self.name
+
+
+class BenchmarkDoesNotExist(Exception):
+ pass
+
+
+class BenchmarkAlreadyExists(Exception):
+ pass
class McBenchClient(object):
@@ -15,16 +31,28 @@
self.redis = redis
def get_benchmark_by_id(self, benchmark_id):
- return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id))
+ data = self.redis.hgetall('benchmark:%s' % benchmark_id)
+ if not data:
+ raise BenchmarkDoesNotExist
+ return Benchmark(**data)
def get_benchmark_by_name(self, name):
- benchmark_id = self.redis.get('benchmark:%s:id', name)
+ benchmark_id = self.redis.get('name:%s:id' % name)
+ if benchmark_id is None:
+ raise BenchmarkDoesNotExist
return self.get_benchmark_by_id(benchmark_id)
+ def get_all_benchmarks(self):
+ return [self.get_benchmark_by_id(key[len('benchmark:'):])
+ for key in self.redis.keys('benchmark:*')]
+
def insert_benchmark(self, benchmark):
+ benchmark_id = self.redis.get('name:%s:id' % benchmark.name)
+ if benchmark_id is not None:
+ raise BenchmarkAlreadyExists
benchmark_id = self.redis.incr('global:next_benchmark_id')
- self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id)
- self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict())
+ self.redis.set('name:%s:id' % benchmark.name, benchmark_id)
+ self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark))
def from_redis_url(redis_url): |
1b9c4935b2edf6601c2d75d8a2d318266de2d456 | circuits/tools/__init__.py | circuits/tools/__init__.py | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def graph(x):
s = StringIO()
d = 0
i = 0
done = False
stack = []
visited = set()
children = list(x.components)
while not done:
if x not in visited:
if d:
s.write("%s%s\n" % (" " * d, "|"))
s.write("%s%s%s\n" % (" " * d, "|-", x))
else:
s.write(" .%s\n" % x)
if x.components:
d += 1
visited.add(x)
if i < len(children):
x = children[i]
i += 1
if x.components:
stack.append((i, children))
children = list(x.components)
i = 0
else:
if stack:
i, children = stack.pop()
d -= 1
else:
done = True
return s.getvalue()
| # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def graph(x):
s = StringIO()
d = 0
i = 0
done = False
stack = []
visited = set()
children = list(x.components)
while not done:
if x not in visited:
if d:
s.write("%s%s\n" % (" " * d, "|"))
s.write("%s%s%s\n" % (" " * d, "|-", x))
else:
s.write(" .%s\n" % x)
if x.components:
d += 1
visited.add(x)
if i < len(children):
x = children[i]
i += 1
if x.components:
stack.append((i, d, children))
children = list(x.components)
i = 0
else:
if stack:
i, d, children = stack.pop()
else:
done = True
return s.getvalue()
| Store the depth (d) on the stack and restore when backtracking | tools: Store the depth (d) on the stack and restore when backtracking
| Python | mit | treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,eriol/circuits | ---
+++
@@ -39,13 +39,12 @@
x = children[i]
i += 1
if x.components:
- stack.append((i, children))
+ stack.append((i, d, children))
children = list(x.components)
i = 0
else:
if stack:
- i, children = stack.pop()
- d -= 1
+ i, d, children = stack.pop()
else:
done = True
|
7ba2299e2d429bd873539507b3edbe3cdd3de9d6 | linkatos/firebase.py | linkatos/firebase.py | import pyrebase
def initialise(FB_API_KEY, project_name):
config = {
"apiKey": FB_API_KEY,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, FB_USER, FB_PASS, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
| import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
| Change variables to lower case | style: Change variables to lower case
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -1,9 +1,9 @@
import pyrebase
-def initialise(FB_API_KEY, project_name):
+def initialise(api_key, project_name):
config = {
- "apiKey": FB_API_KEY,
+ "apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
@@ -12,7 +12,7 @@
return pyrebase.initialize_app(config)
-def store_url(is_yes, url, FB_USER, FB_PASS, firebase):
+def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
@@ -20,7 +20,7 @@
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
- user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS)
+ user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = { |
d320de7a66472036f2504f8b935747ff4a1e4e49 | barf/setup.py | barf/setup.py | #! /usr/bin/env python
from setuptools import setup
from setuptools import find_packages
setup(
author = 'Christian Heitman',
author_email = 'cnheitman@fundacionsadosky.org.ar',
description = 'A multiplatform open source Binary Analysis and Reverse engineering Framework',
install_requires = [
'capstone',
'networkx',
'pefile',
'pybfd',
'pydot',
'pygments',
'pyparsing',
'sphinx',
],
license = 'BSD 2-Clause',
name = 'barf',
packages = find_packages(),
url = 'http://github.com/programa-stic/barf-project',
scripts = [
'tools/gadgets/BARFgadgets'
],
version = '0.2',
zip_safe = False
)
| #! /usr/bin/env python
from setuptools import setup
from setuptools import find_packages
# https://github.com/aquynh/capstone/issues/583
def fix_setuptools():
"""Work around bugs in setuptools.
Some versions of setuptools are broken and raise SandboxViolation for normal
operations in a virtualenv. We therefore disable the sandbox to avoid these
issues.
"""
try:
from setuptools.sandbox import DirectorySandbox
def violation(operation, *args, **_):
print "SandboxViolation: %s" % (args,)
DirectorySandbox._violation = violation
except ImportError:
pass
# Fix bugs in setuptools.
fix_setuptools()
setup(
author = 'Christian Heitman',
author_email = 'cnheitman@fundacionsadosky.org.ar',
description = 'A multiplatform open source Binary Analysis and Reverse engineering Framework',
install_requires = [
'capstone',
'networkx',
'pefile',
'pybfd',
'pydot',
'pygments',
'pyparsing',
'sphinx',
],
license = 'BSD 2-Clause',
name = 'barf',
packages = find_packages(),
url = 'http://github.com/programa-stic/barf-project',
scripts = [
'tools/gadgets/BARFgadgets'
],
version = '0.2',
zip_safe = False
)
| Fix Capstone installation error on virtualenvs | Fix Capstone installation error on virtualenvs
| Python | bsd-2-clause | chubbymaggie/barf-project,programa-stic/barf-project,cnheitman/barf-project,cnheitman/barf-project,chubbymaggie/barf-project,chubbymaggie/barf-project,programa-stic/barf-project,cnheitman/barf-project | ---
+++
@@ -2,6 +2,28 @@
from setuptools import setup
from setuptools import find_packages
+
+
+# https://github.com/aquynh/capstone/issues/583
+def fix_setuptools():
+ """Work around bugs in setuptools.
+
+ Some versions of setuptools are broken and raise SandboxViolation for normal
+ operations in a virtualenv. We therefore disable the sandbox to avoid these
+ issues.
+ """
+ try:
+ from setuptools.sandbox import DirectorySandbox
+
+ def violation(operation, *args, **_):
+ print "SandboxViolation: %s" % (args,)
+
+ DirectorySandbox._violation = violation
+ except ImportError:
+ pass
+
+# Fix bugs in setuptools.
+fix_setuptools()
setup(
author = 'Christian Heitman', |
56edfe1bacff53eec22b05d43f32063f83f43ea5 | studies/helpers.py | studies/helpers.py | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
context['osf_url'] = OSF_URL
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| Add OSF_URL to send_email helper. | Add OSF_URL to send_email helper.
| Python | apache-2.0 | CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api | ---
+++
@@ -1,7 +1,7 @@
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
-from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
+from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL
@app.task
@@ -19,6 +19,7 @@
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
+ context['osf_url'] = OSF_URL
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context) |
6fcf03532dcc549a3a95390b7c999482a64fc6c6 | tests/unit/utils/test_pycrypto.py | tests/unit/utils/test_pycrypto.py | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
# Import Salt Libs
import salt.utils.pycrypto
import salt.utils.platform
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
log = logging.getLogger(__name__)
class PycryptoTestCase(TestCase):
'''
TestCase for salt.utils.pycrypto module
'''
@skipIf(salt.utils.platform.is_windows(), 'No crypto module for Windows')
def test_gen_hash(self):
'''
Test gen_hash
'''
passwd = 'test_password'
id = '$'
if salt.utils.platform.is_darwin():
id = ''
ret = salt.utils.pycrypto.gen_hash(password=passwd)
self.assertTrue(ret.startswith('$6{0}'.format(id)))
ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='md5')
self.assertTrue(ret.startswith('$1{0}'.format(id)))
ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='sha256')
self.assertTrue(ret.startswith('$5{0}'.format(id)))
def test_secure_password(self):
'''
test secure_password
'''
ret = salt.utils.pycrypto.secure_password()
check = re.compile(r'[!@#$%^&*()_=+]')
assert check.search(ret) is None
assert ret
| # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
# Import Salt Libs
import salt.utils.pycrypto
import salt.utils.platform
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
log = logging.getLogger(__name__)
class PycryptoTestCase(TestCase):
'''
TestCase for salt.utils.pycrypto module
'''
# The crypt module is only available on Unix systems
# https://docs.python.org/dev/library/crypt.html
@skipIf(not salt.utils.pycrypto.HAS_CRYPT, 'crypt module not available')
def test_gen_hash(self):
'''
Test gen_hash
'''
passwd = 'test_password'
id = '$'
if salt.utils.platform.is_darwin():
id = ''
ret = salt.utils.pycrypto.gen_hash(password=passwd)
self.assertTrue(ret.startswith('$6{0}'.format(id)))
ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='md5')
self.assertTrue(ret.startswith('$1{0}'.format(id)))
ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='sha256')
self.assertTrue(ret.startswith('$5{0}'.format(id)))
def test_secure_password(self):
'''
test secure_password
'''
ret = salt.utils.pycrypto.secure_password()
check = re.compile(r'[!@#$%^&*()_=+]')
assert check.search(ret) is None
assert ret
| Make the skip apply to any system missing crypt | Make the skip apply to any system missing crypt
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -20,7 +20,9 @@
TestCase for salt.utils.pycrypto module
'''
- @skipIf(salt.utils.platform.is_windows(), 'No crypto module for Windows')
+ # The crypt module is only available on Unix systems
+ # https://docs.python.org/dev/library/crypt.html
+ @skipIf(not salt.utils.pycrypto.HAS_CRYPT, 'crypt module not available')
def test_gen_hash(self):
'''
Test gen_hash |
edebe37458da391723e3206c63102cbb69606c5b | ideascube/conf/idb_irq_bardarash.py | ideascube/conf/idb_irq_bardarash.py | """Bardarash in Kurdistan, Iraq"""
from .idb_jor_azraq import * # pragma: no flakes
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa
(_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']),
)
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender']
ENTRY_ACTIVITY_CHOICES = []
| """Bardarash in Kurdistan, Iraq"""
from .idb_jor_azraq import * # pragma: no flakes
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa
(_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']),
)
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender']
ENTRY_ACTIVITY_CHOICES = []
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'library',
}
]
| Remove Kalite until Arabic language is available | Remove Kalite until Arabic language is available
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -14,3 +14,16 @@
ENTRY_ACTIVITY_CHOICES = []
+
+HOME_CARDS = STAFF_HOME_CARDS + [
+ {
+ 'id': 'blog',
+ },
+ {
+ 'id': 'mediacenter',
+ },
+ {
+ 'id': 'library',
+ }
+]
+ |
066833caebddb9a6e0735e635ff214448e078405 | check_env.py | check_env.py | """ Run this file to check your python installation.
"""
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
assert version_found > (0, 15)
def test_import_numpy():
import numpy
def test_import_matplotlib():
import matplotlib
def test_scrape_web():
import pandas as pd
pd.read_html("http://en.wikipedia.org/wiki/World_population")
if __name__ == "__main__":
import nose
nose.run(defaultTest=__name__)
| """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
assert version_found > (0, 15)
def test_import_numpy():
import numpy
def test_import_matplotlib():
import matplotlib.pyplot as plt
plt.figure
plt.plot
plt.legend
plt.imshow
def test_import_statsmodels():
import statsmodels as sm
from statsmodels.formula.api import ols
from statsmodels.tsa.ar_model import AR
def test_read_html():
import pandas
pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
"sea_levels", "Obtaining Tide Gauge Data.html"))
def test_scrape_web():
import pandas as pd
pd.read_html("http://en.wikipedia.org/wiki/World_population")
if __name__ == "__main__":
import nose
nose.run(defaultTest=__name__)
| Add some more content in tests including with statsmodels. | Add some more content in tests including with statsmodels.
| Python | mit | wateryhcho/pandas_tutorial,linan7788626/pandas_tutorial,jonathanrocher/pandas_tutorial,wateryhcho/pandas_tutorial,Sandor-PRA/pandas_tutorial,Sandor-PRA/pandas_tutorial,ajaykliyara/pandas_tutorial,ajaykliyara/pandas_tutorial,jonathanrocher/pandas_tutorial,jonathanrocher/pandas_tutorial,ajaykliyara/pandas_tutorial,linan7788626/pandas_tutorial,Sandor-PRA/pandas_tutorial,linan7788626/pandas_tutorial,wateryhcho/pandas_tutorial | ---
+++
@@ -1,5 +1,8 @@
""" Run this file to check your python installation.
"""
+from os.path import dirname, join
+
+HERE = dirname(__file__)
def test_import_pandas():
import pandas
@@ -17,7 +20,23 @@
def test_import_matplotlib():
- import matplotlib
+ import matplotlib.pyplot as plt
+ plt.figure
+ plt.plot
+ plt.legend
+ plt.imshow
+
+
+def test_import_statsmodels():
+ import statsmodels as sm
+ from statsmodels.formula.api import ols
+ from statsmodels.tsa.ar_model import AR
+
+
+def test_read_html():
+ import pandas
+ pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
+ "sea_levels", "Obtaining Tide Gauge Data.html"))
def test_scrape_web(): |
5301f5a641426cd223cb528696495ee1df70258a | prefixlist/api.py | prefixlist/api.py | from flask import Flask
from flask_restful import abort, Api, Resource
app = Flask("pre-fixlist")
api = Api(app)
class PrefixListList(Resource):
def get(self):
# Return a list of all prefix lists we know about
return None
class PrefixList(Resource):
def get(self, listid):
# Return a list of versions
return None
def post(self):
# Create a new prefixlist
return None
def put(self, listid):
# Update a prefixlist
return None
def delete(self, listid):
return None
class PrefixListVersion(Resource):
def get(self, listid, version):
# Return a list of prefixes contained in the specific version of the prefixlist
return None
api.add_resource(PrefixListList, "/prefixlist")
api.add_resource(PrefixList, "/prefixlist/<int:listid>")
api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>")
if __name__ == '__main__':
app.run(debug=True)
| from flask import Flask
from flask_restful import abort, Api, Resource
from flask_cors import CORS
app = Flask("pre-fixlist")
api = Api(app)
CORS(app)
class PrefixListList(Resource):
def get(self):
# Return a list of all prefix lists we know about
return None
class PrefixList(Resource):
def get(self, listid):
# Return a list of versions
return None
def post(self):
# Create a new prefixlist
return None
def put(self, listid):
# Update a prefixlist
return None
def delete(self, listid):
return None
class PrefixListVersion(Resource):
def get(self, listid, version):
# Return a list of prefixes contained in the specific version of the prefixlist
return None
api.add_resource(PrefixListList, "/prefixlist")
api.add_resource(PrefixList, "/prefixlist/<int:listid>")
api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>")
if __name__ == '__main__':
app.run(debug=True)
| Add CORS header to API responses | Add CORS header to API responses
| Python | bsd-2-clause | emjemj/pre-fixlist | ---
+++
@@ -1,8 +1,10 @@
from flask import Flask
from flask_restful import abort, Api, Resource
+from flask_cors import CORS
app = Flask("pre-fixlist")
api = Api(app)
+CORS(app)
class PrefixListList(Resource):
|
9b5b6514ace9d08d2dca563b71c8b6a1ca3f4f70 | wordcloud.py | wordcloud.py | import falcon, json, pymongo
MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user'
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
user_name = mongo_db_user_config.split(':')[0]
password = mongo_db_user_config.split(':')[1]
mongo_db_client = pymongo.MongoClient('wordcloud-mongo.home.franks-reich.net', 27017)
mongo_db_client.admin.authenticate(user_name, password)
wordcloud_database = mongo_db_client.wordcloud
class WordCloudResource:
def on_get(self, request, response, name):
"""Handles GET requests"""
wordcloud = {
'name': name,
'wordcloud' : {
'blub' : 40,
'blah' : 34,
'derp' : 57
}
}
response.body = json.dumps(wordcloud)
app = falcon.API()
app.add_route('/wordcloud/{name}', WordCloudResource())
| import falcon, json, pymongo
MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user'
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
user_name = mongo_db_user_config.rstrip('\n').split(':')[0]
password = mongo_db_user_config.rstrip('\n').split(':')[1]
mongo_db_client = pymongo.MongoClient('wordcloud-mongo.home.franks-reich.net', 27017)
mongo_db_client.admin.authenticate(user_name, password)
wordcloud_database = mongo_db_client.wordcloud
class WordCloudResource:
def on_get(self, request, response, name):
"""Handles GET requests"""
wordcloud = {
'name': name,
'wordcloud' : {
'blub' : 40,
'blah' : 34,
'derp' : 57
}
}
response.body = json.dumps(wordcloud)
app = falcon.API()
app.add_route('/wordcloud/{name}', WordCloudResource())
| Read mongo user and passwd from config file | Read mongo user and passwd from config file
| Python | apache-2.0 | Frank-Krick/word_cloud-backend | ---
+++
@@ -5,8 +5,8 @@
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
-user_name = mongo_db_user_config.split(':')[0]
-password = mongo_db_user_config.split(':')[1]
+user_name = mongo_db_user_config.rstrip('\n').split(':')[0]
+password = mongo_db_user_config.rstrip('\n').split(':')[1]
mongo_db_client = pymongo.MongoClient('wordcloud-mongo.home.franks-reich.net', 27017) |
2b0edbadec80300d20a280db0f06281040e00e25 | radar/radar/validation/consultants.py | radar/radar/validation/consultants.py | from radar.validation.core import Field, Validation, ListField, ValidationError
from radar.validation.meta import MetaValidationMixin
from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower
from radar.validation.number_validators import gmc_number
class GroupConsultantValidation(MetaValidationMixin, Validation):
group = Field([required()])
def validate_group(self, group):
if group.type != 'HOSPITAL':
raise ValidationError('Must be a hospital.')
return group
class ConsultantValidation(MetaValidationMixin, Validation):
first_name = Field([not_empty(), upper(), max_length(100)])
last_name = Field([not_empty(), upper(), max_length(100)])
email = Field([none_if_blank(), optional(), lower(), email_address()])
telephone_number = Field([none_if_blank(), optional(), max_length(100)])
gmc_number = Field([optional(), gmc_number()])
group_consultants = ListField(GroupConsultantValidation())
| from radar.validation.core import Field, Validation, ListField, ValidationError
from radar.validation.meta import MetaValidationMixin
from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower
from radar.validation.number_validators import gmc_number
class GroupConsultantValidation(MetaValidationMixin, Validation):
group = Field([required()])
def validate_group(self, group):
if group.type != 'HOSPITAL':
raise ValidationError('Must be a hospital.')
return group
class GroupConsultantListField(ListField):
def __init__(self, chain=None):
super(GroupConsultantListField, self).__init__(GroupConsultantValidation(), chain=chain)
def validate(self, group_consultants):
print 'hello!'
group_ids = set()
for i, group_consultant in enumerate(group_consultants):
group_id = group_consultant.group.id
if group_id in group_ids:
raise ValidationError({i: {'group': 'Consultant already in group.'}})
else:
group_ids.add(group_id)
return group_consultants
class ConsultantValidation(MetaValidationMixin, Validation):
first_name = Field([not_empty(), upper(), max_length(100)])
last_name = Field([not_empty(), upper(), max_length(100)])
email = Field([none_if_blank(), optional(), lower(), email_address()])
telephone_number = Field([none_if_blank(), optional(), max_length(100)])
gmc_number = Field([optional(), gmc_number()])
group_consultants = GroupConsultantListField()
| Check consultant groups aren't duplicated | Check consultant groups aren't duplicated
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | ---
+++
@@ -14,10 +14,30 @@
return group
+class GroupConsultantListField(ListField):
+ def __init__(self, chain=None):
+ super(GroupConsultantListField, self).__init__(GroupConsultantValidation(), chain=chain)
+
+ def validate(self, group_consultants):
+ print 'hello!'
+
+ group_ids = set()
+
+ for i, group_consultant in enumerate(group_consultants):
+ group_id = group_consultant.group.id
+
+ if group_id in group_ids:
+ raise ValidationError({i: {'group': 'Consultant already in group.'}})
+ else:
+ group_ids.add(group_id)
+
+ return group_consultants
+
+
class ConsultantValidation(MetaValidationMixin, Validation):
first_name = Field([not_empty(), upper(), max_length(100)])
last_name = Field([not_empty(), upper(), max_length(100)])
email = Field([none_if_blank(), optional(), lower(), email_address()])
telephone_number = Field([none_if_blank(), optional(), max_length(100)])
gmc_number = Field([optional(), gmc_number()])
- group_consultants = ListField(GroupConsultantValidation())
+ group_consultants = GroupConsultantListField() |
b8359e6b04d13f550aec308308f2e91e194bc372 | uberlogs/handlers/kill_process.py | uberlogs/handlers/kill_process.py | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
# Twisted writes unhandled errors in different calls
# If we exit on the first call, we'd lose the actual error
for log_to_ignore in ["Unhandled error in Deferred"]:
if log_to_ignore.lower() in record.getMessage().lower():
return
os._exit(1)
| import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
msg = record.getMessage()
# Twisted writes unhandled errors in different calls
# If we exit on the first call, we'd lose the actual error
for log_to_ignore in ["Unhandled error in Deferred"]:
if log_to_ignore.lower() in msg.lower():
return
os._exit(1)
| Remove repetitive getMessage calls in KillProcesshandler | Remove repetitive getMessage calls in KillProcesshandler
| Python | mit | odedlaz/uberlogs,odedlaz/uberlogs | ---
+++
@@ -14,9 +14,10 @@
for fd in [sys.stdout, sys.stderr]:
fd.flush()
+ msg = record.getMessage()
# Twisted writes unhandled errors in different calls
# If we exit on the first call, we'd lose the actual error
for log_to_ignore in ["Unhandled error in Deferred"]:
- if log_to_ignore.lower() in record.getMessage().lower():
+ if log_to_ignore.lower() in msg.lower():
return
os._exit(1) |
be5eecf2a043abf7585022f1dda3b79572eba192 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_ndmeasure._pycompat
def test_irange():
r = dask_ndmeasure._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| Add a basic test for irange | Add a basic test for irange
Make sure `irange` is there, it doesn't return a list, and it acts like
`range` on some test arguments.
| Python | bsd-3-clause | dask-image/dask-ndmeasure | ---
+++
@@ -1,2 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+
+
+from __future__ import absolute_import
+
+import dask_ndmeasure._pycompat
+
+
+def test_irange():
+ r = dask_ndmeasure._pycompat.irange(5)
+
+ assert not isinstance(r, list)
+
+ assert list(r) == [0, 1, 2, 3, 4] |
e90a60b1da00a6c6a5e1b4235c4009d7477986ca | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/cppcheck-target-cmake"
license = "MIT"
def source(self):
zip_name = "cppcheck-target-cmake.zip"
download("https://github.com/polysquare/"
"cppcheck-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/cppcheck-target-cmake",
src="cppcheck-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/cppcheck-target-cmake"
license = "MIT"
def source(self):
zip_name = "cppcheck-target-cmake.zip"
download("https://github.com/polysquare/"
"cppcheck-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="cppcheck-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/cppcheck-target-cmake",
src="cppcheck-target-cmake-" + VERSION,
keep_path=True)
| Copy find modules to root of module path | conan: Copy find modules to root of module path
| Python | mit | polysquare/cppcheck-target-cmake | ---
+++
@@ -26,6 +26,10 @@
os.unlink(zip_name)
def package(self):
+ self.copy(pattern="Find*.cmake",
+ dst="",
+ src="cppcheck-target-cmake-" + VERSION,
+ keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/cppcheck-target-cmake",
src="cppcheck-target-cmake-" + VERSION, |
59afb96f2211983ee2a2786c60791074b13c3e7f | ni/__main__.py | ni/__main__.py | """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records: CLAHost):
self.server = server
self.cla_records = cla_records
async def respond(request: web.Request) -> web.StreamResponse: # XXX untested
"""Handle a webhook trigger from the contribution host."""
try:
contribution = ContribHost.process(request)
usernames = await contribution.usernames() # XXX not implemented
cla_status = await self.cla_records.check(usernames) # XXX not implemented
# With a background queue, one could add the update as a work item
# and return an HTTP 202 response.
return (await contribution.update(cla_status)) # XXX not implemented
except abc.ResponseExit as exc:
return exc.response
except Exception as exc:
self.server.log(exc)
return web.Response(
status=http.HTTPStatus.INTERNAL_SERVER_ERROR.value)
if __name__ == '__main__':
server = ServerHost()
cla_records = CLAHost()
handler = Handler(server, cla_records)
app = web.Application()
app.router.add_route(*ContribHost.route, handler.respond)
web.run_app(app, port=server.port())
| """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records: CLAHost):
self.server = server
self.cla_records = cla_records
async def respond(request: web.Request) -> web.StreamResponse: # XXX untested
"""Handle a webhook trigger from the contribution host."""
try:
contribution = ContribHost.process(request)
usernames = await contribution.usernames() # XXX not implemented
cla_status = await self.cla_records.check(usernames) # XXX not implemented
# With a work queue, one could make the updating of the
# contribution a work item and return an HTTP 202 response.
return (await contribution.update(cla_status)) # XXX not implemented
except abc.ResponseExit as exc:
return exc.response
except Exception as exc:
self.server.log(exc)
return web.Response(
status=http.HTTPStatus.INTERNAL_SERVER_ERROR.value)
if __name__ == '__main__':
server = ServerHost()
cla_records = CLAHost()
handler = Handler(server, cla_records)
app = web.Application()
app.router.add_route(*ContribHost.route, handler.respond)
web.run_app(app, port=server.port())
| Tweak comment about 202 response | Tweak comment about 202 response
| Python | apache-2.0 | python/the-knights-who-say-ni,python/the-knights-who-say-ni | ---
+++
@@ -21,8 +21,8 @@
contribution = ContribHost.process(request)
usernames = await contribution.usernames() # XXX not implemented
cla_status = await self.cla_records.check(usernames) # XXX not implemented
- # With a background queue, one could add the update as a work item
- # and return an HTTP 202 response.
+ # With a work queue, one could make the updating of the
+ # contribution a work item and return an HTTP 202 response.
return (await contribution.update(cla_status)) # XXX not implemented
except abc.ResponseExit as exc:
return exc.response |
9681b2f31163e24e72121afc6195262376891220 | marketpulse/main/__init__.py | marketpulse/main/__init__.py | import moneyed
FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price'
def get_currency_choices():
return sorted(((currency, data.name) for currency, data in moneyed.CURRENCIES.items()))
| import moneyed
FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price'
def get_currency_choices():
return sorted(((currency, data.code) for currency, data in moneyed.CURRENCIES.items()))
| Replace currency full name with currency code. | Replace currency full name with currency code.
| Python | mpl-2.0 | akatsoulas/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,mozilla/marketpulse | ---
+++
@@ -5,4 +5,4 @@
def get_currency_choices():
- return sorted(((currency, data.name) for currency, data in moneyed.CURRENCIES.items()))
+ return sorted(((currency, data.code) for currency, data in moneyed.CURRENCIES.items())) |
9cfe03ab06f126406a51c0945e990fc849d8dfb9 | scripts/crontab/gen-crons.py | scripts/crontab/gen-crons.py | #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
parser.add_option("-u", "--user",
help=("Prefix cron with this user. "
"Only define for cron.d style crontabs"))
parser.add_option("-p", "--python", default="/usr/bin/python2.6",
help="Python interpreter to use")
(opts, args) = parser.parse_args()
if not opts.kitsune:
parser.error("-k must be defined")
ctx = {'django': 'cd %s; %s manage.py' % (opts.kitsune, opts.python),}
ctx['cron'] = '%s cron' % ctx['django']
if opts.user:
for k, v in ctx.iteritems():
ctx[k] = '%s %s' % (opts.user, v)
# Needs to stay below the opts.user injection.
ctx['python'] = opts.python
print Template(TEMPLATE).render(**ctx)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
parser.add_option("-u", "--user",
help=("Prefix cron with this user. "
"Only define for cron.d style crontabs"))
parser.add_option("-p", "--python", default="/usr/bin/python2.6",
help="Python interpreter to use")
(opts, args) = parser.parse_args()
if not opts.kitsune:
parser.error("-k must be defined")
# To pick up the right PyOpenSSL:
python_path = 'PYTHONPATH=/usr/local/lib64/python2.6/site-packages'
ctx = {'django': 'cd %s; %s %s manage.py' % (
opts.kitsune, python_path, opts.python),}
ctx['cron'] = '%s cron' % ctx['django']
if opts.user:
for k, v in ctx.iteritems():
ctx[k] = '%s %s' % (opts.user, v)
# Needs to stay below the opts.user injection.
ctx['python'] = opts.python
print Template(TEMPLATE).render(**ctx)
if __name__ == "__main__":
main()
| Add local site-packages to PYTHONPATH. | Add local site-packages to PYTHONPATH.
To pick up the local version of PyOpenSSL.
| Python | bsd-3-clause | philipp-sumo/kitsune,iDTLabssl/kitsune,orvi2014/kitsune,silentbob73/kitsune,NewPresident1/kitsune,MziRintu/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,YOTOV-LIMITED/kitsune,safwanrahman/kitsune,silentbob73/kitsune,safwanrahman/linuxdesh,mythmon/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune,chirilo/kitsune,NewPresident1/kitsune,rlr/kitsune,turtleloveshoes/kitsune,MikkCZ/kitsune,brittanystoroz/kitsune,NewPresident1/kitsune,NewPresident1/kitsune,orvi2014/kitsune,silentbob73/kitsune,Osmose/kitsune,silentbob73/kitsune,MikkCZ/kitsune,chirilo/kitsune,mythmon/kitsune,dbbhattacharya/kitsune,philipp-sumo/kitsune,safwanrahman/linuxdesh,anushbmx/kitsune,dbbhattacharya/kitsune,asdofindia/kitsune,safwanrahman/kitsune,MziRintu/kitsune,asdofindia/kitsune,dbbhattacharya/kitsune,mythmon/kitsune,Osmose/kitsune,feer56/Kitsune2,feer56/Kitsune1,H1ghT0p/kitsune,mozilla/kitsune,feer56/Kitsune1,mozilla/kitsune,Osmose/kitsune,turtleloveshoes/kitsune,iDTLabssl/kitsune,safwanrahman/kitsune,brittanystoroz/kitsune,mozilla/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,mozilla/kitsune,Osmose/kitsune,dbbhattacharya/kitsune,rlr/kitsune,mythmon/kitsune,feer56/Kitsune2,turtleloveshoes/kitsune,YOTOV-LIMITED/kitsune,philipp-sumo/kitsune,chirilo/kitsune,feer56/Kitsune2,asdofindia/kitsune,orvi2014/kitsune,H1ghT0p/kitsune,anushbmx/kitsune,orvi2014/kitsune,MziRintu/kitsune,brittanystoroz/kitsune,H1ghT0p/kitsune,feer56/Kitsune1,safwanrahman/linuxdesh,safwanrahman/kitsune,chirilo/kitsune,MikkCZ/kitsune,anushbmx/kitsune,feer56/Kitsune2,MziRintu/kitsune,rlr/kitsune,rlr/kitsune,H1ghT0p/kitsune,anushbmx/kitsune,asdofindia/kitsune | ---
+++
@@ -23,7 +23,11 @@
if not opts.kitsune:
parser.error("-k must be defined")
- ctx = {'django': 'cd %s; %s manage.py' % (opts.kitsune, opts.python),}
+ # To pick up the right PyOpenSSL:
+ python_path = 'PYTHONPATH=/usr/local/lib64/python2.6/site-packages'
+
+ ctx = {'django': 'cd %s; %s %s manage.py' % (
+ opts.kitsune, python_path, opts.python),}
ctx['cron'] = '%s cron' % ctx['django']
if opts.user: |
49493f11e20e4cb033ae17d29bfa14fa8473d145 | qutebrowser/.qutebrowser/config.py | qutebrowser/.qutebrowser/config.py | c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monospace"
c.fonts.messages.warning = "16pt monospace"
c.fonts.monospace = "\"xos4 Terminus\", Terminus, monospace"
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"
| # Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monospace"
c.fonts.messages.warning = "16pt monospace"
c.fonts.monospace = "\"xos4 Terminus\", Terminus, monospace"
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"
# Play videos with mpv
config.bind('e', 'spawn mpv {url}')
config.bind('E', 'hint links spawn mpv {hint-url}')
| Add mpv spawning to qutebrowser | Add mpv spawning to qutebrowser
Signed-off-by: Tomas <5fad2aa041dd6f0fec7c9125f282be028fd2d7b0@Tomass-MacBook-Pro.local>
| Python | mit | deathbeam/dotfiles,deathbeam/dotfiles,deathbeam/awesomedotrc,deathbeam/dotfiles,deathbeam/dotfiles | ---
+++
@@ -1,3 +1,4 @@
+# Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
@@ -11,3 +12,7 @@
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"
+
+# Play videos with mpv
+config.bind('e', 'spawn mpv {url}')
+config.bind('E', 'hint links spawn mpv {hint-url}') |
cac3099b9ab07d5ac2180e0b2796f55668ddda1e | generate_keyczart.py | generate_keyczart.py | import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.listdir(directory):
os.makedirs(directory)
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczart.main(['addkey','--location=keyset' ,'--status=primary'])
else:
print 'Keyset directory already has something in there. Skipping key generation.'
| import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.path.exists(directory):
os.makedirs(directory)
if not os.listdir(directory):
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczart.main(['addkey','--location=keyset' ,'--status=primary'])
else:
print 'Keyset directory already has something in there. Skipping key generation.'
| Make the directory if it doesn't exist | Make the directory if it doesn't exist
| Python | apache-2.0 | arubdesu/Crypt-Server,arubdesu/Crypt-Server,arubdesu/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server | ---
+++
@@ -2,8 +2,11 @@
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
+
+if not os.path.exists(directory):
+ os.makedirs(directory)
+
if not os.listdir(directory):
- os.makedirs(directory)
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczart.main(['addkey','--location=keyset' ,'--status=primary'])
else: |
62d5682fa3be9dfbae80b2acae9839cd1278dcb6 | whatismyip.py | whatismyip.py | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text)
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__':
main()
| #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__':
main()
| Use lxml as a parsing engine for bs4 | Use lxml as a parsing engine for bs4
| Python | apache-2.0 | MichaelAquilina/whatismyip | ---
+++
@@ -8,7 +8,7 @@
def main():
r = requests.get('http://www.whatismyip.com')
- soup = BeautifulSoup(r.text)
+ soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'): |
c485876017c92ac01af733945f04d36a21da8a6d | newsroom/settings.py | newsroom/settings.py | from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 12)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"big")
ARTICLE_PRIMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"large")
CACHE_PERIOD = getattr(settings, 'NEWSROOM_CACHE_PERIOD', 500)
ADVERT_CODE = getattr(settings, 'NEWSROOM_ADVERT_CODE', '')
| from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 16)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"big")
ARTICLE_PRIMARY_IMAGE_SIZE = getattr(settings,
'NEWSROOM_ARTICLE_TEASER_IMAGE_SIZE',
"large")
CACHE_PERIOD = getattr(settings, 'NEWSROOM_CACHE_PERIOD', 500)
ADVERT_CODE = getattr(settings, 'NEWSROOM_ADVERT_CODE', '')
| Set default number of articles on page to 16, up from 12. | Set default number of articles on page to 16, up from 12.
| Python | bsd-3-clause | groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu | ---
+++
@@ -2,7 +2,7 @@
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
-ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 12)
+ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 16)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZE = getattr(settings, |
9d0798904160f86d7f580dde3bfba8cc28b5a23f | troposphere/ram.py | troposphere/ram.py | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare(AWSObject):
resource_type = "AWS::RAM::ResourceShare"
props = {
"AllowExternalPrincipals": (boolean, False),
"Name": (str, True),
"Principals": ([str], False),
"ResourceArns": ([str], False),
"Tags": (Tags, False),
}
| # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.3.0
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare(AWSObject):
resource_type = "AWS::RAM::ResourceShare"
props = {
"AllowExternalPrincipals": (boolean, False),
"Name": (str, True),
"PermissionArns": ([str], False),
"Principals": ([str], False),
"ResourceArns": ([str], False),
"Tags": (Tags, False),
}
| Update RAM per 2021-06-10 changes | Update RAM per 2021-06-10 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -1,7 +1,11 @@
-# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
+# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
+#
+# *** Do not modify - this file is autogenerated ***
+# Resource specification version: 39.3.0
+
from troposphere import Tags
@@ -15,6 +19,7 @@
props = {
"AllowExternalPrincipals": (boolean, False),
"Name": (str, True),
+ "PermissionArns": ([str], False),
"Principals": ([str], False),
"ResourceArns": ([str], False),
"Tags": (Tags, False), |
eb4456b752313383a573bacfc102db9149ee1854 | django_transfer/urls.py | django_transfer/urls.py | from __future__ import unicode_literals
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'',
url(r'^download/.*$', 'django_transfer.views.download', name='download'),
url(r'^upload/$', 'django_transfer.views.upload', name='upload'),
)
| from __future__ import unicode_literals
try:
from django.conf.urls import url
def patterns(*args):
return args
except ImportError:
from django.conf.urls.defaults import patterns, url
from django_transfer.views import download, upload
urlpatterns = patterns(
url(r'^download/.*$', download, name='download'),
url(r'^upload/$', upload, name='upload'),
)
| Fix URL patterns for different Django versions. | Fix URL patterns for different Django versions.
| Python | mit | smartfile/django-transfer | ---
+++
@@ -1,13 +1,18 @@
from __future__ import unicode_literals
try:
- from django.conf.urls import patterns, url
+ from django.conf.urls import url
+
+ def patterns(*args):
+ return args
+
except ImportError:
from django.conf.urls.defaults import patterns, url
+from django_transfer.views import download, upload
+
urlpatterns = patterns(
- '',
- url(r'^download/.*$', 'django_transfer.views.download', name='download'),
- url(r'^upload/$', 'django_transfer.views.upload', name='upload'),
+ url(r'^download/.*$', download, name='download'),
+ url(r'^upload/$', upload, name='upload'),
) |
4cff7dd08fdb345b6e091570a2ca5500ef871318 | flask_authorization_panda/basic_auth.py | flask_authorization_panda/basic_auth.py | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, Response, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
dict.
Args:
original_function (function): The function to wrap.
Returns:
flask.Response: When credentials are missing or don't match.
original_function (function): The original function.
"""
@wraps(original_function)
def decorated(*args, **kwargs):
try:
assert request.authorization.username == \
current_app.config['APP_USERNAME']
assert request.authorization.password == \
current_app.config['APP_PASSWORD']
except AttributeError:
return Response(
'You must provide access credentials for this url.', 401,
{'WWW-Authenticate': 'Basic'})
except AssertionError:
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic'})
return original_function(*args, **kwargs)
return decorated | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, jsonify, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
dict.
Args:
original_function (function): The function to wrap.
Returns:
flask.Response: When credentials are missing or don't match.
original_function (function): The original function.
"""
@wraps(original_function)
def decorated(*args, **kwargs):
try:
if not (request.authorization.username,
request.authorization.password) == (
current_app.config.basic_auth_credentials['username'],
current_app.config.basic_auth_credentials['password']):
unauthorized_response = jsonify(
{'message': 'Could not verify your access level '
'for that URL. \nYou have to login '
'with proper credentials',
'statusCode': 401})
unauthorized_response.status_code = 401
return unauthorized_response
except AttributeError:
unauthorized_response = jsonify(
{'message': 'Could not verify your access level '
'for that URL. \nYou have to login '
'with proper credentials',
'statusCode': 401})
unauthorized_response.status_code = 401
return original_function(*args, **kwargs)
return decorated | Remove use of assert statements since this does not conform to general best practice. | Remove use of assert statements since this does not conform to general best practice.
This is unfortunate, because the code is much more verbose than before and NOT as clear.
| Python | mit | eikonomega/flask-authorization-panda | ---
+++
@@ -5,7 +5,7 @@
from functools import wraps
-from flask import request, Response, current_app
+from flask import request, jsonify, current_app
def basic_auth(original_function):
@@ -22,22 +22,28 @@
original_function (function): The original function.
"""
+
@wraps(original_function)
def decorated(*args, **kwargs):
try:
- assert request.authorization.username == \
- current_app.config['APP_USERNAME']
- assert request.authorization.password == \
- current_app.config['APP_PASSWORD']
+ if not (request.authorization.username,
+ request.authorization.password) == (
+ current_app.config.basic_auth_credentials['username'],
+ current_app.config.basic_auth_credentials['password']):
+ unauthorized_response = jsonify(
+ {'message': 'Could not verify your access level '
+ 'for that URL. \nYou have to login '
+ 'with proper credentials',
+ 'statusCode': 401})
+ unauthorized_response.status_code = 401
+ return unauthorized_response
except AttributeError:
- return Response(
- 'You must provide access credentials for this url.', 401,
- {'WWW-Authenticate': 'Basic'})
- except AssertionError:
- return Response(
- 'Could not verify your access level for that URL.\n'
- 'You have to login with proper credentials', 401,
- {'WWW-Authenticate': 'Basic'})
+ unauthorized_response = jsonify(
+ {'message': 'Could not verify your access level '
+ 'for that URL. \nYou have to login '
+ 'with proper credentials',
+ 'statusCode': 401})
+ unauthorized_response.status_code = 401
return original_function(*args, **kwargs)
return decorated |
e33a2879fbafe36c8c29d48042dad8277b068e91 | umap/tests/test_plot.py | umap/tests/test_plot.py | from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at_all():
umap.plot.points(mapper, labels=iris.target)
umap.plot.points(mapper, values=iris.data[:, 0])
umap.plot.diagnostic(mapper, diagnostic_type="all")
umap.plot.connectivity(mapper)
| from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at_all():
umap.plot.points(mapper)
umap.plot.points(mapper, labels=iris.target)
umap.plot.points(mapper, values=iris.data[:, 0])
umap.plot.points(mapper, theme='fire')
umap.plot.diagnostic(mapper, diagnostic_type='all')
umap.plot.diagnostic(mapper, diagnostic_type='neighborhood')
umap.plot.connectivity(mapper)
umap.plot.interactive(mapper)
umap.plot.interactive(mapper, labels=iris.target)
umap.plot.interactive(mapper, values=iris.data[:, 0])
umap.plot.interactive(mapper, theme='fire')
umap.plot._datashade_points(mapper.embedding_)
| Add more basic plotting tests | Add more basic plotting tests
| Python | bsd-3-clause | lmcinnes/umap,lmcinnes/umap | ---
+++
@@ -17,7 +17,15 @@
def test_plot_runs_at_all():
+ umap.plot.points(mapper)
umap.plot.points(mapper, labels=iris.target)
umap.plot.points(mapper, values=iris.data[:, 0])
- umap.plot.diagnostic(mapper, diagnostic_type="all")
+ umap.plot.points(mapper, theme='fire')
+ umap.plot.diagnostic(mapper, diagnostic_type='all')
+ umap.plot.diagnostic(mapper, diagnostic_type='neighborhood')
umap.plot.connectivity(mapper)
+ umap.plot.interactive(mapper)
+ umap.plot.interactive(mapper, labels=iris.target)
+ umap.plot.interactive(mapper, values=iris.data[:, 0])
+ umap.plot.interactive(mapper, theme='fire')
+ umap.plot._datashade_points(mapper.embedding_) |
bf23c87c7606cbcf8afcd2c5120c25ede92675c0 | irc/functools.py | irc/functools.py | from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, we save the args and
kwargs with which it was called.
>>> class MyClass(object):
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}
>>> my_ob.method(a=3, b='foo')
3 foo
>>> my_ob._saved_method.args
()
>>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
True
"""
args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
attr_name = '_saved_' + method.__name__
attr = args_and_kwargs(args, kwargs)
setattr(self, attr_name, attr)
return method(self, *args, **kwargs)
return wrapper
| from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass(object):
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}
>>> my_ob.method(a=3, b='foo')
3 foo
>>> my_ob._saved_method.args
()
>>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
True
The arguments are stored on the instance, allowing for
different instance to save different args.
>>> your_ob = MyClass()
>>> your_ob.method({3}, b=[4])
{3} [4]
>>> your_ob._saved_method.args
({3},)
>>> my_ob._saved_method.args
()
"""
args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
attr_name = '_saved_' + method.__name__
attr = args_and_kwargs(args, kwargs)
setattr(self, attr_name, attr)
return method(self, *args, **kwargs)
return wrapper
| Update docstring and expand doctests. | Update docstring and expand doctests.
| Python | mit | jaraco/irc | ---
+++
@@ -5,8 +5,8 @@
def save_method_args(method):
"""
- Wrap a method such that when it is called, we save the args and
- kwargs with which it was called.
+ Wrap a method such that when it is called, the args and kwargs are
+ saved on the method.
>>> class MyClass(object):
... @save_method_args
@@ -25,6 +25,17 @@
()
>>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
True
+
+ The arguments are stored on the instance, allowing for
+ different instance to save different args.
+
+ >>> your_ob = MyClass()
+ >>> your_ob.method({3}, b=[4])
+ {3} [4]
+ >>> your_ob._saved_method.args
+ ({3},)
+ >>> my_ob._saved_method.args
+ ()
"""
args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
@functools.wraps(method) |
dfc7d629956f708cf5b69e464fe3a7298ffb6cfa | BotHandler.py | BotHandler.py | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_with_port.split(":")[1])
self.startBotFactory(server, port, channels)
GlobalVars.bothandler = self
reactor.run()
def startBotFactory(self, server, port, channels):
if server in self.botfactories:
print "Already on server '{}'.".format(server)
return False
print "Joining server '{}'.".format(server)
botfactory = HubbotFactory(server, port, channels)
self.botfactories[server] = botfactory
return True
def stopBotFactory(self, server, quitmessage="ohok"):
quitmessage = quitmessage.encode("utf-8")
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
self.botfactories[server].protocol.quit(quitmessage)
self.unregisterFactory(server)
def unregisterFactory(self, server):
if server in self.botfactories:
del self.botfactories[server]
if len(self.botfactories)==0:
print "No more running bots, shutting down."
reactor.callLater(2.0, reactor.stop)
if __name__=="__main__":
bothandler = BotHandler()
| from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_with_port.split(":")[1])
self.startBotFactory(server, port, channels)
GlobalVars.bothandler = self
reactor.run()
def startBotFactory(self, server, port, channels):
if server in self.botfactories:
print "Already on server '{}'.".format(server)
return False
print "Joining server '{}'.".format(server)
botfactory = HubbotFactory(server, port, channels)
self.botfactories[server] = botfactory
return True
def stopBotFactory(self, server, quitmessage="ohok"):
quitmessage = quitmessage.encode("utf-8")
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
print "Shutting down bot for server '{}'".format(server)
self.botfactories[server].protocol.quit(quitmessage)
self.unregisterFactory(server)
def unregisterFactory(self, server):
if server in self.botfactories:
del self.botfactories[server]
if len(self.botfactories)==0:
print "No more running bots, shutting down."
reactor.callLater(2.0, reactor.stop)
if __name__=="__main__":
bothandler = BotHandler()
| Print a quit message when shutting down a bot | Print a quit message when shutting down a bot
| Python | mit | HubbeKing/Hubbot_Twisted | ---
+++
@@ -29,6 +29,7 @@
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
+ print "Shutting down bot for server '{}'".format(server)
self.botfactories[server].protocol.quit(quitmessage)
self.unregisterFactory(server)
|
982f4af638e83ee49c87a0dffad2b47daf872749 | workers/data_refinery_workers/downloaders/test_utils.py | workers/data_refinery_workers/downloaders/test_utils.py | import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an exception with no files."""
create_processor_job_for_original_files([])
self.assertTrue(True)
| import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
@tag('downloaders')
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an exception with no files."""
create_processor_job_for_original_files([])
self.assertTrue(True)
| Add tag to downloaders test so it is actually run. | Add tag to downloaders test so it is actually run.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | ---
+++
@@ -8,6 +8,7 @@
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
+ @tag('downloaders')
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an exception with no files."""
create_processor_job_for_original_files([]) |
813970150109450e53be44715913e5fb3c680c77 | uscampgrounds/models.py | uscampgrounds/models.py | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = models.TextField()
sites = models.CharField(max_length=128)
elevation = models.CharField(max_length=128)
hookups = models.CharField(max_length=128)
amenities = models.TextField()
point = models.PointField(srid=4326)
def locator_point(self):
return self.point
def __unicode__(self):
return self.name
# integrate with the django-locator app for easy geo lookups if it's installed
if 'locator.objects' in settings.INSTALLED_APPS:
from locator.objects.models import create_locator_object
models.signals.post_save.connect(create_locator_object, sender=Campground)
| from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = models.TextField()
sites = models.CharField(max_length=128)
elevation = models.CharField(max_length=128)
hookups = models.CharField(max_length=128)
amenities = models.TextField()
point = models.PointField(srid=4326)
objects = models.GeoManager()
def locator_point(self):
return self.point
def __unicode__(self):
return self.name
# integrate with the django-locator app for easy geo lookups if it's installed
if 'locator.objects' in settings.INSTALLED_APPS:
from locator.objects.models import create_locator_object
models.signals.post_save.connect(create_locator_object, sender=Campground)
| Include an override to the default manager to allow geospatial querying. | Include an override to the default manager to allow geospatial querying.
| Python | bsd-3-clause | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds | ---
+++
@@ -13,6 +13,8 @@
amenities = models.TextField()
point = models.PointField(srid=4326)
+ objects = models.GeoManager()
+
def locator_point(self):
return self.point
|
f0dd6411458a19985408404d511584f7c7e26e38 | useful/tests/tasks/call_management_command.py | useful/tests/tasks/call_management_command.py | from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_management_command(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
| from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_success(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
def test_failure(self):
t = call_management_command.delay('somethingrandomthatdoesntexist')
self.assertEquals(t.status, 'FAILURE')
| Add failed management command test | Add failed management command test
| Python | isc | yprez/django-useful,yprez/django-useful | ---
+++
@@ -5,6 +5,10 @@
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
- def test_management_command(self):
+ def test_success(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
+
+ def test_failure(self):
+ t = call_management_command.delay('somethingrandomthatdoesntexist')
+ self.assertEquals(t.status, 'FAILURE') |
bfa98f350a3da827da8359a4e6e7373fc11626cd | changeling/models.py | changeling/models.py | import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
},
'additionalProperties': False,
}
def __init__(self, id=None, name=None):
self.id = id or str(uuid.uuid4())
self.name = name
@classmethod
def from_dict(self, data):
self.validate(data)
return Change(**data)
def to_dict(self):
def _generate_set_attributes():
for k in Change.schema['properties'].keys():
val = getattr(self, k)
if val is not None:
yield (k, val)
return dict(_generate_set_attributes())
def __str__(self):
return "<Change id=%s name=%s>" % (self.id, self.name)
@classmethod
def validate(cls, data):
try:
jsonschema.validate(data, cls.schema)
except jsonschema.ValidationError as exc:
raise changeling.exception.ValidationError(exc)
def is_valid(self):
try:
self.validate(self.to_dict())
except changeling.exception.ValidationError:
return False
else:
return True
| import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
'description': {'type': 'string'},
},
'additionalProperties': False,
}
def __init__(self, id=None, name=None, description=None):
self.id = id or str(uuid.uuid4())
self.name = name
self.description = description
@classmethod
def from_dict(self, data):
self.validate(data)
return Change(**data)
def to_dict(self):
def _generate_set_attributes():
for k in Change.schema['properties'].keys():
val = getattr(self, k)
if val is not None:
yield (k, val)
return dict(_generate_set_attributes())
def __str__(self):
return "<Change id=%s name=%s>" % (self.id, self.name)
@classmethod
def validate(cls, data):
try:
jsonschema.validate(data, cls.schema)
except jsonschema.ValidationError as exc:
raise changeling.exception.ValidationError(exc)
def is_valid(self):
try:
self.validate(self.to_dict())
except changeling.exception.ValidationError:
return False
else:
return True
| Add description attr to Change | Add description attr to Change
| Python | apache-2.0 | bcwaldon/changeling,bcwaldon/changeling | ---
+++
@@ -12,13 +12,15 @@
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
+ 'description': {'type': 'string'},
},
'additionalProperties': False,
}
- def __init__(self, id=None, name=None):
+ def __init__(self, id=None, name=None, description=None):
self.id = id or str(uuid.uuid4())
self.name = name
+ self.description = description
@classmethod
def from_dict(self, data): |
0165e350a8b49e11b119c6393de93b28f9523dca | fedoracommunity/mokshaapps/packages/controllers/bugs.py | fedoracommunity/mokshaapps/packages/controllers/bugs.py | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
class BugsDashboard(DashboardContainer, ContextAwareWidget):
template = 'mako:fedoracommunity.mokshaapps.packages.templates.single_col_dashboard'
layout = [Category('content-col-apps',[])]
bugs_dashboard = BugsDashboard
class BugsController(Controller):
@expose('mako:moksha.templates.widget')
def index(self, package):
tmpl_context.widget = bugs_dashboard
return {'package': package}
| from tw.api import Widget as TWWidget
from pylons import cache
from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.lib.helpers import Widget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget, Grid
from moksha.api.connectors import get_connector
from tg import expose, tmpl_context, require, request
class BugStatsWidget(TWWidget):
template='mako:fedoracommunity.mokshaapps.packages.templates.bugs_stats_widget'
params = ['id', 'product', 'component', 'version', 'num_closed', 'num_open', 'num_new']
product = 'Fedora'
version = 'rawhide'
component = None
num_closed = num_open = num_new = '-'
bug_stats_widget = BugStatsWidget('bug_stats')
class BugsGrid(Grid):
template='mako:fedoracommunity.mokshaapps.packages.templates.bugs_table_widget'
def update_params(self, d):
d['resource'] = 'bugzilla'
d['resource_path'] = 'query_bugs'
super(BugsGrid, self).update_params(d)
bugs_grid = BugsGrid('bugs_grid')
class BugsDashboard(DashboardContainer, ContextAwareWidget):
template = 'mako:fedoracommunity.mokshaapps.packages.templates.single_col_dashboard'
layout = [Category('content-col-apps',[
Widget('Dashboard', bug_stats_widget,
params={'filters':{'package': ''}}),
Widget('Recently Filed Bugs',
bugs_grid,
params={'filters':{'package': ''}}),
])]
def update_params(self, d):
package = d.get('package')
conn = get_connector('pkgdb')
info = conn.get_basic_package_info(package)
d['pkg_summary'] = info['summary']
super(BugsDashboard, self).update_params(d)
bugs_dashboard = BugsDashboard('bugs_dashboard')
class BugsController(Controller):
@expose('mako:moksha.templates.widget')
def index(self, package):
tmpl_context.widget = bugs_dashboard
return {'options': {'package': package}}
| Add BugStats and BugsGrid widgets | Add BugStats and BugsGrid widgets
| Python | agpl-3.0 | Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages | ---
+++
@@ -1,18 +1,61 @@
+from tw.api import Widget as TWWidget
+from pylons import cache
from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
+from moksha.lib.helpers import Widget
from moksha.api.widgets.containers import DashboardContainer
-from moksha.api.widgets import ContextAwareWidget
+from moksha.api.widgets import ContextAwareWidget, Grid
+from moksha.api.connectors import get_connector
from tg import expose, tmpl_context, require, request
+class BugStatsWidget(TWWidget):
+ template='mako:fedoracommunity.mokshaapps.packages.templates.bugs_stats_widget'
+ params = ['id', 'product', 'component', 'version', 'num_closed', 'num_open', 'num_new']
+ product = 'Fedora'
+ version = 'rawhide'
+ component = None
+
+ num_closed = num_open = num_new = '-'
+
+
+bug_stats_widget = BugStatsWidget('bug_stats')
+
+
+class BugsGrid(Grid):
+ template='mako:fedoracommunity.mokshaapps.packages.templates.bugs_table_widget'
+
+ def update_params(self, d):
+ d['resource'] = 'bugzilla'
+ d['resource_path'] = 'query_bugs'
+ super(BugsGrid, self).update_params(d)
+
+bugs_grid = BugsGrid('bugs_grid')
+
+
class BugsDashboard(DashboardContainer, ContextAwareWidget):
template = 'mako:fedoracommunity.mokshaapps.packages.templates.single_col_dashboard'
- layout = [Category('content-col-apps',[])]
+ layout = [Category('content-col-apps',[
+ Widget('Dashboard', bug_stats_widget,
+ params={'filters':{'package': ''}}),
+ Widget('Recently Filed Bugs',
+ bugs_grid,
+ params={'filters':{'package': ''}}),
+ ])]
-bugs_dashboard = BugsDashboard
+ def update_params(self, d):
+ package = d.get('package')
+ conn = get_connector('pkgdb')
+ info = conn.get_basic_package_info(package)
+ d['pkg_summary'] = info['summary']
+ super(BugsDashboard, self).update_params(d)
+
+
+bugs_dashboard = BugsDashboard('bugs_dashboard')
class BugsController(Controller):
+
@expose('mako:moksha.templates.widget')
def index(self, package):
tmpl_context.widget = bugs_dashboard
- return {'package': package}
+ return {'options': {'package': package}} |
0ff8c816d739deb19352b6e49cab86ddbde948fb | openelex/tasks/__init__.py | openelex/tasks/__init__.py | from invoke import Collection
from mongoengine import ConnectionError
from openelex.settings import init_db
from fetch import fetch
import archive, cache, datasource, load, load_metadata, transform, validate, bake
# Build tasks namespace
ns = Collection()
ns.add_task(fetch)
ns.add_collection(archive)
ns.add_collection(cache)
ns.add_collection(datasource)
ns.add_collection(load)
ns.add_collection(load_metadata)
ns.add_collection(transform)
ns.add_collection(validate)
ns.add_collection(bake)
# Initialize prod Mongo connection
try:
init_db()
except ConnectionError:
pass
| from invoke import Collection
from mongoengine import ConnectionError
from openelex.settings import init_db
from fetch import fetch
import archive, cache, datasource, load, load_metadata, transform, validate
# TODO: Add bake task back in
# import bake
# Build tasks namespace
ns = Collection()
ns.add_task(fetch)
ns.add_collection(archive)
ns.add_collection(cache)
ns.add_collection(datasource)
ns.add_collection(load)
ns.add_collection(load_metadata)
ns.add_collection(transform)
ns.add_collection(validate)
#ns.add_collection(bake)
# Initialize prod Mongo connection
try:
init_db()
except ConnectionError:
pass
| Disable bake for now because it doesn't match rawresult models | Disable bake for now because it doesn't match rawresult models
| Python | mit | cathydeng/openelections-core,datamade/openelections-core,openelections/openelections-core,cathydeng/openelections-core,openelections/openelections-core,datamade/openelections-core | ---
+++
@@ -4,7 +4,9 @@
from openelex.settings import init_db
from fetch import fetch
-import archive, cache, datasource, load, load_metadata, transform, validate, bake
+import archive, cache, datasource, load, load_metadata, transform, validate
+# TODO: Add bake task back in
+# import bake
# Build tasks namespace
@@ -17,7 +19,7 @@
ns.add_collection(load_metadata)
ns.add_collection(transform)
ns.add_collection(validate)
-ns.add_collection(bake)
+#ns.add_collection(bake)
# Initialize prod Mongo connection
try: |
46ab04db26f6330e732abdf4284242bd83179684 | lametro/management/commands/refresh_guid.py | lametro/management/commands/refresh_guid.py | from django.core.management.base import BaseCommand
from django.conf import settings
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = LegistarAPIBillScraper()
scraper.BASE_URL = 'https://webapi.legistar.com/v1/metrotest'
scraper.retry_attempts = 0
scraper.requests_per_minute = 0
all_topics = scraper.topics()
# Delete topics not currently in use
current_topics = Subject.objects.values_list('subject', flat=True)
deleted, _ = SubjectGuid.objects.exclude(name__in=current_topics).delete()
self.stdout.write('Removed {0} stale topics'.format(deleted))
total_created = 0
for topic in all_topics:
subject, created = SubjectGuid.objects.get_or_create(
name=topic['IndexName'],
guid=topic['api_metadata']
)
if created:
total_created += 1
self.stdout.write('{0} topics created'.format(total_created))
| from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import IntegrityError
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = LegistarAPIBillScraper()
scraper.BASE_URL = 'https://webapi.legistar.com/v1/metro'
scraper.retry_attempts = 0
scraper.requests_per_minute = 0
all_topics = scraper.topics()
# Delete topics not currently in use
current_topics = Subject.objects.values_list('subject', flat=True)
deleted, _ = SubjectGuid.objects.exclude(name__in=current_topics).delete()
self.stdout.write('Removed {0} stale topics'.format(deleted))
total_created = 0
total_updated = 0
total_noop = 0
for topic in all_topics:
try:
subject, created = SubjectGuid.objects.get_or_create(
name=topic['IndexName'],
guid=topic['api_metadata']
)
except IntegrityError as e:
# This exception will be raised if get_or_create tries to create
# a SubjectGuid with a name that already exists. The Legistar
# API should not contain duplicates, i.e., the GUID has changed.
# Update the GUID on the existing topic.
subject = SubjectGuid.objects.get(name=topic['IndexName'])
subject.guid = topic['api_metadata']
subject.save()
total_updated += 1
else:
if created:
total_created += 1
else:
total_noop += 1
self.stdout.write('Created {0} new topics'.format(total_created))
self.stdout.write('Updated {0} existing topics'.format(total_updated))
self.stdout.write("No-op'ed {0} topics".format(total_updated))
| Update API path, handle updated SubjectGuid | Update API path, handle updated SubjectGuid
| Python | mit | datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic | ---
+++
@@ -1,5 +1,7 @@
from django.core.management.base import BaseCommand
from django.conf import settings
+from django.db.utils import IntegrityError
+
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
@@ -8,7 +10,7 @@
def handle(self, *args, **options):
scraper = LegistarAPIBillScraper()
- scraper.BASE_URL = 'https://webapi.legistar.com/v1/metrotest'
+ scraper.BASE_URL = 'https://webapi.legistar.com/v1/metro'
scraper.retry_attempts = 0
scraper.requests_per_minute = 0
@@ -21,12 +23,30 @@
self.stdout.write('Removed {0} stale topics'.format(deleted))
total_created = 0
+ total_updated = 0
+ total_noop = 0
+
for topic in all_topics:
- subject, created = SubjectGuid.objects.get_or_create(
- name=topic['IndexName'],
- guid=topic['api_metadata']
- )
- if created:
- total_created += 1
+ try:
+ subject, created = SubjectGuid.objects.get_or_create(
+ name=topic['IndexName'],
+ guid=topic['api_metadata']
+ )
+ except IntegrityError as e:
+ # This exception will be raised if get_or_create tries to create
+ # a SubjectGuid with a name that already exists. The Legistar
+ # API should not contain duplicates, i.e., the GUID has changed.
+ # Update the GUID on the existing topic.
+ subject = SubjectGuid.objects.get(name=topic['IndexName'])
+ subject.guid = topic['api_metadata']
+ subject.save()
+ total_updated += 1
+ else:
+ if created:
+ total_created += 1
+ else:
+ total_noop += 1
- self.stdout.write('{0} topics created'.format(total_created))
+ self.stdout.write('Created {0} new topics'.format(total_created))
+ self.stdout.write('Updated {0} existing topics'.format(total_updated))
+ self.stdout.write("No-op'ed {0} topics".format(total_updated)) |
7798d5d8c625a4cbdb689cb7ffa38c2f90c0dc02 | dduplicated/fileManager.py | dduplicated/fileManager.py | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path, src, link)).start()
deleted_files.append(path)
if link:
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
| import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path, src, link)).start()
deleted_files.append(path)
if link:
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
# Return empty list object
return []
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
| Fix in error when analyze directories without duplicates | Fix in error when analyze directories without duplicates
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -37,8 +37,9 @@
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
- return None
-
+ # Return empty list object
+ return []
+
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link)) |
bfea504373593bbfbe08ad423a8e98ecbd77565e | mule/utils/multithreading.py | mule/utils/multithreading.py | from collections import defaultdict
from Queue import Queue
from threading import Thread
import thread
_results = defaultdict(list)
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kwargs, ident = self.tasks.get()
try:
_results[ident].append({
'func': func,
'args': args,
'kwargs': kwargs,
'result': func(*args, **kwargs),
})
finally:
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in xrange(num_threads):
Worker(self.tasks)
def add(self, func, *args, **kwargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kwargs, id(self)), False)
def join(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
return _results[id(self)] | from collections import defaultdict
from Queue import Queue
from threading import Thread
import thread
_results = defaultdict(list)
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kwargs, ident = self.tasks.get()
try:
_results[ident].append({
'func': func,
'args': args,
'kwargs': kwargs,
'result': func(*args, **kwargs),
})
finally:
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in xrange(num_threads):
Worker(self.tasks)
def add(self, func, *args, **kwargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kwargs, id(self)))
def join(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
return _results[id(self)] | Add needs to block so the queue doesnt end up full | Add needs to block so the queue doesnt end up full
| Python | apache-2.0 | disqus/mule | ---
+++
@@ -35,7 +35,7 @@
def add(self, func, *args, **kwargs):
"""Add a task to the queue"""
- self.tasks.put((func, args, kwargs, id(self)), False)
+ self.tasks.put((func, args, kwargs, id(self)))
def join(self):
"""Wait for completion of all the tasks in the queue""" |
63935d3c62dad19d2668d0e0633ebd4ce6e6ed26 | actions/kvstore.py | actions/kvstore.py | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = KeyValuePair()
instance.id = client.keys.get_by_name(key).name
instance.name = key
instance.value = value
try:
kvstore = getattr(client.keys, action)
kvp = kvstore(instance)
except Exception as e:
raise
if action == 'delete':
return kvp
else:
return kvp.serialize()
| from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = client.keys.get_by_name(key) or KeyValuePair()
instance.id = key
instance.name = key
instance.value = value
kvp = client.keys.update(instance) if action in ['create', 'update'] else None
if action == 'delete':
return kvp
else:
return kvp.serialize()
| Fix create action for key value pair | Fix create action for key value pair
| Python | apache-2.0 | StackStorm/st2cd,StackStorm/st2cd | ---
+++
@@ -25,16 +25,12 @@
return kvp.value
else:
- instance = KeyValuePair()
- instance.id = client.keys.get_by_name(key).name
+ instance = client.keys.get_by_name(key) or KeyValuePair()
+ instance.id = key
instance.name = key
instance.value = value
- try:
- kvstore = getattr(client.keys, action)
- kvp = kvstore(instance)
- except Exception as e:
- raise
+ kvp = client.keys.update(instance) if action in ['create', 'update'] else None
if action == 'delete':
return kvp |
c18f21995ff76681fdfa7e511019f5f27bfea749 | playserver/trackchecker.py | playserver/trackchecker.py | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
if (song != self.currentSong or artist != self.currentArtist
or album != self.currentAlbum):
self.currentSong = song
self.currentArtist = artist
self.currentAlbum = album
self._callListeners()
if self.timer != None:
self.startTimer()
def registerListener(self, function):
_listeners.append(function)
def _callListeners(self):
for listener in _listeners:
listener()
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong)
self.timer.daemon = True
self.timer.start()
def cancelTimer(self):
self.timer.cancel()
self.timer = None
| from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
if (song != self.currentSong or artist != self.currentArtist
or album != self.currentAlbum):
self.currentSong = song
self.currentArtist = artist
self.currentAlbum = album
self._callListeners()
if self.timer != None:
self.startTimer()
def registerListener(self, function):
_listeners.append(function)
def _callListeners(self):
data = {
"song": track.getCurrentSong(),
"artist": track.getCurrentArtist(),
"album": track.getCurrentAlbum()
}
for listener in _listeners:
listener(data)
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong)
self.timer.daemon = True
self.timer.start()
def cancelTimer(self):
self.timer.cancel()
self.timer = None
| Send data in trackChecker callbacks | Send data in trackChecker callbacks
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver | ---
+++
@@ -31,8 +31,14 @@
_listeners.append(function)
def _callListeners(self):
+ data = {
+ "song": track.getCurrentSong(),
+ "artist": track.getCurrentArtist(),
+ "album": track.getCurrentAlbum()
+ }
+
for listener in _listeners:
- listener()
+ listener(data)
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong) |
51080ad6e8ad38ea8c22593b07d70b27965545bd | api/views/users.py | api/views/users.py | from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@detail_route(methods=['put'])
def follow(self, request, pk=None): # follows a given user
pass
@detail_route(methods=['put'])
def unfollow(self, request, pk=None): # unfollows a given user
pass
# Override create to return token
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
headers = self.get_success_headers(serializer.data)
response = serializer.data
response['access_token'] = Token.objects.get(user=user).key
return Response(response, status=status.HTTP_201_CREATED, headers=headers)
| from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes_by_action = {'create': []}
@detail_route(methods=['put'])
def follow(self, request, pk=None): # follows a given user
pass
@detail_route(methods=['put'])
def unfollow(self, request, pk=None): # unfollows a given user
pass
# Override create to return token
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
headers = self.get_success_headers(serializer.data)
response = serializer.data
response['access_token'] = Token.objects.get(user=user).key
return Response(response, status=status.HTTP_201_CREATED, headers=headers)
# Token isn't required when creating user (signup)
def get_permissions(self):
try:
return [permission() for permission in self.permission_classes_by_action[self.action]]
except KeyError:
return [permission() for permission in self.permission_classes]
| Make signup not require token in API | Make signup not require token in API
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq | ---
+++
@@ -10,6 +10,8 @@
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
+
+ permission_classes_by_action = {'create': []}
@detail_route(methods=['put'])
def follow(self, request, pk=None): # follows a given user
@@ -28,3 +30,10 @@
response = serializer.data
response['access_token'] = Token.objects.get(user=user).key
return Response(response, status=status.HTTP_201_CREATED, headers=headers)
+
+ # Token isn't required when creating user (signup)
+ def get_permissions(self):
+ try:
+ return [permission() for permission in self.permission_classes_by_action[self.action]]
+ except KeyError:
+ return [permission() for permission in self.permission_classes] |
6d7c1172ff156f376c61476bccf9912598059d19 | rabbitpy/__init__.py | rabbitpy/__init__.py | __version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
| __version__ = '0.10.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
| Fix order of operations issues | Fix order of operations issues
| Python | bsd-3-clause | jonahbull/rabbitpy,gmr/rabbitpy,gmr/rabbitpy | ---
+++
@@ -1,5 +1,19 @@
__version__ = '0.10.0'
version = __version__
+
+DEBUG = False
+
+import logging
+
+try:
+ from logging import NullHandler
+except ImportError:
+ # Python 2.6 does not have a NullHandler
+ class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+
+logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
@@ -16,17 +30,3 @@
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
-
-import logging
-
-try:
- from logging import NullHandler
-except ImportError:
- # Python 2.6 does not have a NullHandler
- class NullHandler(logging.Handler):
- def emit(self, record):
- pass
-
-logging.getLogger('rabbitpy').addHandler(NullHandler())
-
-DEBUG = False |
7c60024684024b604eb19a02d119adab547ed0d1 | ovp_organizations/migrations/0023_auto_20170627_0236.py | ovp_organizations/migrations/0023_auto_20170627_0236.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='address',
field=models.OneToOneField(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='ovp_core.SimpleAddress', verbose_name='address'),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
('ovp_core', '0011_simpleaddress'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='address',
field=models.OneToOneField(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='ovp_core.SimpleAddress', verbose_name='address'),
),
]
| Add ovp_core_0011 migration as dependency for ovp_organizations_0023 | Add ovp_core_0011 migration as dependency for ovp_organizations_0023
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations | ---
+++
@@ -10,6 +10,7 @@
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
+ ('ovp_core', '0011_simpleaddress'),
]
operations = [ |
b2f40d9b1ed9d78a4fdc1f73e64575a26d117d0c | nuitka/tools/release/msi_create/__main__.py | nuitka/tools/release/msi_create/__main__.py | # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
""" Release: Create Windows MSI files for Nuitka
"""
from nuitka.tools.release.MSI import createMSIPackage
def main():
createMSIPackage()
if __name__ == "__main__":
main()
| # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
""" Release: Create Windows MSI files for Nuitka
"""
import os
import shutil
from nuitka.tools.Basics import goHome
from nuitka.tools.release.MSI import createMSIPackage
def main():
goHome()
msi_filename = createMSIPackage()
if not os.path.exists("msi"):
os.makedirs("msi")
shutil.move(msi_filename, "msi")
if __name__ == "__main__":
main()
| Copy created MSI to dedicated folder. | Release: Copy created MSI to dedicated folder.
* The "dist" folder is erased each time and we determine the result
name from being the only MSI file.
| Python | apache-2.0 | kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka | ---
+++
@@ -19,11 +19,23 @@
"""
+import os
+import shutil
+
+from nuitka.tools.Basics import goHome
from nuitka.tools.release.MSI import createMSIPackage
def main():
- createMSIPackage()
+ goHome()
+
+ msi_filename = createMSIPackage()
+
+ if not os.path.exists("msi"):
+ os.makedirs("msi")
+
+ shutil.move(msi_filename, "msi")
+
if __name__ == "__main__":
main() |
41a8d7e1e762133fb24608524e229b882fabda22 | packages/pegasus-python/src/Pegasus/service/defaults.py | packages/pegasus-python/src/Pegasus/service/defaults.py | import os
import tempfile
# SERVER CONFIGURATION
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5000
# SSL config: path to certificate and private key files
CERTIFICATE = None
PRIVATE_KEY = None
# Max number of processes to fork when handling requests
MAX_PROCESSES = 10
# Enable debugging
DEBUG = False
# The secret key used by Flask to encrypt session keys
SECRET_KEY = os.urandom(24)
# Authentication method to use (NoAuthentication or PAMAuthentication)
AUTHENTICATION = "PAMAuthentication"
PROCESS_SWITCHING = True
# Flask cache configuration
CACHE_TYPE = "filesystem"
CACHE_DIR = os.path.join(tempfile.gettempdir(), "pegasus-service")
#
# Authorization -
# None, '', False -> User can only access their own data.
# * -> All users are admin users and can access data of any other user.
# {'u1', .., 'un'} OR ['u1', .., 'un'] -> Only users in the set/list are admin users.
#
ADMIN_USERS = None
# CLIENT CONFIGURATION
# User credentials
USERNAME = ""
PASSWORD = ""
# ENSEMBLE MANAGER CONFIGURATION
# Workflow processing interval in seconds
EM_INTERVAL = 60
# Directory to store data
STORAGE_DIRECTORY = "/var/pegasus"
# Path to Pegasus home directory
# PEGASUS_HOME = "/usr"
# Path to Condor home directory
# CONDOR_HOME = "/usr"
| import os
import tempfile
# SERVER CONFIGURATION
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5000
# SSL config: path to certificate and private key files
CERTIFICATE = None
PRIVATE_KEY = None
# Max number of processes to fork when handling requests
MAX_PROCESSES = 10
# Enable debugging
DEBUG = False
# The secret key used by Flask to encrypt session keys
SECRET_KEY = os.urandom(24)
# Authentication method to use (NoAuthentication or PAMAuthentication)
AUTHENTICATION = "PAMAuthentication"
PROCESS_SWITCHING = True
# Flask cache configuration
CACHE_TYPE = "flask_caching.backends.SimpleCache"
#
# Authorization -
# None, '', False -> User can only access their own data.
# * -> All users are admin users and can access data of any other user.
# {'u1', .., 'un'} OR ['u1', .., 'un'] -> Only users in the set/list are admin users.
#
ADMIN_USERS = None
# CLIENT CONFIGURATION
# User credentials
USERNAME = ""
PASSWORD = ""
# ENSEMBLE MANAGER CONFIGURATION
# Workflow processing interval in seconds
EM_INTERVAL = 60
# Directory to store data
STORAGE_DIRECTORY = "/var/pegasus"
# Path to Pegasus home directory
# PEGASUS_HOME = "/usr"
# Path to Condor home directory
# CONDOR_HOME = "/usr"
| Use SimpleCache instead of Filesystemcache as it can cause errors due to use of different pickle versions. | Use SimpleCache instead of Filesystemcache as it can cause errors due to use of different pickle versions.
| Python | apache-2.0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | ---
+++
@@ -24,8 +24,7 @@
PROCESS_SWITCHING = True
# Flask cache configuration
-CACHE_TYPE = "filesystem"
-CACHE_DIR = os.path.join(tempfile.gettempdir(), "pegasus-service")
+CACHE_TYPE = "flask_caching.backends.SimpleCache"
#
# Authorization - |
dda88345334985796dac2095f6e78bb106bc19b3 | pullpush/pullpush.py | pullpush/pullpush.py | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(self.repo_dir)
origin = self.repo.create_remote('origin', source_repo)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def set_target_repo(self, new_url):
"""
Changes the target url of the previously pulled repo.
"""
origin = self.repo.remotes.origin
cw = origin.config_writer
cw.set("url", new_url)
cw.release()
def push(self, target_repo):
"""
Pushes the previously pulled repo to the target_repo.
"""
origin = self.repo.remotes.origin
self.set_target_repo(target_repo)
self.repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master)
origin.push()
| #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(self.repo_dir)
origin = self.repo.create_remote('origin', source_repo)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def set_target_repo(self, new_url):
"""
Changes the target url of the previously pulled repo.
"""
origin = self.repo.remotes.origin
cw = origin.config_writer
cw.set("url", new_url)
cw.release()
def push(self, target_repo):
"""
Pushes the previously pulled repo to the target_repo.
"""
if self.repo is None:
# TODO Better handling
return
origin = self.repo.remotes.origin
self.set_target_repo(target_repo)
self.repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master)
origin.push()
| Check of repo was pulled | Check of repo was pulled
| Python | mit | martialblog/git-pullpush | ---
+++
@@ -35,6 +35,10 @@
Pushes the previously pulled repo to the target_repo.
"""
+ if self.repo is None:
+ # TODO Better handling
+ return
+
origin = self.repo.remotes.origin
self.set_target_repo(target_repo)
self.repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master) |
beb8f12e4a8290d4107cdb91a321a6618a038ef9 | rose_trellis/util.py | rose_trellis/util.py | from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.strip('/')
newpath = urljoin(TRELLO_URL_BASE, part)
while newpath.endswith('/'):
newpath = newpath[:-1]
return newpath
def easy_run(func: Callable[Any], *args, **kwargs) -> Any:
el = asyncio.get_event_loop()
return el.run_until_complete(func(*args, **kwargs))
| from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.strip('/')
newpath = urljoin(TRELLO_URL_BASE, part)
while newpath.endswith('/'):
newpath = newpath[:-1]
return newpath
def easy_run(gen) -> Any:
el = asyncio.get_event_loop()
return el.run_until_complete(gen)
| Make easy_run better by taking the generator from coroutines | Make easy_run better by taking the generator from coroutines
| Python | mit | dmwyatt/rose_trellis | ---
+++
@@ -24,6 +24,6 @@
return newpath
-def easy_run(func: Callable[Any], *args, **kwargs) -> Any:
+def easy_run(gen) -> Any:
el = asyncio.get_event_loop()
- return el.run_until_complete(func(*args, **kwargs))
+ return el.run_until_complete(gen) |
2c15d96a7d77269fbe41e5b2940873fc849d411a | random_projection.py | random_projection.py | """
Random projection, Assignment 1c
"""
| """
Random projection, Assignment 1c
"""
import numpy as np
import matplotlib.pylab as plt
import random, mnist_dataloader
from numpy import dtype
"""
Generate random projection matrix R
@param: k, the reduced number of dimensions
@param: d, the original number of dimensions
@return: R, the generated random projection matrix, k * d size
"""
def generate_random_projection_matrix(k, d):
R = np.zeros((k, d), dtype = np.float64)
for r in np.nditer(R, op_flags=['readwrite']):
r[...] = random.randint(0, 1)
if r[...] == 0:
r[...] = -1
R *= 1.0 / np.sqrt(k)
return R
"""
random projection matrix P into R
@param R: random projection matrix
@param P: matrix to be reduced in dimension
@return: Q: projected matrix of P on R
"""
def random_projection(R, P):
if R.shape[1] != P.shape[0]:
return False
print R.shape, P.shape
return np.dot(R, P)
if __name__ == "__main__":
# load data set
training_data, validation_data, test_data = mnist_dataloader.load_data()
# row vector (matrix)
training_data_instances = training_data[0]
training_data_labels = training_data[1]
# row vector (matrix)
test_data_instances = test_data[0]
test_data_labels = test_data[1]
# dimension of a training data instance
d = training_data_instances.shape[1]
for k in [50, 100, 500]:
random_projection_matrix = generate_random_projection_matrix(k, d)
# transpose to column vector (matrix) before projection and recover after projection
random_projected_matrix = np.transpose(random_projection(random_projection_matrix, np.transpose(training_data_instances[0:20])))
print random_projected_matrix[0], random_projected_matrix.shape
| Add random projection matrix generation and random projection. | Add random projection matrix generation and random projection.
| Python | mit | lidalei/DataMining | ---
+++
@@ -1,3 +1,59 @@
"""
Random projection, Assignment 1c
"""
+import numpy as np
+import matplotlib.pylab as plt
+import random, mnist_dataloader
+from numpy import dtype
+
+"""
+Generate random projection matrix R
+@param: k, the reduced number of dimensions
+@param: d, the original number of dimensions
+@return: R, the generated random projection matrix, k * d size
+"""
+
+def generate_random_projection_matrix(k, d):
+ R = np.zeros((k, d), dtype = np.float64)
+ for r in np.nditer(R, op_flags=['readwrite']):
+ r[...] = random.randint(0, 1)
+ if r[...] == 0:
+ r[...] = -1
+
+ R *= 1.0 / np.sqrt(k)
+
+ return R
+
+"""
+random projection matrix P into R
+@param R: random projection matrix
+@param P: matrix to be reduced in dimension
+@return: Q: projected matrix of P on R
+"""
+def random_projection(R, P):
+ if R.shape[1] != P.shape[0]:
+ return False
+
+ print R.shape, P.shape
+
+ return np.dot(R, P)
+
+if __name__ == "__main__":
+ # load data set
+ training_data, validation_data, test_data = mnist_dataloader.load_data()
+ # row vector (matrix)
+ training_data_instances = training_data[0]
+ training_data_labels = training_data[1]
+ # row vector (matrix)
+ test_data_instances = test_data[0]
+ test_data_labels = test_data[1]
+ # dimension of a training data instance
+ d = training_data_instances.shape[1]
+
+ for k in [50, 100, 500]:
+ random_projection_matrix = generate_random_projection_matrix(k, d)
+ # transpose to column vector (matrix) before projection and recover after projection
+ random_projected_matrix = np.transpose(random_projection(random_projection_matrix, np.transpose(training_data_instances[0:20])))
+
+ print random_projected_matrix[0], random_projected_matrix.shape
+ |
5596f599287d36126b3a6e30e7579eb00ed07d73 | downstream_farmer/utils.py | downstream_farmer/utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to keep
the 2 & 3 stuff all in one place, meaning rather than try to import the
urllib stuff twice in each file where url-safe strings are needed, we keep
it all in one file: here.
Supporting multiple Pythons is hard.
:param string: String to URLify
:return: URLified string
"""
return quote_plus(string)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to keep
the 2 & 3 stuff all in one place, meaning rather than try to import the
urllib stuff twice in each file where url-safe strings are needed, we keep
it all in one file: here.
Supporting multiple Pythons is hard.
:param string: String to URLify
:return: URLified string
"""
return quote(string)
| Fix method to use quote, not quote_plus | Fix method to use quote, not quote_plus
| Python | mit | Storj/downstream-farmer | ---
+++
@@ -3,9 +3,9 @@
try:
- from urllib import quote_plus
+ from urllib import quote
except ImportError:
- from urllib.parse import quote_plus
+ from urllib.parse import quote
def urlify(string):
@@ -20,4 +20,4 @@
:param string: String to URLify
:return: URLified string
"""
- return quote_plus(string)
+ return quote(string) |
f842cf7605018e85b13f27f3a0886122e4cbb80c | expert_tourist/views.py | expert_tourist/views.py | from collections import namedtuple
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt_identity())
@api.route('/sign_up', methods=['POST'])
def sign_up():
schema = UserSchema().loads(request.data)
if schema.errors:
raise APIException('Fields <username, email, password> are required')
user = schema.data
if not user.exists():
user.save()
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('A user with the email {} already exists. Forgot your password?'.format(user.email))
@api.route('/sign_in', methods=['POST'])
def sign_in():
conditions = [request.json.get('username', None), request.json.get('password', None)]
if not all(conditions):
raise APIException('Fields <username, password> are required.')
user = User.validate_login(conditions[0], conditions[1])
if user:
print(user.token)
return jsonify(token=user.token)
else:
raise APIException('Invalid login credentials', status_code=401)
| from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt_identity())
@api.route('/sign_up', methods=['POST'])
def sign_up():
schema = UserSchema().loads(request.data)
if schema.errors:
raise APIException('Fields <username, email, password> are required')
user = schema.data
if not user.exists():
user.save()
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('A user with the email {} already exists. Forgot your password?'.format(user.email))
@api.route('/sign_in', methods=['POST'])
def sign_in():
conditions = [request.json.get('username', None), request.json.get('password', None)]
if not all(conditions):
raise APIException('Fields <username, password> are required.')
user = User.validate_login(conditions[0], conditions[1])
if user:
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('Invalid login credentials', status_code=401)
| Return the whole user in successful login | Return the whole user in successful login
| Python | mit | richin13/expert-tourist | ---
+++
@@ -1,5 +1,3 @@
-from collections import namedtuple
-
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
@@ -41,7 +39,6 @@
user = User.validate_login(conditions[0], conditions[1])
if user:
- print(user.token)
- return jsonify(token=user.token)
+ return jsonify(UserSchema().dump(user).data)
else:
raise APIException('Invalid login credentials', status_code=401) |
01a9b6457d78dd583637bf8174edda40e2bd3276 | django_website/blog/feeds.py | django_website/blog/feeds.py | from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self):
return Entry.objects.published()[:10]
def item_pubdate(self, item):
return item.pub_date
| from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self):
return Entry.objects.published()[:10]
def item_pubdate(self, item):
return item.pub_date
def item_author_name(self, item):
return item.author
def item_description(self, item):
return item.body_html
| Add author name and body to the weblog RSS feed. | Add author name and body to the weblog RSS feed.
| Python | bsd-3-clause | alawnchen/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,khkaminska/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,rmoorman/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoproject.com,relekang/djangoproject.com,rmoorman/djangoproject.com,relekang/djangoproject.com,rmoorman/djangoproject.com,hassanabidpk/djangoproject.com,vxvinh1511/djangoproject.com,vxvinh1511/djangoproject.com,khkaminska/djangoproject.com,nanuxbe/django,alawnchen/djangoproject.com,khkaminska/djangoproject.com,vxvinh1511/djangoproject.com,xavierdutreilh/djangoproject.com,xavierdutreilh/djangoproject.com,hassanabidpk/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoproject.com,relekang/djangoproject.com,hassanabidpk/djangoproject.com,vxvinh1511/djangoproject.com,django/djangoproject.com,alawnchen/djangoproject.com,relekang/djangoproject.com,gnarf/djangoproject.com,gnarf/djangoproject.com,hassanabidpk/djangoproject.com,nanuxbe/django,alawnchen/djangoproject.com | ---
+++
@@ -13,3 +13,9 @@
def item_pubdate(self, item):
return item.pub_date
+
+ def item_author_name(self, item):
+ return item.author
+
+ def item_description(self, item):
+ return item.body_html |
5adb6de6b926a54dc9a6dd334a34d42dd2044481 | src/pushover_complete/pushover_api.py | src/pushover_complete/pushover_api.py | import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound=None, html=False):
if priority == 2:
if retry is None or expire is None:
raise PushoverCompleteError('Must specify `retry` and `expire` with priority 2.')
payload = {
'token': self.token,
'user': user,
'message': message,
'device': device,
'title': title,
'url': url,
'url_title': url_title,
'priority': priority,
'retry': retry,
'expire': expire,
'timestamp': timestamp,
'sound': sound,
'html': html
}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
r = requests.post(
'https://api.pushover.net/1/messages.json',
data=payload,
headers=headers
)
return r
| import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound=None, html=False):
if priority == 2:
if retry is None or expire is None:
raise PushoverCompleteError('Must specify `retry` and `expire` with priority 2.')
payload = {
'token': self.token,
'user': user,
'message': message,
'device': device,
'title': title,
'url': url,
'url_title': url_title,
'priority': priority,
'retry': retry,
'expire': expire,
'timestamp': timestamp,
'sound': sound,
'html': html
}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
r = requests.post(
'https://api.pushover.net/1/messages.json',
data=payload,
headers=headers
def get_sounds(self):
resp = requests.get(
urljoin(PUSHOVER_API_URL, 'sounds.json'),
data={'token': self.token}
)
sounds = resp.json().get('sounds', None)
if sounds:
return sounds
else:
raise PushoverCompleteError('Could not retrieve sounds')
| Split send_message out in to _send_message to reuse functionality later | Split send_message out in to _send_message to reuse functionality later
| Python | mit | scolby33/pushover_complete | ---
+++
@@ -31,5 +31,16 @@
'https://api.pushover.net/1/messages.json',
data=payload,
headers=headers
+ def get_sounds(self):
+ resp = requests.get(
+ urljoin(PUSHOVER_API_URL, 'sounds.json'),
+ data={'token': self.token}
)
- return r
+ sounds = resp.json().get('sounds', None)
+ if sounds:
+ return sounds
+ else:
+ raise PushoverCompleteError('Could not retrieve sounds')
+
+
+ |
f87b8c5b94e3e163f19ea0414d1fb2c42f09c166 | test/test_genmidi.py | test/test_genmidi.py | import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInstance(midi.midi_data, MIDIFile)
def test_seq_notes_with_more_tracks_than_exists(self):
midi = Midi(1)
with self.assertRaises(MidiError):
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
def test_seq_notes(self):
midi = Midi(2)
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
class TestWriteMidi(unittest.TestCase):
def test_write_midifile(self):
notes1 = NoteSeq("D4 F#8 R A")
midi = Midi(1, tempo=133)
midi.seq_notes(notes1, track=0)
midi.write(tempfile.TemporaryFile())
| import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInstance(midi.midi_data, MIDIFile)
def test_seq_notes_with_more_tracks_than_exists(self):
midi = Midi(1)
with self.assertRaises(MidiError):
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
def test_seq_notes(self):
midi = Midi(2)
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
def test_seq_chords(self):
chords = [NoteSeq("C E G"), NoteSeq("G B D")]
midi = Midi()
midi.seq_chords(chords)
class TestWriteMidi(unittest.TestCase):
def test_write_midifile(self):
notes1 = NoteSeq("D4 F#8 R A")
midi = Midi(1, tempo=133)
midi.seq_notes(notes1, track=0)
midi.write(tempfile.TemporaryFile())
| Test for sequence of chords | Test for sequence of chords
| Python | mit | palmerev/pyknon,kroger/pyknon | ---
+++
@@ -22,6 +22,11 @@
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
+ def test_seq_chords(self):
+ chords = [NoteSeq("C E G"), NoteSeq("G B D")]
+ midi = Midi()
+ midi.seq_chords(chords)
+
class TestWriteMidi(unittest.TestCase):
def test_write_midifile(self): |
86cf16611fe4126f4345477b24da5c15fed4c1e8 | eval_kernel/eval_kernel.py | eval_kernel/eval_kernel.py | from __future__ import print_function
from jupyter_kernel import MagicKernel
import os
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_kernel_help_on(self, expr, level):
return "Sorry, no help is available on '%s'." % expr
def do_execute_direct(self, code):
try:
return eval(code.strip(), self.env)
except:
try:
exec code.strip() in self.env
except:
return "Error: " + code
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
| from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
| Update eval kernel to use python magic. | Update eval kernel to use python magic.
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -1,7 +1,7 @@
from __future__ import print_function
from jupyter_kernel import MagicKernel
-import os
+
class EvalKernel(MagicKernel):
implementation = 'Eval'
@@ -20,17 +20,25 @@
"""
self.env[name] = value
- def get_kernel_help_on(self, expr, level):
- return "Sorry, no help is available on '%s'." % expr
+ def get_variable(self, name):
+ """
+ Get a variable from the kernel language.
+ """
+ return self.env.get(name, None)
def do_execute_direct(self, code):
- try:
- return eval(code.strip(), self.env)
- except:
- try:
- exec code.strip() in self.env
- except:
- return "Error: " + code
+ python_magic = self.line_magics['python']
+ resp = python_magic.eval(code.strip())
+ if not resp is None:
+ self.Print(str(resp))
+
+ def get_completions(self, token):
+ python_magic = self.line_magics['python']
+ return python_magic.get_completions(token)
+
+ def get_kernel_help_on(self, expr, level=0):
+ python_magic = self.line_magics['python']
+ return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp |
b0b4bad0ca68ebd1927229e85e7116fb63126c65 | src/olympia/zadmin/helpers.py | src/olympia/zadmin/helpers.py | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
| from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
| Remove generate error page from admin site | Remove generate error page from admin site
| Python | bsd-3-clause | bqbn/addons-server,wagnerand/olympia,harry-7/addons-server,wagnerand/addons-server,harikishen/addons-server,psiinon/addons-server,lavish205/olympia,mstriemer/addons-server,kumar303/addons-server,Prashant-Surya/addons-server,mstriemer/olympia,mozilla/addons-server,harikishen/addons-server,Revanth47/addons-server,mstriemer/addons-server,mstriemer/olympia,lavish205/olympia,lavish205/olympia,wagnerand/olympia,diox/olympia,eviljeff/olympia,aviarypl/mozilla-l10n-addons-server,mozilla/olympia,tsl143/addons-server,Revanth47/addons-server,wagnerand/addons-server,psiinon/addons-server,eviljeff/olympia,wagnerand/addons-server,harry-7/addons-server,kumar303/addons-server,wagnerand/olympia,eviljeff/olympia,Prashant-Surya/addons-server,bqbn/addons-server,kumar303/addons-server,Revanth47/addons-server,kumar303/olympia,harry-7/addons-server,kumar303/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/addons-server,mstriemer/addons-server,harikishen/addons-server,mstriemer/olympia,Prashant-Surya/addons-server,mozilla/olympia,diox/olympia,psiinon/addons-server,harry-7/addons-server,wagnerand/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/olympia,mstriemer/olympia,mozilla/addons-server,bqbn/addons-server,Revanth47/addons-server,mstriemer/addons-server,diox/olympia,harikishen/addons-server,wagnerand/addons-server,diox/olympia,atiqueahmedziad/addons-server,psiinon/addons-server,eviljeff/olympia,tsl143/addons-server,mozilla/olympia,kumar303/olympia,lavish205/olympia,atiqueahmedziad/addons-server,tsl143/addons-server,tsl143/addons-server,mozilla/addons-server,mozilla/olympia,bqbn/addons-server,aviarypl/mozilla-l10n-addons-server,Prashant-Surya/addons-server,atiqueahmedziad/addons-server,mozilla/addons-server,atiqueahmedziad/addons-server | ---
+++
@@ -32,7 +32,6 @@
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
- ('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
} |
be964b02036159567efcaecce5b5d905f23985af | deduper/scanfiles.py | deduper/scanfiles.py | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE fileself.
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
| # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE fileself.
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if not os.path.isfile(fullpath):
continue
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
| Check that fullpath is a regular file before continuing | Check that fullpath is a regular file before continuing
| Python | bsd-3-clause | cgspeck/filededuper | ---
+++
@@ -24,6 +24,9 @@
fullpath = os.path.join(root, filename)
+ if not os.path.isfile(fullpath):
+ continue
+
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename)) |
a95e891b637f0182031f229465bcded966100889 | readthedocs/core/models.py | readthedocs/core/models.py | from django.db import models
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(User, unique=True, related_name='profile')
whitelisted = models.BooleanField()
homepage = models.CharField(max_length=100, blank=True)
allow_email = models.BooleanField(help_text='Show your email on VCS contributions.', default=True)
def get_absolute_url(self):
return ('profiles_profile_detail', (), {'username': self.user.username})
get_absolute_url = models.permalink(get_absolute_url)
def __unicode__(self):
return "%s's profile" % self.user.username
def get_contribution_details(self):
"""
Gets the line to put into commits to attribute the author.
Returns a tuple (name, email)
"""
if self.user.first_name and self.user.last_name:
name = '%s %s' % (self.user.first_name, self.user.last_name)
else:
name = self.user.username
if self.allow_email:
email = self.user.email
else:
email = STANDARD_EMAIL
return (name, email)
| from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(User, unique=True, related_name='profile')
whitelisted = models.BooleanField()
homepage = models.CharField(max_length=100, blank=True)
allow_email = models.BooleanField(help_text='Show your email on VCS contributions.', default=True)
def get_absolute_url(self):
return ('profiles_profile_detail', (), {'username': self.user.username})
get_absolute_url = models.permalink(get_absolute_url)
def __unicode__(self):
return "%s's profile" % self.user.username
def get_contribution_details(self):
"""
Gets the line to put into commits to attribute the author.
Returns a tuple (name, email)
"""
if self.user.first_name and self.user.last_name:
name = '%s %s' % (self.user.first_name, self.user.last_name)
else:
name = self.user.username
if self.allow_email:
email = self.user.email
else:
email = STANDARD_EMAIL
return (name, email)
@receiver(post_save, sender=User)
def create_profile(sender, **kwargs):
if kwargs['created'] is True:
UserProfile.objects.create(user_id=kwargs['instance'].id, whitelisted=False)
| Add post save signal for user creation | Add post save signal for user creation
| Python | mit | safwanrahman/readthedocs.org,raven47git/readthedocs.org,sunnyzwh/readthedocs.org,agjohnson/readthedocs.org,d0ugal/readthedocs.org,GovReady/readthedocs.org,kenshinthebattosai/readthedocs.org,jerel/readthedocs.org,jerel/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,titiushko/readthedocs.org,wijerasa/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,ojii/readthedocs.org,kdkeyser/readthedocs.org,d0ugal/readthedocs.org,KamranMackey/readthedocs.org,wanghaven/readthedocs.org,kenshinthebattosai/readthedocs.org,SteveViss/readthedocs.org,mhils/readthedocs.org,takluyver/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,johncosta/private-readthedocs.org,clarkperkins/readthedocs.org,fujita-shintaro/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,attakei/readthedocs-oauth,atsuyim/readthedocs.org,wanghaven/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,nyergler/pythonslides,sunnyzwh/readthedocs.org,fujita-shintaro/readthedocs.org,techtonik/readthedocs.org,atsuyim/readthedocs.org,wijerasa/readthedocs.org,attakei/readthedocs-oauth,Carreau/readthedocs.org,sils1297/readthedocs.org,soulshake/readthedocs.org,attakei/readthedocs-oauth,asampat3090/readthedocs.org,VishvajitP/readthedocs.org,atsuyim/readthedocs.org,ojii/readthedocs.org,kdkeyser/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,fujita-shintaro/readthedocs.org,cgourlay/readthedocs.org,istresearch/readthedocs.org,KamranMackey/readthedocs.org,nikolas/readthedocs.org,cgourlay/readthedocs.org,ojii/readthedocs.org,sid-kap/readthedocs.org,raven47git/readthedocs.org,rtfd/readthedocs.org,mrshoki/readthedocs.org,wanghaven/readthedocs.org,safwanrahman/readthedocs.org,sils1297/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,johncosta/private-readthedocs.org,takluyver/readthedocs.org,kenwang76/readthedocs.org,LukasBoersma/readthedocs.org,KamranMackey/readthedocs.org,techtonik/readthedocs.org,GovReady/readthedocs.org,mhils/readthedocs.org,CedarLogic/readthedocs.org,nyergler/pythonslides,soulshake/readthedocs.org,sid-kap/readthedocs.org,kdkeyser/readthedocs.org,asampat3090/readthedocs.org,laplaceliu/readthedocs.org,Tazer/readthedocs.org,kdkeyser/readthedocs.org,ojii/readthedocs.org,agjohnson/readthedocs.org,royalwang/readthedocs.org,hach-que/readthedocs.org,michaelmcandrew/readthedocs.org,CedarLogic/readthedocs.org,CedarLogic/readthedocs.org,laplaceliu/readthedocs.org,soulshake/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,takluyver/readthedocs.org,soulshake/readthedocs.org,hach-que/readthedocs.org,SteveViss/readthedocs.org,agjohnson/readthedocs.org,atsuyim/readthedocs.org,clarkperkins/readthedocs.org,clarkperkins/readthedocs.org,pombredanne/readthedocs.org,stevepiercy/readthedocs.org,titiushko/readthedocs.org,stevepiercy/readthedocs.org,nikolas/readthedocs.org,michaelmcandrew/readthedocs.org,nikolas/readthedocs.org,michaelmcandrew/readthedocs.org,SteveViss/readthedocs.org,LukasBoersma/readthedocs.org,gjtorikian/readthedocs.org,Tazer/readthedocs.org,espdev/readthedocs.org,kenwang76/readthedocs.org,wijerasa/readthedocs.org,royalwang/readthedocs.org,raven47git/readthedocs.org,mrshoki/readthedocs.org,VishvajitP/readthedocs.org,stevepiercy/readthedocs.org,espdev/readthedocs.org,pombredanne/readthedocs.org,Tazer/readthedocs.org,techtonik/readthedocs.org,tddv/readthedocs.org,istresearch/readthedocs.org,d0ugal/readthedocs.org,agjohnson/readthedocs.org,Tazer/readthedocs.org,istresearch/readthedocs.org,GovReady/readthedocs.org,nyergler/pythonslides,hach-que/readthedocs.org,stevepiercy/readthedocs.org,hach-que/readthedocs.org,kenwang76/readthedocs.org,nyergler/pythonslides,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,takluyver/readthedocs.org,GovReady/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,wijerasa/readthedocs.org,emawind84/readthedocs.org,mrshoki/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,Carreau/readthedocs.org,davidfischer/readthedocs.org,VishvajitP/readthedocs.org,espdev/readthedocs.org,royalwang/readthedocs.org,emawind84/readthedocs.org,mhils/readthedocs.org,sid-kap/readthedocs.org,sid-kap/readthedocs.org,davidfischer/readthedocs.org,tddv/readthedocs.org,LukasBoersma/readthedocs.org,istresearch/readthedocs.org,dirn/readthedocs.org,LukasBoersma/readthedocs.org,CedarLogic/readthedocs.org,kenshinthebattosai/readthedocs.org,Carreau/readthedocs.org,singingwolfboy/readthedocs.org,clarkperkins/readthedocs.org,KamranMackey/readthedocs.org,sils1297/readthedocs.org,espdev/readthedocs.org,gjtorikian/readthedocs.org,titiushko/readthedocs.org,d0ugal/readthedocs.org,kenshinthebattosai/readthedocs.org,attakei/readthedocs-oauth,dirn/readthedocs.org,jerel/readthedocs.org,mrshoki/readthedocs.org,kenwang76/readthedocs.org,sils1297/readthedocs.org,mhils/readthedocs.org,wanghaven/readthedocs.org,davidfischer/readthedocs.org,jerel/readthedocs.org,asampat3090/readthedocs.org,laplaceliu/readthedocs.org,nikolas/readthedocs.org,Carreau/readthedocs.org,johncosta/private-readthedocs.org,tddv/readthedocs.org,michaelmcandrew/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,titiushko/readthedocs.org,SteveViss/readthedocs.org | ---
+++
@@ -1,4 +1,6 @@
from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
@@ -33,3 +35,9 @@
else:
email = STANDARD_EMAIL
return (name, email)
+
+
+@receiver(post_save, sender=User)
+def create_profile(sender, **kwargs):
+ if kwargs['created'] is True:
+ UserProfile.objects.create(user_id=kwargs['instance'].id, whitelisted=False) |
bf6565d3bf3c2345a7187d07585bdbf08db06f61 | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
site_name = getattr(c.site, "analytics_name", c.site.name)
# adzerk reporting is easier when not using a space in the tag
if isinstance(c.site, DefaultSR):
site_name = FRONTPAGE_NAME
self.ad_url = g.config[url_key].format(
subreddit=quote(site_name.lower()),
origin=c.request_origin,
)
self.frame_id = "ad_main"
| from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
site_name = getattr(c.site, "analytics_name", c.site.name)
# adzerk reporting is easier when not using a space in the tag
if isinstance(c.site, DefaultSR):
site_name = FRONTPAGE_NAME
self.ad_url = g.config[url_key].format(
subreddit=quote(site_name.lower()),
origin=c.request_origin,
loggedin="loggedin" if c.user_is_loggedin else "loggedout",
)
self.frame_id = "ad_main"
| Add loggedin keyword to adzerk Ads. | Add loggedin keyword to adzerk Ads.
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk | ---
+++
@@ -22,5 +22,6 @@
self.ad_url = g.config[url_key].format(
subreddit=quote(site_name.lower()),
origin=c.request_origin,
+ loggedin="loggedin" if c.user_is_loggedin else "loggedout",
)
self.frame_id = "ad_main" |
fe22a0f9ca92ef0e76bb2f730a2b22da500db5dd | addons/website_sale_management/__manifest__.py | addons/website_sale_management/__manifest__.py | # -*- encoding: utf-8 -*-
{
'name': 'Website Sale - Sale Management',
'version': '1.0',
'category': 'Website',
'description': """
Display orders to invoice in website dashboard.
""",
'depends': [
'sale_management',
'website_sale',
],
'installable': True,
'autoinstall': True,
'data': [
],
'demo': [
],
'qweb': ['static/src/xml/*.xml'],
}
| # -*- encoding: utf-8 -*-
{
'name': 'Website Sale - Sale Management',
'version': '1.0',
'category': 'Website',
'description': """
Display orders to invoice in website dashboard.
""",
'depends': [
'sale_management',
'website_sale',
],
'installable': True,
'auto_install': True,
'data': [
],
'demo': [
],
'qweb': ['static/src/xml/*.xml'],
}
| Fix auto_install typo in manifest | [FIX] website_sale_management: Fix auto_install typo in manifest
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -11,7 +11,7 @@
'website_sale',
],
'installable': True,
- 'autoinstall': True,
+ 'auto_install': True,
'data': [
],
'demo': [ |
ad17f4a48bdee7ca57e8fe66e4658821b3c8789e | corehq/apps/userreports/migrations/0018_ucrexpression.py | corehq/apps/userreports/migrations/0018_ucrexpression.py | # Generated by Django 2.2.27 on 2022-04-12 10:28
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name='UCRExpression',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('domain', models.CharField(db_index=True, max_length=255)),
('description', models.TextField(blank=True, null=True)),
('expression_type', models.CharField(choices=[('named_expression', 'named_expression'), ('named_filter', 'named_filter')], db_index=True, default='named_expression', max_length=20)),
('definition', django.contrib.postgres.fields.jsonb.JSONField(null=True)),
],
options={
'unique_together': {('name', 'domain')},
},
),
]
| # Generated by Django 3.2.12 on 2022-04-12 15:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name='UCRExpression',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('domain', models.CharField(db_index=True, max_length=255)),
('description', models.TextField(blank=True, null=True)),
('expression_type', models.CharField(choices=[('named_expression', 'named_expression'), ('named_filter', 'named_filter')], db_index=True, default='named_expression', max_length=20)),
('definition', models.JSONField(null=True)),
],
options={
'unique_together': {('name', 'domain')},
},
),
]
| Use django 3 to make migration | Use django 3 to make migration
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,6 +1,5 @@
-# Generated by Django 2.2.27 on 2022-04-12 10:28
+# Generated by Django 3.2.12 on 2022-04-12 15:07
-import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
@@ -19,7 +18,7 @@
('domain', models.CharField(db_index=True, max_length=255)),
('description', models.TextField(blank=True, null=True)),
('expression_type', models.CharField(choices=[('named_expression', 'named_expression'), ('named_filter', 'named_filter')], db_index=True, default='named_expression', max_length=20)),
- ('definition', django.contrib.postgres.fields.jsonb.JSONField(null=True)),
+ ('definition', models.JSONField(null=True)),
],
options={
'unique_together': {('name', 'domain')}, |
7ee5692a98a6dfc714a05f1add8e72b09c52929e | students/psbriant/final_project/clean_data.py | students/psbriant/final_project/clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
# print(data["Date Text"].head())
first_date = data["Date Text"].values[0]
print(first_date)
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
| """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dates=[0], infer_datetime_format=True)
temp = pandas.DatetimeIndex(data["Date_Text"])
data["Month"] = temp.month
data["Year"] = temp.year
print(data)
# print(data["Date Text"].head())
# first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%b-%Y")
# datetime(2012, 3, 10, 0, 0)
# data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
| Add code to split month and year into new columns. | Add code to split month and year into new columns.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -12,18 +12,24 @@
from datetime import datetime
# Change source to smaller file.
-data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
+data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
+ parse_dates=[0], infer_datetime_format=True)
+temp = pandas.DatetimeIndex(data["Date_Text"])
+data["Month"] = temp.month
+data["Year"] = temp.year
+print(data)
# print(data["Date Text"].head())
-first_date = data["Date Text"].values[0]
-print(first_date)
+# first_date = data["Date Text"].values[0]
+# print(first_date)
-# datetime.strptime(first_date, "%Y-%m-%d")
+# datetime.strptime(first_date, "%b-%Y")
+
# datetime(2012, 3, 10, 0, 0)
-# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
+# data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
# data.index = data.date
# print(data) |
f334c9770dd7d9fb38fd5c118df806dbf532d17a | wsgi.py | wsgi.py | # -*- coding: utf-8 -*-
"""
wsgi
~~~~
ieee wsgi module
"""
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from myip.factory import create_app
if __name__ == "__main__":
run_simple('localhost', 5000, create_app(), use_reloader=True,
use_debugger=True, use_evalex=True)
| # -*- coding: utf-8 -*-
"""
wsgi
~~~~
ieee wsgi module
"""
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from myip.factory import create_app
application = create_app()
if __name__ == "__main__":
run_simple('localhost', 5000, application, use_reloader=True,
use_debugger=True, use_evalex=True)
| Add application variable for the procfile. | Add application variable for the procfile.
| Python | mit | brotatos/myip,brotatos/myip | ---
+++
@@ -11,7 +11,9 @@
from myip.factory import create_app
+application = create_app()
+
if __name__ == "__main__":
- run_simple('localhost', 5000, create_app(), use_reloader=True,
+ run_simple('localhost', 5000, application, use_reloader=True,
use_debugger=True, use_evalex=True) |
d52a7b19f7b5596e88d7233dfea35a70b2645385 | osmaxx-py/excerptconverter/converter_manager.py | osmaxx-py/excerptconverter/converter_manager.py | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
export_options = {}
for Converter in BaseExcerptConverter.available_converters:
export_options[Converter.__name__] = Converter.converter_configuration()
return export_options
def __init__(self, extraction_order,
available_converters=BaseExcerptConverter.available_converters,
run_as_celery_tasks=True):
""""
:param execution_configuration example:
{
'gis': {
'formats': ['txt', 'file_gdb'],
'options': {
'coordinate_reference_system': 'wgs72',
'detail_level': 'verbatim'
}
},
'routing': { ... }
}
"""
self.extraction_order = extraction_order
self.available_converters = available_converters
self.run_as_celery_tasks = run_as_celery_tasks
def execute_converters(self):
for Converter in self.available_converters:
if Converter.__name__ in self.extraction_order.extraction_configuration:
Converter.execute(
self.extraction_order,
self.extraction_order.extraction_configuration[Converter.__name__],
self.run_as_celery_tasks
)
| from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
return {Converter.__name__: Converter.converter_configuration()
for Converter in BaseExcerptConverter.available_converters}
def __init__(self, extraction_order,
available_converters=BaseExcerptConverter.available_converters,
run_as_celery_tasks=True):
""""
:param execution_configuration example:
{
'gis': {
'formats': ['txt', 'file_gdb'],
'options': {
'coordinate_reference_system': 'wgs72',
'detail_level': 'verbatim'
}
},
'routing': { ... }
}
"""
self.extraction_order = extraction_order
self.available_converters = available_converters
self.run_as_celery_tasks = run_as_celery_tasks
def execute_converters(self):
for Converter in self.available_converters:
if Converter.__name__ in self.extraction_order.extraction_configuration:
Converter.execute(
self.extraction_order,
self.extraction_order.extraction_configuration[Converter.__name__],
self.run_as_celery_tasks
)
| Replace loop by dictionary comprehension | Refactoring: Replace loop by dictionary comprehension
| Python | mit | geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend | ---
+++
@@ -4,10 +4,8 @@
class ConverterManager:
@staticmethod
def converter_configuration():
- export_options = {}
- for Converter in BaseExcerptConverter.available_converters:
- export_options[Converter.__name__] = Converter.converter_configuration()
- return export_options
+ return {Converter.__name__: Converter.converter_configuration()
+ for Converter in BaseExcerptConverter.available_converters}
def __init__(self, extraction_order,
available_converters=BaseExcerptConverter.available_converters, |
d9da661c9493c0d1b54eeda8bb416ad98ca07a33 | acapi/resources/environmentlist.py | acapi/resources/environmentlist.py | """ Acquia Cloud API server list resource. """
from .acquialist import AcquiaList
class EnvironmentList(AcquiaList):
"""Dict of Acquia Cloud API Server resources keyed by hostname."""
def set_base_uri(self, base_uri):
""" Set the base URI for server resources.
Parameters
----------
base_uri : str
The base URI to use for generating the new URI.
"""
uri = '{}/servers'.format(base_uri)
self.uri = uri
| """ Acquia Cloud API server list resource. """
from .acquialist import AcquiaList
class EnvironmentList(AcquiaList):
"""Dict of Acquia Cloud API Server resources keyed by hostname."""
def set_base_uri(self, base_uri):
""" Set the base URI for server resources.
Parameters
----------
base_uri : str
The base URI to use for generating the new URI.
"""
uri = '{}/envs'.format(base_uri)
self.uri = uri
| Use correct URI for looking up environment resources | Use correct URI for looking up environment resources
| Python | mit | skwashd/python-acquia-cloud | ---
+++
@@ -15,5 +15,5 @@
base_uri : str
The base URI to use for generating the new URI.
"""
- uri = '{}/servers'.format(base_uri)
+ uri = '{}/envs'.format(base_uri)
self.uri = uri |
f5d864c2a5c9b4d2ea1ff95e59d60adf2ebd176e | recipes/sos-bash/run_test.py | recipes/sos-bash/run_test.py | import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
@unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32')
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as kc:
execute(kc=kc, code='a = 1')
stdout, stderr = assemble_output(kc.iopub_channel)
self.assertEqual(stdout.strip(), '', f'Stdout is not empty, "{stdout}" received')
self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received')
execute(kc=kc, code='%use Bash\n%get a\necho $a')
stdout, stderr = assemble_output(kc.iopub_channel)
self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received')
self.assertEqual(stdout.strip(), '1', f'Stdout should be 1, "{stdout}" received')
if __name__ == '__main__':
unittest.main()
| import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as kc:
execute(kc=kc, code='a = 1')
stdout, stderr = assemble_output(kc.iopub_channel)
self.assertEqual(stdout.strip(), '', f'Stdout is not empty, "{stdout}" received')
self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received')
execute(kc=kc, code='%use Bash\n%get a\necho $a')
stdout, stderr = assemble_output(kc.iopub_channel)
self.assertEqual(stderr.strip(), '', f'Stderr is not empty, "{stderr}" received')
self.assertEqual(stdout.strip(), '1', f'Stdout should be 1, "{stdout}" received')
if __name__ == '__main__':
unittest.main()
| Test does not have to fail under windows | Test does not have to fail under windows
| Python | bsd-3-clause | birdsarah/staged-recipes,synapticarbors/staged-recipes,SylvainCorlay/staged-recipes,kwilcox/staged-recipes,johanneskoester/staged-recipes,synapticarbors/staged-recipes,asmeurer/staged-recipes,SylvainCorlay/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,hadim/staged-recipes,hadim/staged-recipes,ReimarBauer/staged-recipes,chrisburr/staged-recipes,conda-forge/staged-recipes,chrisburr/staged-recipes,dschreij/staged-recipes,stuertz/staged-recipes,ReimarBauer/staged-recipes,scopatz/staged-recipes,stuertz/staged-recipes,kwilcox/staged-recipes,jakirkham/staged-recipes,goanpeca/staged-recipes,jochym/staged-recipes,Juanlu001/staged-recipes,jochym/staged-recipes,ocefpaf/staged-recipes,ocefpaf/staged-recipes,Juanlu001/staged-recipes,asmeurer/staged-recipes,johanneskoester/staged-recipes,mariusvniekerk/staged-recipes,mcs07/staged-recipes,isuruf/staged-recipes,petrushy/staged-recipes,conda-forge/staged-recipes,mariusvniekerk/staged-recipes,dschreij/staged-recipes,petrushy/staged-recipes,birdsarah/staged-recipes,isuruf/staged-recipes,igortg/staged-recipes,jakirkham/staged-recipes,patricksnape/staged-recipes,igortg/staged-recipes,mcs07/staged-recipes | ---
+++
@@ -4,7 +4,6 @@
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
-@unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32')
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as kc: |
c7bc130efaaba1e079bc8a0f39f37ef3c2534413 | Yank/tests/test_utils.py | Yank/tests/test_utils.py | #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#=============================================================================================
# TESTING FUNCTIONS
#=============================================================================================
def test_yank_options():
"""Test option priorities and handling."""
cl_opt = {'option1': 1}
yaml_opt = {'option1': 2, 'option2': 'test'}
yank_opt = YankOptions(cl_opt=cl_opt, yaml_opt=yaml_opt)
assert yank_opt['option2'] == 'test'
assert yank_opt['option1'] == 1 # command line > yaml
assert len(yank_opt) == 2
# runtime > command line
yank_opt['option1'] = 0
assert yank_opt['option1'] == 0
# restore old option when deleted at runtime
del yank_opt['option1']
assert yank_opt['option1'] == 1
# modify specific priority level
yank_opt.default = {'option3': -2}
assert len(yank_opt) == 3
assert yank_opt['option3'] == -2
# test iteration interface
assert yank_opt.items() == [('option1', 1), ('option2', 'test'), ('option3', -2)]
assert yank_opt.keys() == ['option1', 'option2', 'option3']
| #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#=============================================================================================
# TESTING FUNCTIONS
#=============================================================================================
def test_yank_options():
"""Test option priorities and handling."""
cl_opt = {'option1': 1}
yaml_opt = {'option1': 2, 'option2': 'test'}
yank_opt = YankOptions(cl_opt=cl_opt, yaml_opt=yaml_opt)
assert yank_opt['option2'] == 'test'
assert yank_opt['option1'] == 1 # command line > yaml
assert len(yank_opt) == 2, "Excepted two options, found: %s" % str([x for x in yank_opt])
# runtime > command line
yank_opt['option1'] = 0
assert yank_opt['option1'] == 0
# restore old option when deleted at runtime
del yank_opt['option1']
assert yank_opt['option1'] == 1
# modify specific priority level
yank_opt.default = {'option3': -2}
assert len(yank_opt) == 3
assert yank_opt['option3'] == -2
# test iteration interface
assert yank_opt.items() == [('option1', 1), ('option2', 'test'), ('option3', -2)]
assert yank_opt.keys() == ['option1', 'option2', 'option3']
| Add more informative error message for yank options assertion test. | Add more informative error message for yank options assertion test.
| Python | mit | andrrizzi/yank,andrrizzi/yank,choderalab/yank,andrrizzi/yank,choderalab/yank | ---
+++
@@ -24,7 +24,7 @@
assert yank_opt['option2'] == 'test'
assert yank_opt['option1'] == 1 # command line > yaml
- assert len(yank_opt) == 2
+ assert len(yank_opt) == 2, "Excepted two options, found: %s" % str([x for x in yank_opt])
# runtime > command line
yank_opt['option1'] = 0 |
81dc92b3c2875b6775d33321b1bcd9f994be8a10 | txircd/modules/extra/snotice_remoteconnect.py | txircd/modules/extra/snotice_remoteconnect.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
return [ ("remoteregister", 1, self.sendRemoteConnectNotice),
("servernoticetype", 1, self.checkSnoType),
("startburstcommand", 1, self.markStartBurst),
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
server = self.ircd.servers[user.uuid[:3]].name
if server == self.burstingServer:
return
message = "Client connected on {}: {} ({}) [{}]".format(server, user.hostmaskWithRealHost(), user.ip, user.gecos)
snodata = {
"mask": "connect",
"message": message
}
self.ircd.runActionProcessing("sendservernotice", snodata)
def checkSnoType(self, user, typename):
return typename == "remoteconnect"
def markStartBurst(self, server, command):
self.burstingServer = server
def markEndBurst(self, server, command):
self.burstingServer = None
snoRemoteConnect = SnoRemoteConnect() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
return [ ("remoteregister", 1, self.sendRemoteConnectNotice),
("servernoticetype", 1, self.checkSnoType),
("startburstcommand", 1, self.markStartBurst),
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
server = self.ircd.servers[user.uuid[:3]]
if server == self.burstingServer:
return
server = server.name
message = "Client connected on {}: {} ({}) [{}]".format(server, user.hostmaskWithRealHost(), user.ip, user.gecos)
snodata = {
"mask": "connect",
"message": message
}
self.ircd.runActionProcessing("sendservernotice", snodata)
def checkSnoType(self, user, typename):
return typename == "remoteconnect"
def markStartBurst(self, server, command):
self.burstingServer = server
def markEndBurst(self, server, command):
self.burstingServer = None
snoRemoteConnect = SnoRemoteConnect() | Fix checking a name against an object | Fix checking a name against an object
| Python | bsd-3-clause | Heufneutje/txircd | ---
+++
@@ -17,9 +17,10 @@
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
- server = self.ircd.servers[user.uuid[:3]].name
+ server = self.ircd.servers[user.uuid[:3]]
if server == self.burstingServer:
return
+ server = server.name
message = "Client connected on {}: {} ({}) [{}]".format(server, user.hostmaskWithRealHost(), user.ip, user.gecos)
snodata = {
"mask": "connect", |
8ecf97b338dd37eaf5a4e2672e33e27cc40d215d | sacred/observers/__init__.py | sacred/observers/__init__.py | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observers.tinydb_hashfs import TinyDbObserver
if opt.has_pymongo:
from sacred.observers.mongo import MongoObserver
else:
MongoObserver = opt.MissingDependencyMock('pymongo')
class MongoDbOption(CommandLineOption):
"""To use the MongoObserver you need to install pymongo first."""
arg = 'DB'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -m/--mongo_db flag: '
'missing pymongo dependency')
if opt.has_sqlalchemy:
from sacred.observers.sql import SqlObserver
else:
SqlObserver = opt.MissingDependencyMock('sqlalchemy')
class SqlOption(CommandLineOption):
"""To use the SqlObserver you need to install sqlalchemy first."""
arg = 'DB_URL'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -s/--sql flag: '
'missing sqlalchemy dependency')
__all__ = ('FileStorageObserver', 'RunObserver', 'MongoObserver',
'SqlObserver', 'TinyDbObserver')
| #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observers.tinydb_hashfs import TinyDbObserver, TinyDbReader
if opt.has_pymongo:
from sacred.observers.mongo import MongoObserver
else:
MongoObserver = opt.MissingDependencyMock('pymongo')
class MongoDbOption(CommandLineOption):
"""To use the MongoObserver you need to install pymongo first."""
arg = 'DB'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -m/--mongo_db flag: '
'missing pymongo dependency')
if opt.has_sqlalchemy:
from sacred.observers.sql import SqlObserver
else:
SqlObserver = opt.MissingDependencyMock('sqlalchemy')
class SqlOption(CommandLineOption):
"""To use the SqlObserver you need to install sqlalchemy first."""
arg = 'DB_URL'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -s/--sql flag: '
'missing sqlalchemy dependency')
__all__ = ('FileStorageObserver', 'RunObserver', 'MongoObserver',
'SqlObserver', 'TinyDbObserver', 'TinyDbReader')
| Add TinyDbReader to observers init | Add TinyDbReader to observers init
| Python | mit | IDSIA/sacred,IDSIA/sacred | ---
+++
@@ -7,7 +7,7 @@
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
-from sacred.observers.tinydb_hashfs import TinyDbObserver
+from sacred.observers.tinydb_hashfs import TinyDbObserver, TinyDbReader
if opt.has_pymongo:
from sacred.observers.mongo import MongoObserver
@@ -41,4 +41,4 @@
__all__ = ('FileStorageObserver', 'RunObserver', 'MongoObserver',
- 'SqlObserver', 'TinyDbObserver')
+ 'SqlObserver', 'TinyDbObserver', 'TinyDbReader') |
04fec1c50ac81c1b80c22f37bd43845a0e08c1a3 | fancypages/assets/models.py | fancypages/assets/models.py | from django.db import models
from django.utils.translation import ugettext as _
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey('auth.User', verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| from django.db import models
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey(User, verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| Add support for custom user model (Django 1.5+) | Add support for custom user model (Django 1.5+)
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages | ---
+++
@@ -1,5 +1,11 @@
from django.db import models
from django.utils.translation import ugettext as _
+
+try:
+ from django.contrib.auth import get_user_model
+ User = get_user_model()
+except ImportError:
+ from django.contrib.auth.models import User
class AbstractAsset(models.Model):
@@ -9,7 +15,7 @@
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
- creator = models.ForeignKey('auth.User', verbose_name=_("Creator"))
+ creator = models.ForeignKey(User, verbose_name=_("Creator"))
def __unicode__(self):
return self.name |
7629afde2627457b4f4b19e1542a87e695c1837d | tests/events/test_models.py | tests/events/test_models.py | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.create(title='five')
# THEN it's there
assert Event.objects.count() == 1
def test_event_has_all_the_attributes(): # noqa: D103
# GIVEN an event
e = EventFactory.build()
# THEN it has …
assert e.title
assert e.date
assert e.venue
assert e.description
assert e.fb_event_url
def test_event_has_slug(db): # noqa: D103
# GIVEN an event
e = EventFactory.build(
title='One Happy Family',
date=datetime.date(2018, 1, 1),
venue=None,
)
assert e.slug == ''
# WHEN saving the event
e.save()
# THEN it gets a slug generated from its date and title
assert e.slug == '2018-01-01-one-happy-family'
| """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.create(title='five')
# THEN it's there
assert Event.objects.count() == 1
def test_event_has_all_the_attributes(): # noqa: D103
# GIVEN an event
e = EventFactory.build()
# THEN it has …
assert e.title
assert e.date
assert e.venue
assert e.description
assert e.fb_event_url
def test_event_has_slug(db): # noqa: D103
# GIVEN an event
e = EventFactory.build(
title='One Happy Family',
date=datetime.date(2018, 1, 1),
venue=None,
)
assert e.slug == ''
# WHEN saving the event
e.save()
# THEN it gets a slug generated from its date and title
assert e.slug == '2018-01-01-one-happy-family'
def test_event_slug_gets_updated_on_date_change(db): # noqa: D103
# GIVEN an event
e = EventFactory.create(
date=datetime.date(2018, 1, 1),
venue=None,
)
# WHEN changing the date
assert e.slug.startswith('2018-01-01')
e.date = datetime.date(2018, 1, 2)
e.save()
# THEN the slug changes to reflect the new date
assert e.slug.startswith('2018-01-02')
| Make sure slug gets updated on date change | Make sure slug gets updated on date change
| Python | mit | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx | ---
+++
@@ -42,3 +42,19 @@
# THEN it gets a slug generated from its date and title
assert e.slug == '2018-01-01-one-happy-family'
+
+
+def test_event_slug_gets_updated_on_date_change(db): # noqa: D103
+ # GIVEN an event
+ e = EventFactory.create(
+ date=datetime.date(2018, 1, 1),
+ venue=None,
+ )
+
+ # WHEN changing the date
+ assert e.slug.startswith('2018-01-01')
+ e.date = datetime.date(2018, 1, 2)
+ e.save()
+
+ # THEN the slug changes to reflect the new date
+ assert e.slug.startswith('2018-01-02') |
8209b77a16c899436418dbc85dc891f671949bfc | bot/logger/message_sender/asynchronous.py | bot/logger/message_sender/asynchronous.py | from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sender)
self.worker = worker
def send(self, text):
self.worker.post(Work(lambda: self.sender.send(text), "async_message_send"))
| from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sender)
self.worker = worker
def send(self, text):
self.worker.post(Work(lambda: self.sender.send(text), "asynchronous_message_sender:send"))
| Clarify work action in AsynchronousMessageSender | Clarify work action in AsynchronousMessageSender
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -9,4 +9,4 @@
self.worker = worker
def send(self, text):
- self.worker.post(Work(lambda: self.sender.send(text), "async_message_send"))
+ self.worker.post(Work(lambda: self.sender.send(text), "asynchronous_message_sender:send")) |
ccf3c508bd6750073ea3bbaefff567b92880df73 | rest_framework/authtoken/serializers.py | rest_framework/authtoken/serializers.py | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError()
attrs['user'] = user
return attrs
else:
msg = _('Unable to login with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "username" and "password"')
raise serializers.ValidationError(msg)
| from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs
else:
msg = _('Unable to login with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "username" and "password"')
raise serializers.ValidationError(msg)
| Fix missing message in ValidationError | Fix missing message in ValidationError | Python | bsd-2-clause | jtiai/django-rest-framework,sbellem/django-rest-framework,kylefox/django-rest-framework,jerryhebert/django-rest-framework,zeldalink0515/django-rest-framework,adambain-vokal/django-rest-framework,tcroiset/django-rest-framework,alacritythief/django-rest-framework,johnraz/django-rest-framework,rhblind/django-rest-framework,kezabelle/django-rest-framework,cyberj/django-rest-framework,bluedazzle/django-rest-framework,andriy-s/django-rest-framework,alacritythief/django-rest-framework,antonyc/django-rest-framework,wedaly/django-rest-framework,paolopaolopaolo/django-rest-framework,paolopaolopaolo/django-rest-framework,wedaly/django-rest-framework,AlexandreProenca/django-rest-framework,werthen/django-rest-framework,rafaelang/django-rest-framework,tomchristie/django-rest-framework,tomchristie/django-rest-framework,rubendura/django-rest-framework,kgeorgy/django-rest-framework,uploadcare/django-rest-framework,waytai/django-rest-framework,antonyc/django-rest-framework,ajaali/django-rest-framework,jpadilla/django-rest-framework,uruz/django-rest-framework,potpath/django-rest-framework,d0ugal/django-rest-framework,brandoncazander/django-rest-framework,wangpanjun/django-rest-framework,maryokhin/django-rest-framework,elim/django-rest-framework,wedaly/django-rest-framework,hnakamur/django-rest-framework,davesque/django-rest-framework,kennydude/django-rest-framework,ajaali/django-rest-framework,HireAnEsquire/django-rest-framework,kezabelle/django-rest-framework,fishky/django-rest-framework,arpheno/django-rest-framework,James1345/django-rest-framework,rubendura/django-rest-framework,iheitlager/django-rest-framework,damycra/django-rest-framework,YBJAY00000/django-rest-framework,pombredanne/django-rest-framework,HireAnEsquire/django-rest-framework,HireAnEsquire/django-rest-framework,waytai/django-rest-framework,ticosax/django-rest-framework,davesque/django-rest-framework,hnakamur/django-rest-framework,MJafarMashhadi/django-rest-framework,damycra/django-rest-framework,justanr/django-rest-framework,ashishfinoit/django-rest-framework,qsorix/django-rest-framework,johnraz/django-rest-framework,fishky/django-rest-framework,gregmuellegger/django-rest-framework,cheif/django-rest-framework,xiaotangyuan/django-rest-framework,maryokhin/django-rest-framework,douwevandermeij/django-rest-framework,canassa/django-rest-framework,sehmaschine/django-rest-framework,tcroiset/django-rest-framework,ticosax/django-rest-framework,justanr/django-rest-framework,mgaitan/django-rest-framework,buptlsl/django-rest-framework,wzbozon/django-rest-framework,thedrow/django-rest-framework-1,cyberj/django-rest-framework,adambain-vokal/django-rest-framework,edx/django-rest-framework,vstoykov/django-rest-framework,zeldalink0515/django-rest-framework,kezabelle/django-rest-framework,xiaotangyuan/django-rest-framework,ambivalentno/django-rest-framework,andriy-s/django-rest-framework,nhorelik/django-rest-framework,hunter007/django-rest-framework,delinhabit/django-rest-framework,wzbozon/django-rest-framework,sbellem/django-rest-framework,jtiai/django-rest-framework,kgeorgy/django-rest-framework,thedrow/django-rest-framework-1,abdulhaq-e/django-rest-framework,krinart/django-rest-framework,maryokhin/django-rest-framework,jtiai/django-rest-framework,adambain-vokal/django-rest-framework,rafaelcaricio/django-rest-framework,iheitlager/django-rest-framework,ambivalentno/django-rest-framework,VishvajitP/django-rest-framework,ebsaral/django-rest-framework,sheppard/django-rest-framework,sheppard/django-rest-framework,abdulhaq-e/django-rest-framework,tigeraniya/django-rest-framework,lubomir/django-rest-framework,hnakamur/django-rest-framework,brandoncazander/django-rest-framework,ebsaral/django-rest-framework,delinhabit/django-rest-framework,mgaitan/django-rest-framework,aericson/django-rest-framework,elim/django-rest-framework,potpath/django-rest-framework,jness/django-rest-framework,kgeorgy/django-rest-framework,ashishfinoit/django-rest-framework,callorico/django-rest-framework,rafaelang/django-rest-framework,wangpanjun/django-rest-framework,jpadilla/django-rest-framework,James1345/django-rest-framework,antonyc/django-rest-framework,ajaali/django-rest-framework,aericson/django-rest-framework,nryoung/django-rest-framework,alacritythief/django-rest-framework,kennydude/django-rest-framework,dmwyatt/django-rest-framework,delinhabit/django-rest-framework,uploadcare/django-rest-framework,linovia/django-rest-framework,uruz/django-rest-framework,tomchristie/django-rest-framework,ezheidtmann/django-rest-framework,rafaelang/django-rest-framework,akalipetis/django-rest-framework,sheppard/django-rest-framework,raphaelmerx/django-rest-framework,leeahoward/django-rest-framework,potpath/django-rest-framework,pombredanne/django-rest-framework,nryoung/django-rest-framework,jpulec/django-rest-framework,tigeraniya/django-rest-framework,dmwyatt/django-rest-framework,d0ugal/django-rest-framework,cheif/django-rest-framework,jness/django-rest-framework,ossanna16/django-rest-framework,MJafarMashhadi/django-rest-framework,callorico/django-rest-framework,rafaelcaricio/django-rest-framework,aericson/django-rest-framework,cyberj/django-rest-framework,simudream/django-rest-framework,rhblind/django-rest-framework,wangpanjun/django-rest-framework,tcroiset/django-rest-framework,yiyocx/django-rest-framework,raphaelmerx/django-rest-framework,andriy-s/django-rest-framework,wwj718/django-rest-framework,damycra/django-rest-framework,tigeraniya/django-rest-framework,canassa/django-rest-framework,canassa/django-rest-framework,werthen/django-rest-framework,kylefox/django-rest-framework,linovia/django-rest-framework,agconti/django-rest-framework,nhorelik/django-rest-framework,vstoykov/django-rest-framework,sehmaschine/django-rest-framework,sehmaschine/django-rest-framework,MJafarMashhadi/django-rest-framework,werthen/django-rest-framework,buptlsl/django-rest-framework,krinart/django-rest-framework,zeldalink0515/django-rest-framework,AlexandreProenca/django-rest-framework,davesque/django-rest-framework,VishvajitP/django-rest-framework,ticosax/django-rest-framework,brandoncazander/django-rest-framework,akalipetis/django-rest-framework,leeahoward/django-rest-framework,kylefox/django-rest-framework,nhorelik/django-rest-framework,linovia/django-rest-framework,wzbozon/django-rest-framework,agconti/django-rest-framework,krinart/django-rest-framework,qsorix/django-rest-framework,leeahoward/django-rest-framework,rubendura/django-rest-framework,abdulhaq-e/django-rest-framework,jness/django-rest-framework,YBJAY00000/django-rest-framework,gregmuellegger/django-rest-framework,iheitlager/django-rest-framework,pombredanne/django-rest-framework,ossanna16/django-rest-framework,jerryhebert/django-rest-framework,paolopaolopaolo/django-rest-framework,AlexandreProenca/django-rest-framework,rafaelcaricio/django-rest-framework,raphaelmerx/django-rest-framework,uruz/django-rest-framework,agconti/django-rest-framework,buptlsl/django-rest-framework,cheif/django-rest-framework,bluedazzle/django-rest-framework,jerryhebert/django-rest-framework,edx/django-rest-framework,douwevandermeij/django-rest-framework,simudream/django-rest-framework,atombrella/django-rest-framework,jpulec/django-rest-framework,wwj718/django-rest-framework,douwevandermeij/django-rest-framework,thedrow/django-rest-framework-1,simudream/django-rest-framework,bluedazzle/django-rest-framework,nryoung/django-rest-framework,qsorix/django-rest-framework,ossanna16/django-rest-framework,johnraz/django-rest-framework,sbellem/django-rest-framework,waytai/django-rest-framework,gregmuellegger/django-rest-framework,d0ugal/django-rest-framework,arpheno/django-rest-framework,akalipetis/django-rest-framework,rhblind/django-rest-framework,lubomir/django-rest-framework,justanr/django-rest-framework,atombrella/django-rest-framework,edx/django-rest-framework,ashishfinoit/django-rest-framework,xiaotangyuan/django-rest-framework,arpheno/django-rest-framework,yiyocx/django-rest-framework,mgaitan/django-rest-framework,hunter007/django-rest-framework,uploadcare/django-rest-framework,lubomir/django-rest-framework,hunter007/django-rest-framework,vstoykov/django-rest-framework,James1345/django-rest-framework,ezheidtmann/django-rest-framework,atombrella/django-rest-framework,kennydude/django-rest-framework,ambivalentno/django-rest-framework,fishky/django-rest-framework,jpadilla/django-rest-framework,VishvajitP/django-rest-framework,hnarayanan/django-rest-framework,ebsaral/django-rest-framework,yiyocx/django-rest-framework,hnarayanan/django-rest-framework,hnarayanan/django-rest-framework,wwj718/django-rest-framework,dmwyatt/django-rest-framework,YBJAY00000/django-rest-framework,elim/django-rest-framework,jpulec/django-rest-framework,ezheidtmann/django-rest-framework,callorico/django-rest-framework | ---
+++
@@ -18,7 +18,7 @@
if user:
if not user.is_active:
msg = _('User account is disabled.')
- raise serializers.ValidationError()
+ raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs
else: |
ac1a2191b7923a21b621c5e2ea6465e79a36e579 | doc2dash/__init__.py | doc2dash/__init__.py | """
Convert docs to Dash.app's docset format.
"""
from __future__ import absolute_import, division, print_function
__author__ = 'Hynek Schlawack'
__version__ = '2.0.0'
__license__ = 'MIT'
| """
Convert docs to Dash.app's docset format.
"""
from __future__ import absolute_import, division, print_function
__author__ = 'Hynek Schlawack'
__version__ = '2.0.0-dev'
__license__ = 'MIT'
| Use -dev tag for in-dev versions | Use -dev tag for in-dev versions
| Python | mit | hynek/doc2dash,hynek/doc2dash | ---
+++
@@ -6,5 +6,5 @@
__author__ = 'Hynek Schlawack'
-__version__ = '2.0.0'
+__version__ = '2.0.0-dev'
__license__ = 'MIT' |
5f6fb5866ca74793b05308ac27c4698033068cfe | tvtk/tests/test_garbage_collection.py | tvtk/tests/test_garbage_collection.py | """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from tvtk.tests.common import TestGarbageCollection
class TestTVTKGarbageCollection(TestGarbageCollection):
""" See: tvtk.tests.common.TestGarbageCollection
"""
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene(self):
""" Tests if Scene can be garbage collected."""
def obj_fn():
return Scene()
def close_fn(o):
o.closed = True
self.check_object_garbage_collected(obj_fn, close_fn)
def test_scene_model(self):
""" Tests if SceneModel can be garbage collected."""
def create_fn():
return SceneModel()
def close_fn(obj):
obj.closed = True
self.check_object_garbage_collected(create_fn, close_fn)
| """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.tvtk_scene import TVTKScene
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from tvtk.tests.common import TestGarbageCollection
class TestTVTKGarbageCollection(TestGarbageCollection):
""" See: tvtk.tests.common.TestGarbageCollection
"""
def test_tvtk_scene(self):
""" Tests if TVTK scene can be garbage collected."""
def create_fn():
return TVTKScene()
def close_fn(o):
o.closed = True
self.check_object_garbage_collected(create_fn, close_fn)
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene(self):
""" Tests if Scene can be garbage collected."""
def create_fn():
return Scene()
def close_fn(o):
o.closed = True
self.check_object_garbage_collected(create_fn, close_fn)
def test_scene_model(self):
""" Tests if SceneModel can be garbage collected."""
def create_fn():
return SceneModel()
def close_fn(obj):
obj.closed = True
self.check_object_garbage_collected(create_fn, close_fn)
| Test TVTKScene garbage collection and renaming | Test TVTKScene garbage collection and renaming
| Python | bsd-3-clause | alexandreleroux/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi,dmsurti/mayavi,dmsurti/mayavi | ---
+++
@@ -7,6 +7,7 @@
import unittest
from traits.etsconfig.api import ETSConfig
+from tvtk.pyface.tvtk_scene import TVTKScene
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from tvtk.tests.common import TestGarbageCollection
@@ -14,18 +15,27 @@
class TestTVTKGarbageCollection(TestGarbageCollection):
""" See: tvtk.tests.common.TestGarbageCollection
"""
+ def test_tvtk_scene(self):
+ """ Tests if TVTK scene can be garbage collected."""
+ def create_fn():
+ return TVTKScene()
+
+ def close_fn(o):
+ o.closed = True
+
+ self.check_object_garbage_collected(create_fn, close_fn)
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene(self):
""" Tests if Scene can be garbage collected."""
- def obj_fn():
+ def create_fn():
return Scene()
def close_fn(o):
o.closed = True
- self.check_object_garbage_collected(obj_fn, close_fn)
+ self.check_object_garbage_collected(create_fn, close_fn)
def test_scene_model(self):
""" Tests if SceneModel can be garbage collected.""" |
6af828b3f541adf0c42e73d76d7998bc21a072cb | sample_proj/polls/filters.py | sample_proj/polls/filters.py | from datafilters.filterform import FilterForm
from datafilters.specs import (GenericSpec, DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = GenericSpec('choice__votes')
has_choice_with_votes = GreaterThanZeroFilterSpec('choice__votes')
pub_date = DateFieldFilterSpec('pub_date', label='Date of publishing')
has_major_choice = GreaterThanFilterSpec('choice__votes', value=50)
question_contains = ContainsFilterSpec('question')
choice_contains = ContainsFilterSpec('choice__choice_text')
| from datafilters.filterform import FilterForm
from datafilters.filterspec import FilterSpec
from datafilters.specs import (DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = FilterSpec('choice__votes')
has_choice_with_votes = GreaterThanZeroFilterSpec('choice__votes')
pub_date = DateFieldFilterSpec('pub_date', label='Date of publishing')
has_major_choice = GreaterThanFilterSpec('choice__votes', value=50)
question_contains = ContainsFilterSpec('question')
choice_contains = ContainsFilterSpec('choice__choice_text')
| Use FilterSpec instead of GenericSpec in sample_proj | Use FilterSpec instead of GenericSpec in sample_proj
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters | ---
+++
@@ -1,11 +1,12 @@
from datafilters.filterform import FilterForm
-from datafilters.specs import (GenericSpec, DateFieldFilterSpec,
+from datafilters.filterspec import FilterSpec
+from datafilters.specs import (DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
- has_exact_votes = GenericSpec('choice__votes')
+ has_exact_votes = FilterSpec('choice__votes')
has_choice_with_votes = GreaterThanZeroFilterSpec('choice__votes')
pub_date = DateFieldFilterSpec('pub_date', label='Date of publishing')
has_major_choice = GreaterThanFilterSpec('choice__votes', value=50) |
d611eb18b234c7d85371d38d8c875aaae447c231 | testing/urls.py | testing/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.views.generic import View
urlpatterns = patterns('',
url(r'foo$', View.as_view(), name="foo"),
)
| # -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import View
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
| Fix tests remove unneccessary imports | Fix tests remove unneccessary imports
| Python | bsd-3-clause | niwinz/django-sites,niwinz/django-sites | ---
+++
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
-from django.conf.urls import patterns, include, url
+from django.conf.urls import url
from django.views.generic import View
-urlpatterns = patterns('',
+urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
-)
+] |
69ce0c86e2eb5be9b4977cc6033c5aa330c88122 | tfx/utils/dsl_utils_test.py | tfx/utils/dsl_utils_test.py | # Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tfx.utils.dsl_utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Standard Imports
import tensorflow as tf
from tfx.utils import dsl_utils
class DslUtilsTest(tf.test.TestCase):
def csv_input(self):
[csv] = dsl_utils.csv_input(uri='path')
self.assertEqual('ExternalPath', csv.type_name)
self.assertEqual('path', csv.uri)
if __name__ == '__main__':
tf.test.main()
| # Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tfx.utils.dsl_utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Standard Imports
import tensorflow as tf
from tfx.utils import dsl_utils
class DslUtilsTest(tf.test.TestCase):
def testCsvInput(self):
[csv] = dsl_utils.csv_input(uri='path')
self.assertEqual('ExternalPath', csv.type_name)
self.assertEqual('path', csv.uri)
if __name__ == '__main__':
tf.test.main()
| Change a test name to CamelCase instead of snake, to conform with TFX convention. | Change a test name to CamelCase instead of snake, to conform with TFX convention.
PiperOrigin-RevId: 246340014
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -25,7 +25,7 @@
class DslUtilsTest(tf.test.TestCase):
- def csv_input(self):
+ def testCsvInput(self):
[csv] = dsl_utils.csv_input(uri='path')
self.assertEqual('ExternalPath', csv.type_name)
self.assertEqual('path', csv.uri) |
72dd3f7245f07f7c596da707dffbb67ae6aa7cd0 | tohu/custom_generator_v2.py | tohu/custom_generator_v2.py | import logging
logger = logging.getLogger('tohu')
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
logger.debug('[DDD] CustomGeneratorMetaV2.__new__')
logger.debug(f' - metacls={metacls}')
logger.debug(f' - cg_name={cg_name}')
logger.debug(f' - bases={bases}')
logger.debug(f' - clsdict={clsdict}')
new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict)
logger.debug(f' -- new_obj={new_obj}')
def reset(self, seed=None):
logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})')
logger.debug(f' TODO: reset internal seed generator and call reset() on each child generator')
new_obj.reset = reset
return new_obj | import logging
logger = logging.getLogger('tohu')
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
logger.debug('[DDD]')
logger.debug('CustomGeneratorMetaV2.__new__')
logger.debug(f' - metacls={metacls}')
logger.debug(f' - cg_name={cg_name}')
logger.debug(f' - bases={bases}')
logger.debug(f' - clsdict={clsdict}')
#
# Create new custom generator object
#
new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict)
logger.debug(f' - new_obj={new_obj}')
#
# Create and assign automatically generated reset() method
#
def reset(self, seed=None):
logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})')
logger.debug(f' TODO: reset internal seed generator and call reset() on each child generator')
new_obj.reset = reset
return new_obj | Tweak debugging messages, add comments | Tweak debugging messages, add comments
| Python | mit | maxalbert/tohu | ---
+++
@@ -6,14 +6,22 @@
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
- logger.debug('[DDD] CustomGeneratorMetaV2.__new__')
- logger.debug(f' - metacls={metacls}')
- logger.debug(f' - cg_name={cg_name}')
- logger.debug(f' - bases={bases}')
- logger.debug(f' - clsdict={clsdict}')
+ logger.debug('[DDD]')
+ logger.debug('CustomGeneratorMetaV2.__new__')
+ logger.debug(f' - metacls={metacls}')
+ logger.debug(f' - cg_name={cg_name}')
+ logger.debug(f' - bases={bases}')
+ logger.debug(f' - clsdict={clsdict}')
+ #
+ # Create new custom generator object
+ #
new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict)
- logger.debug(f' -- new_obj={new_obj}')
+ logger.debug(f' - new_obj={new_obj}')
+
+ #
+ # Create and assign automatically generated reset() method
+ #
def reset(self, seed=None):
logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})') |
af2b561cd1a25fc4abd7c7948e5ff8ceb507a497 | tests/cli/test_rasa_shell.py | tests/cli/test_rasa_shell.py | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
| from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
[-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
| Adjust rasa shell help test to changes. | Adjust rasa shell help test to changes.
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | ---
+++
@@ -5,9 +5,10 @@
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
- help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
- [--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
- [--cors [CORS [CORS ...]]] [--enable-api]
+ help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
+ [--conversation-id CONVERSATION_ID] [-m MODEL]
+ [--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
+ [-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE] |
43ca4bf6a9c30055385519bb4c4472a530cce4dd | site_scons/site_tools/build_and_compress.py | site_scons/site_tools/build_and_compress.py | def build_and_compress(env, source, target):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
def exists(env):
return True
| def build_and_compress(env, target, source):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
def exists(env):
return True
| Fix argument order in BuildAndCompress pseudo-builder | Fix argument order in BuildAndCompress pseudo-builder
| Python | mit | robobrobro/terminus | ---
+++
@@ -1,4 +1,4 @@
-def build_and_compress(env, source, target):
+def build_and_compress(env, target, source):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact( |
fb7c10fd96747285e13f89a5415da8e09c8beae6 | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
],
keywords='notifications',
packages=find_packages(),
)
| from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
],
keywords='notifications',
packages=find_packages(),
)
| Update Development Status from Planning to Alpha | Update Development Status from Planning to Alpha
| Python | bsd-2-clause | incuna/incuna-pigeon | ---
+++
@@ -12,7 +12,7 @@
author_email='admin@incuna.com',
license='BSD',
classifiers=[
- 'Development Status :: 1 - Planning',
+ 'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD License', |
cc7da0c83a27e42619f0d800b11ef7bf7f82e4bb | setup.py | setup.py | from distutils.core import setup
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = '0.3.0',
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/bb4242/sdnotify',
download_url = 'https://github.com/bb4242/sdnotify/tarball/v0.3.0',
keywords = ['systemd'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description = """\
systemd Service Notification
This is a pure Python implementation of the systemd sd_notify protocol. This protocol can be used to inform systemd about service start-up completion, watchdog events, and other service status changes. Thus, this package can be used to write system services in Python that play nicely with systemd. sdnotify is compatible with both Python 2 and Python 3.
"""
)
| from distutils.core import setup
VERSION='0.3.1'
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/bb4242/sdnotify',
download_url = 'https://github.com/bb4242/sdnotify/tarball/v{}'.format(VERSION),
keywords = ['systemd'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Topic :: Software Development :: Libraries :: Python Modules",
],
data_files = [("", ["LICENSE.txt"])],
long_description = """\
systemd Service Notification
This is a pure Python implementation of the systemd sd_notify protocol. This protocol can be used to inform systemd about service start-up completion, watchdog events, and other service status changes. Thus, this package can be used to write system services in Python that play nicely with systemd. sdnotify is compatible with both Python 2 and Python 3.
"""
)
| Include LICENSE.txt in the package tarball | Include LICENSE.txt in the package tarball
| Python | mit | bb4242/sdnotify | ---
+++
@@ -1,13 +1,16 @@
from distutils.core import setup
+
+VERSION='0.3.1'
+
setup(
name = 'sdnotify',
packages = ['sdnotify'],
- version = '0.3.0',
+ version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/bb4242/sdnotify',
- download_url = 'https://github.com/bb4242/sdnotify/tarball/v0.3.0',
+ download_url = 'https://github.com/bb4242/sdnotify/tarball/v{}'.format(VERSION),
keywords = ['systemd'],
classifiers = [
"Programming Language :: Python",
@@ -18,6 +21,7 @@
"Operating System :: POSIX :: Linux",
"Topic :: Software Development :: Libraries :: Python Modules",
],
+ data_files = [("", ["LICENSE.txt"])],
long_description = """\
systemd Service Notification
|
9c9a461cf85d123a249460aa306d8300c515ac81 | setup.py | setup.py | from setuptools import setup
setup(name='tfr',
version='0.1',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=False,
install_requires=[
'numpy',
'scikit-learn',
'scipy',
'soundfile',
],
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Multimedia :: Sound/Audio :: Analysis',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
])
| from setuptools import setup
setup(name='tfr',
version='0.1',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=False,
install_requires=[
'numpy',
'scikit-learn',
'scipy',
'soundfile',
],
setup_requires=['setuptools-markdown'],
long_description_markdown_filename='README.md',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Multimedia :: Sound/Audio :: Analysis',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
])
| Add the markdown readme to the pip package. | Add the markdown readme to the pip package.
| Python | mit | bzamecnik/tfr,bzamecnik/tfr | ---
+++
@@ -15,6 +15,8 @@
'scipy',
'soundfile',
],
+ setup_requires=['setuptools-markdown'],
+ long_description_markdown_filename='README.md',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are |
935c1bfa6fedea6ee3f1d4329c3632fecb7a4bdc | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
# Optional
'django-paging>=0.2.2',
'django-indexer==0.2',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
) | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
'django-paging>=0.2.2',
'django-indexer==0.2',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
) | Remove all info pertaining to pygooglechart | Remove all info pertaining to pygooglechart
| Python | bsd-3-clause | primepix/django-sentry,kevinlondon/sentry,JTCunning/sentry,Goldmund-Wyldebeast-Wunderliebe/raven-python,imankulov/sentry,zenefits/sentry,arthurlogilab/raven-python,johansteffner/raven-python,Kryz/sentry,smarkets/raven-python,ewdurbin/raven-python,kevinastone/sentry,songyi199111/sentry,rdio/sentry,mvaled/sentry,beniwohli/apm-agent-python,dirtycoder/opbeat_python,SilentCircle/sentry,icereval/raven-python,wong2/sentry,arthurlogilab/raven-python,jbarbuto/raven-python,SilentCircle/sentry,JTCunning/sentry,fuziontech/sentry,jbarbuto/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,percipient/raven-python,ticosax/opbeat_python,mitsuhiko/raven,patrys/opbeat_python,jean/sentry,WoLpH/django-sentry,wujuguang/sentry,alex/sentry,looker/sentry,arthurlogilab/raven-python,jokey2k/sentry,ifduyue/sentry,1tush/sentry,icereval/raven-python,jmagnusson/raven-python,BayanGroup/sentry,beeftornado/sentry,arthurlogilab/raven-python,pauloschilling/sentry,alex/sentry,tbarbugli/sentry_fork,akalipetis/raven-python,TedaLIEz/sentry,chayapan/django-sentry,Goldmund-Wyldebeast-Wunderliebe/raven-python,percipient/raven-python,danriti/raven-python,SilentCircle/sentry,mvaled/sentry,dbravender/raven-python,gg7/sentry,JamesMura/sentry,gg7/sentry,mvaled/sentry,gencer/sentry,drcapulet/sentry,ronaldevers/raven-python,ifduyue/sentry,ngonzalvez/sentry,jean/sentry,SilentCircle/sentry,akheron/raven-python,ronaldevers/raven-python,wujuguang/sentry,nicholasserra/sentry,dbravender/raven-python,johansteffner/raven-python,mitsuhiko/sentry,1tush/sentry,Goldmund-Wyldebeast-Wunderliebe/raven-python,NickPresta/sentry,jean/sentry,smarkets/raven-python,pauloschilling/sentry,rdio/sentry,BuildingLink/sentry,tbarbugli/sentry_fork,fuziontech/sentry,tbarbugli/sentry_fork,getsentry/raven-python,Photonomie/raven-python,beni55/sentry,TedaLIEz/sentry,Photonomie/raven-python,argonemyth/sentry,songyi199111/sentry,fotinakis/sentry,boneyao/sentry,nikolas/raven-python,jmagnusson/raven-python,fotinakis/sentry,jmagnusson/raven-python,someonehan/raven-python,BuildingLink/sentry,felixbuenemann/sentry,Natim/sentry,nikolas/raven-python,jean/sentry,Photonomie/raven-python,imankulov/sentry,alexm92/sentry,hzy/raven-python,akheron/raven-python,hongliang5623/sentry,tarkatronic/opbeat_python,JamesMura/sentry,recht/raven-python,Kronuz/django-sentry,smarkets/raven-python,beeftornado/sentry,gg7/sentry,drcapulet/sentry,gencer/sentry,akalipetis/raven-python,primepix/django-sentry,recht/raven-python,BayanGroup/sentry,camilonova/sentry,beni55/sentry,TedaLIEz/sentry,JackDanger/sentry,gencer/sentry,beniwohli/apm-agent-python,WoLpH/django-sentry,BuildingLink/sentry,mvaled/sentry,korealerts1/sentry,tarkatronic/opbeat_python,camilonova/sentry,jokey2k/sentry,inspirehep/raven-python,primepix/django-sentry,songyi199111/sentry,kevinlondon/sentry,drcapulet/sentry,ifduyue/sentry,akheron/raven-python,zenefits/sentry,daikeren/opbeat_python,nicholasserra/sentry,llonchj/sentry,JackDanger/sentry,fotinakis/sentry,jmp0xf/raven-python,tarkatronic/opbeat_python,ticosax/opbeat_python,JackDanger/sentry,alex/raven,fuziontech/sentry,JamesMura/sentry,felixbuenemann/sentry,daevaorn/sentry,smarkets/raven-python,mitsuhiko/sentry,Kronuz/django-sentry,lepture/raven-python,akalipetis/raven-python,dcramer/sentry-old,inspirehep/raven-python,ifduyue/sentry,wujuguang/sentry,beniwohli/apm-agent-python,felixbuenemann/sentry,jbarbuto/raven-python,gencer/sentry,ngonzalvez/sentry,ewdurbin/raven-python,patrys/opbeat_python,patrys/opbeat_python,mvaled/sentry,ticosax/opbeat_python,hongliang5623/sentry,chayapan/django-sentry,jokey2k/sentry,icereval/raven-python,lopter/raven-python-old,BuildingLink/sentry,korealerts1/sentry,beeftornado/sentry,nicholasserra/sentry,pauloschilling/sentry,wong2/sentry,boneyao/sentry,rdio/sentry,dirtycoder/opbeat_python,daevaorn/sentry,ngonzalvez/sentry,hzy/raven-python,wong2/sentry,someonehan/raven-python,zenefits/sentry,dcramer/sentry-old,JamesMura/sentry,recht/raven-python,looker/sentry,getsentry/raven-python,BuildingLink/sentry,ewdurbin/sentry,argonemyth/sentry,inspirehep/raven-python,JamesMura/sentry,Natim/sentry,hongliang5623/sentry,llonchj/sentry,imankulov/sentry,beni55/sentry,vperron/sentry,fotinakis/sentry,zenefits/sentry,1tush/sentry,ewdurbin/raven-python,NickPresta/sentry,Kronuz/django-sentry,JTCunning/sentry,kevinlondon/sentry,rdio/sentry,daevaorn/sentry,hzy/raven-python,dirtycoder/opbeat_python,danriti/raven-python,beniwohli/apm-agent-python,vperron/sentry,NickPresta/sentry,ronaldevers/raven-python,mitsuhiko/raven,chayapan/django-sentry,getsentry/raven-python,kevinastone/sentry,danriti/raven-python,ewdurbin/sentry,zenefits/sentry,lepture/raven-python,nikolas/raven-python,Kryz/sentry,patrys/opbeat_python,jmp0xf/raven-python,jmp0xf/raven-python,someonehan/raven-python,BayanGroup/sentry,inspirehep/raven-python,looker/sentry,ewdurbin/sentry,Natim/sentry,kevinastone/sentry,NickPresta/sentry,camilonova/sentry,boneyao/sentry,nikolas/raven-python,korealerts1/sentry,ifduyue/sentry,dbravender/raven-python,alexm92/sentry,Kryz/sentry,percipient/raven-python,collective/mr.poe,johansteffner/raven-python,mvaled/sentry,looker/sentry,icereval/raven-python,WoLpH/django-sentry,argonemyth/sentry,lepture/raven-python,openlabs/raven,alexm92/sentry,alex/sentry,llonchj/sentry,vperron/sentry,gencer/sentry,jbarbuto/raven-python,daikeren/opbeat_python,jean/sentry,looker/sentry,daikeren/opbeat_python,dcramer/sentry-old,daevaorn/sentry | ---
+++
@@ -12,7 +12,6 @@
packages=find_packages(),
zip_safe=False,
install_requires=[
- # Optional
'django-paging>=0.2.2',
'django-indexer==0.2',
], |
c486d44cbb6007d5a89f36746822e68ea8cb0afa | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="cumulus",
version="0.1.0",
description="Girder API endpoints for interacting with cloud providers.",
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
packages=find_packages(),
package_data={
"": ["*.json"],
"cumulus": ["conf/*.json"],
})
| from setuptools import setup, find_packages
setup(
name="cumulus",
version="0.1.0",
description="Girder API endpoints for interacting with cloud providers.",
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
packages=find_packages(exclude=["*.tests", "*.tests.*",
"tests.*", "tests"]),
package_data={
"": ["*.json", "*.sh"],
"cumulus": ["conf/*.json"],
})
| Exclude unit tests from install | Exclude unit tests from install
| Python | apache-2.0 | Kitware/cumulus,Kitware/cumulus,cjh1/cumulus,cjh1/cumulus | ---
+++
@@ -7,8 +7,9 @@
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
- packages=find_packages(),
+ packages=find_packages(exclude=["*.tests", "*.tests.*",
+ "tests.*", "tests"]),
package_data={
- "": ["*.json"],
+ "": ["*.json", "*.sh"],
"cumulus": ["conf/*.json"],
}) |
208f31883a42bc1407f2f911f627b44fd23bf8b1 | setup.py | setup.py | #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long_description,
author="Russell Keith-Magee",
author_email="russell@keith-magee.com",
url='http://github.com/freakboy3742/pyspamsum/',
license="New BSD",
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Text Processing',
'Topic :: Utilities',
],
ext_modules=[
Extension(
"spamsum", [
"pyspamsum.c",
"spamsum.c",
"edit_dist.c",
]
)
],
test_suite='tests',
)
| #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long_description,
author="Russell Keith-Magee",
author_email="russell@keith-magee.com",
url='http://github.com/freakboy3742/pyspamsum/',
license="New BSD",
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Text Processing',
'Topic :: Utilities',
],
ext_modules=[
Extension(
"spamsum", [
"pyspamsum.c",
"spamsum.c",
"edit_dist.c",
]
)
],
test_suite='tests',
)
| Remove support for deprecated Python versions. | Remove support for deprecated Python versions.
| Python | bsd-3-clause | freakboy3742/pyspamsum,freakboy3742/pyspamsum | ---
+++
@@ -21,11 +21,7 @@
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.4',
- 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8', |
1fd8ea9c746bc1c3fa0dc95a3b00244f97373976 | setup.py | setup.py | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| Remove download URL since Github doesn't get his act together. Damnit | Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <48255722c72bb2e7f7bec0fff5f60dc7fb5357fb@12edf5ea-513a-0410-8a8c-37067077e60f>
| Python | bsd-3-clause | Jythoner/django-robots,Jythoner/django-robots | ---
+++
@@ -8,7 +8,6 @@
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
- download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[ |
743fcf5266235b47cfec7f9e12b7df0378f4f9c4 | solar/solar/extensions/modules/discovery.py | solar/solar/extensions/modules/discovery.py | import io
import os
import yaml
from solar.extensions import base
class Discovery(base.BaseExtension):
VERSION = '1.0.0'
ID = 'discovery'
PROVIDES = ['nodes_resources']
COLLECTION_NAME = 'nodes'
FILE_PATH = os.path.join(
# TODO(pkaminski): no way we need '..' here...
os.path.dirname(__file__), '..', '..', '..', '..',
'examples', 'nodes_list.yaml')
def discover(self):
with io.open(self.FILE_PATH) as f:
nodes = yaml.load(f)
for node in nodes:
node['tags'] = []
self.db.store_list(self.COLLECTION_NAME, nodes)
return nodes
def nodes_resources(self):
nodes_list = self.db.get_list(self.COLLECTION_NAME)
nodes_resources = []
for node in nodes_list:
node_resource = {}
node_resource['id'] = node['id']
node_resource['name'] = node['id']
node_resource['handler'] = 'data'
node_resource['type'] = 'resource'
node_resource['version'] = self.VERSION
node_resource['tags'] = node['tags']
node_resource['output'] = node
node_resource['ssh_host'] = node['ip']
# TODO replace it with ssh type
node_resource['connection_type'] = 'local'
nodes_resources.append(node_resource)
return nodes_resources
| import io
import os
import yaml
from solar.extensions import base
class Discovery(base.BaseExtension):
VERSION = '1.0.0'
ID = 'discovery'
PROVIDES = ['nodes_resources']
COLLECTION_NAME = 'nodes'
FILE_PATH = os.path.join(
# TODO(pkaminski): no way we need '..' here...
os.path.dirname(__file__), '..', '..', '..', '..',
'examples', 'nodes_list.yaml')
def discover(self):
with io.open(self.FILE_PATH) as f:
nodes = yaml.load(f)
for node in nodes:
node['tags'] = ['node/{0}'.format(node['id'])]
self.db.store_list(self.COLLECTION_NAME, nodes)
return nodes
def nodes_resources(self):
nodes_list = self.db.get_list(self.COLLECTION_NAME)
nodes_resources = []
for node in nodes_list:
node_resource = {}
node_resource['id'] = node['id']
node_resource['name'] = node['id']
node_resource['handler'] = 'data'
node_resource['type'] = 'resource'
node_resource['version'] = self.VERSION
node_resource['tags'] = node['tags']
node_resource['output'] = node
node_resource['ssh_host'] = node['ip']
# TODO replace it with ssh type
node_resource['connection_type'] = 'local'
nodes_resources.append(node_resource)
return nodes_resources
| Add node specific tag generation | Add node specific tag generation
| Python | apache-2.0 | pigmej/solar,pigmej/solar,torgartor21/solar,torgartor21/solar,zen/solar,loles/solar,Mirantis/solar,CGenie/solar,pigmej/solar,zen/solar,dshulyak/solar,openstack/solar,Mirantis/solar,loles/solar,openstack/solar,Mirantis/solar,dshulyak/solar,Mirantis/solar,CGenie/solar,loles/solar,loles/solar,openstack/solar,zen/solar,zen/solar | ---
+++
@@ -24,7 +24,7 @@
nodes = yaml.load(f)
for node in nodes:
- node['tags'] = []
+ node['tags'] = ['node/{0}'.format(node['id'])]
self.db.store_list(self.COLLECTION_NAME, nodes)
|
d5e05aa44998e6f2cebc41b0c945d234eeb6317d | gcloud/search/connection.py | gcloud/search/connection.py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create / interact with gcloud search connections."""
from gcloud import connection as base_connection
class Connection(base_connection.JSONConnection):
"""A connection to Google Cloud Search via the JSON REST API."""
API_BASE_URL = 'https://cloudsearch.googleapis.com'
"""The base of the API call URL."""
API_VERSION = 'v1'
"""The version of the API, used in building the API call's URL."""
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
SCOPE = ('https://www.googleapis.com/auth/ndev.cloudsearch',)
"""The scopes required for authenticating as a Cloud Search consumer."""
| # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create / interact with gcloud search connections."""
from gcloud import connection as base_connection
class Connection(base_connection.JSONConnection):
"""A connection to Google Cloud Search via the JSON REST API."""
API_BASE_URL = 'https://cloudsearch.googleapis.com'
"""The base of the API call URL."""
API_VERSION = 'v1'
"""The version of the API, used in building the API call's URL."""
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
SCOPE = ('https://www.googleapis.com/auth/cloudsearch',)
"""The scopes required for authenticating as a Cloud Search consumer."""
| Fix scope used for Cloud Search. | Fix scope used for Cloud Search.
| Python | apache-2.0 | googleapis/google-cloud-python,VitalLabs/gcloud-python,jgeewax/gcloud-python,waprin/google-cloud-python,tseaver/gcloud-python,jgeewax/gcloud-python,jonparrott/google-cloud-python,tswast/google-cloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,jonparrott/gcloud-python,dhermes/google-cloud-python,jonparrott/google-cloud-python,Fkawala/gcloud-python,quom/google-cloud-python,daspecster/google-cloud-python,waprin/gcloud-python,waprin/gcloud-python,dhermes/gcloud-python,Fkawala/gcloud-python,GoogleCloudPlatform/gcloud-python,tartavull/google-cloud-python,jonparrott/gcloud-python,tseaver/google-cloud-python,tseaver/google-cloud-python,tswast/google-cloud-python,dhermes/gcloud-python,dhermes/google-cloud-python,quom/google-cloud-python,elibixby/gcloud-python,tseaver/gcloud-python,VitalLabs/gcloud-python,elibixby/gcloud-python,tartavull/google-cloud-python,tswast/google-cloud-python,calpeyser/google-cloud-python,googleapis/google-cloud-python,calpeyser/google-cloud-python,GoogleCloudPlatform/gcloud-python,daspecster/google-cloud-python,waprin/google-cloud-python | ---
+++
@@ -29,5 +29,5 @@
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
- SCOPE = ('https://www.googleapis.com/auth/ndev.cloudsearch',)
+ SCOPE = ('https://www.googleapis.com/auth/cloudsearch',)
"""The scopes required for authenticating as a Cloud Search consumer.""" |
f4fb4e90725cec378634c22ee8803eeb29ccf143 | conveyor/processor.py | conveyor/processor.py | from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(self.index)
def process(self):
raise NotImplementedError
def get_releases(self, name, version=None):
if version is None:
return set(self.client.package_releases(name, True))
else:
return set([version])
class BulkProcessor(BaseProcessor):
def process(self):
pass
| from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(self.index)
def process(self):
raise NotImplementedError
def get_releases(self, name, version=None):
if version is None:
return self.client.package_releases(name, True)
else:
return [version]
class BulkProcessor(BaseProcessor):
def process(self):
pass
| Switch from returning a set to returning a list | Switch from returning a set to returning a list
| Python | bsd-2-clause | crateio/carrier | ---
+++
@@ -18,9 +18,9 @@
def get_releases(self, name, version=None):
if version is None:
- return set(self.client.package_releases(name, True))
+ return self.client.package_releases(name, True)
else:
- return set([version])
+ return [version]
class BulkProcessor(BaseProcessor): |
22ab7f94c3b8b04a50cd11e73b2963bddb0470a5 | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "poradnia.informacjapubliczna.org.pl",
"name": "poradnia"
}
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "example.com",
"name": "example.com"
}
)
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.RunPython(update_site_forward, update_site_backward),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "porady.siecobywatelska.pl",
"name": "poradnia"
}
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "example.com",
"name": "example.com"
}
)
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.RunPython(update_site_forward, update_site_backward),
]
| Fix migrations - drop old domain | Fix migrations - drop old domain
| Python | mit | rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia | ---
+++
@@ -11,7 +11,7 @@
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
- "domain": "poradnia.informacjapubliczna.org.pl",
+ "domain": "porady.siecobywatelska.pl",
"name": "poradnia"
}
) |
73feddb22ad3a2543ad4f8047061d909c64fd75d | server/system/CommonMySQL.py | server/system/CommonMySQL.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCfg('MYSQL', 'idField')
tableLogin = getCfg('MYSQL', 'loginField')
tablePassword = getCfg('MYSQL', 'passwordField')
try:
# Starting
con = connect()
cur = con.cursor()
cur.execute(
'SELECT ' + tableId + ' FROM ' + table +
' WHERE ' + tableLogin + '=%s AND ' + tablePassword + '=%s',
(
login,
password
)
)
userContent = cur.fetchone()
if userContent is not None:
userContent = userContent[0]
except db.Error as e:
logging.error('loginUser: Error from MySQL => %s' % e)
finally:
if con:
con.close()
return userContent | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
import logging
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCfg('MYSQL', 'idField')
tableLogin = getCfg('MYSQL', 'loginField')
tablePassword = getCfg('MYSQL', 'passwordField')
con = None
try:
# Starting
con = connect()
cur = con.cursor()
cur.execute(
'SELECT ' + tableId + ' FROM ' + table +
' WHERE ' + tableLogin + '=%s AND ' + tablePassword + '=%s',
(
login,
password
)
)
userContent = cur.fetchone()
if userContent is not None:
userContent = userContent[0]
except Exception as e:
logging.error('loginUser: Error from MySQL => %s' % e)
finally:
if con:
con.close()
return userContent | Remove some bug on mysql elements. | Remove some bug on mysql elements.
| Python | mit | Deisss/webservice-notification,Deisss/webservice-notification | ---
+++
@@ -3,6 +3,7 @@
from system.DBMysql import connect
from system.ConfigLoader import getCfg
+import logging
def loginUser(login, password):
''' Try to login a user regarding login/password '''
@@ -13,6 +14,7 @@
tableLogin = getCfg('MYSQL', 'loginField')
tablePassword = getCfg('MYSQL', 'passwordField')
+ con = None
try:
# Starting
con = connect()
@@ -32,7 +34,7 @@
if userContent is not None:
userContent = userContent[0]
- except db.Error as e:
+ except Exception as e:
logging.error('loginUser: Error from MySQL => %s' % e)
finally:
if con: |
9ffb43c969288bdb06de20aded660bd7e4e5c337 | plugins/witai.py | plugins/witai.py | import os
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
@respond_to('')
def wit(message):
message.react('+1')
message.reply('You said: ' + message.body['text'])
wit_client.run_actions('asdf', message.body['text'])
| import os
import random
import string
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
wit_context = {}
def random_word(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
@respond_to('')
def wit(message):
global wit_context
message.react('+1')
wit_context = wit_client.run_actions(
random_word(10),
message.body['text'],
wit_context)
| Create new session on restart | Create new session on restart
| Python | mit | sanjaybv/netbot | ---
+++
@@ -1,4 +1,6 @@
import os
+import random
+import string
from slackbot.bot import respond_to
from slackbot.bot import listen_to
@@ -11,9 +13,18 @@
actions=actions
)
+wit_context = {}
+
+def random_word(length):
+ return ''.join(random.choice(string.lowercase) for i in range(length))
+
@respond_to('')
def wit(message):
+ global wit_context
+
message.react('+1')
- message.reply('You said: ' + message.body['text'])
- wit_client.run_actions('asdf', message.body['text'])
+ wit_context = wit_client.run_actions(
+ random_word(10),
+ message.body['text'],
+ wit_context) |
667fbe85d0e0ce60a696e63aa705dcb6b59c1214 | geokey_wegovnow/__init__.py | geokey_wegovnow/__init__.py | """Main initialization for the WeGovNow extension."""
VERSION = (3, 1, 1)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
)
except BaseException:
print 'Please install GeoKey first'
| """Main initialization for the WeGovNow extension."""
VERSION = (3, 1, 2)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
)
except BaseException:
print 'Please install GeoKey first'
| Increment patch number following bugfix. | Increment patch number following bugfix. | Python | mit | ExCiteS/geokey-wegovnow,ExCiteS/geokey-wegovnow | ---
+++
@@ -1,6 +1,6 @@
"""Main initialization for the WeGovNow extension."""
-VERSION = (3, 1, 1)
+VERSION = (3, 1, 2)
__version__ = '.'.join(map(str, VERSION))
|
25351cd6b9119ea27123a2fddbbcc274c3620886 | examples/examples.py | examples/examples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size = (1000, ndim)
data = np.random.normal(size=size)
eta, lam = 4, -.9
skst = SkewStudent(eta=eta, lam=lam)
data = skst.rvs(size=size)
out = MultiDensity.fit_mle(data=data)
print(out)
mdens = MultiDensity()
mdens.from_theta(out.x)
fig, axes = plt.subplots(nrows=size[1], ncols=1)
for innov, ax in zip(data.T, axes):
sns.kdeplot(innov, ax=ax)
lines = [ax.get_lines()[0].get_xdata() for ax in axes]
lines = np.vstack(lines).T
marginals = mdens.marginals(lines)
for line, margin, ax in zip(lines.T, marginals.T, axes):
ax.plot(line, margin)
plt.show()
if __name__ == '__main__':
estimate_bivariate_mle()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size = (1000, ndim)
data = np.random.normal(size=size)
eta, lam = 4, -.9
skst = SkewStudent(eta=eta, lam=lam)
data = skst.rvs(size=size)
out = MultiDensity.fit_mle(data=data)
print(out)
mdens = MultiDensity()
mdens.from_theta(out.x)
fig, axes = plt.subplots(nrows=size[1], ncols=1)
for innov, ax in zip(data.T, axes):
sns.kdeplot(innov, ax=ax, label='data')
lines = [ax.get_lines()[0].get_xdata() for ax in axes]
lines = np.vstack(lines).T
marginals = mdens.marginals(lines)
for line, margin, ax in zip(lines.T, marginals.T, axes):
ax.plot(line, margin, label='fitted')
ax.legend()
plt.show()
if __name__ == '__main__':
estimate_bivariate_mle()
| Add plot legend in the example | Add plot legend in the example
| Python | mit | khrapovs/multidensity | ---
+++
@@ -29,14 +29,15 @@
fig, axes = plt.subplots(nrows=size[1], ncols=1)
for innov, ax in zip(data.T, axes):
- sns.kdeplot(innov, ax=ax)
+ sns.kdeplot(innov, ax=ax, label='data')
lines = [ax.get_lines()[0].get_xdata() for ax in axes]
lines = np.vstack(lines).T
marginals = mdens.marginals(lines)
for line, margin, ax in zip(lines.T, marginals.T, axes):
- ax.plot(line, margin)
+ ax.plot(line, margin, label='fitted')
+ ax.legend()
plt.show()
|
cde9dd479b2974f26f2e50b3611bfd0756f86c2b | game_of_thrones/__init__.py | game_of_thrones/__init__.py | class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
return [pair for pair in zip(text[0::1], text[1::1])]
| class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya')
[('A', 'r'), ('r', 'y'), ('y', 'a')]
"""
return [pair for pair in zip(text[0::1], text[1::1])]
| Add docstring to the `pair_symbols` method | Add docstring to the `pair_symbols` method
| Python | mit | Matt-Deacalion/Name-of-Thrones | ---
+++
@@ -6,4 +6,10 @@
self.text = text
def pair_symbols(self, text):
+ """
+ Takes an string and returns a list of tuples. For example:
+
+ >>> pair_symbols('Arya')
+ [('A', 'r'), ('r', 'y'), ('y', 'a')]
+ """
return [pair for pair in zip(text[0::1], text[1::1])] |
c8cbd2c660a2e10cc021bdc0a2fead872f77967d | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
| # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.iterator():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
| Use iterator in resultset data migration | Use iterator in resultset data migration
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -14,7 +14,7 @@
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
@@ -23,7 +23,7 @@
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.iterator():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
) |
32d2d6069191cd2f7e98d1dedce13ddc1a6b1f32 | config.py | config.py | dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://sixpak.org/finance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| Use example.com for API URL. | Use example.com for API URL. | Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash | ---
+++
@@ -1,6 +1,6 @@
dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
-apiurl = "https://sixpak.org/finance/api.py"
+apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.