commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
413bebe630c29764dcbf17b114662427edfdac3c
|
pydot/errors.py
|
pydot/errors.py
|
class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
try:
self.err_code = json_response['@attributes']['err_code']
self.message = str(json_response['err'])
except KeyError:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
|
class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
self.err_code = json_response.get('@attributes').get('err_code')
self.message = str(json_response.get('err'))
if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
|
Refactor error data extraction from JSON
|
Refactor error data extraction from JSON
|
Python
|
mit
|
joshgeller/PyPardot
|
13e4a0ef064460ffa90bc150dc04b9a1fff26a1c
|
blanc_basic_news/news/templatetags/news_tags.py
|
blanc_basic_news/news/templatetags/news_tags.py
|
from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
|
from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
|
Add a template tag to get the latest news posts.
|
Add a template tag to get the latest news posts.
|
Python
|
bsd-3-clause
|
blancltd/blanc-basic-news
|
649f2aa5a23541a4c57372eeb34a337d84dd0f86
|
timed/tests/test_serializers.py
|
timed/tests/test_serializers.py
|
from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key = 'test_nr'
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
|
from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
|
Remove obsolete pk_key in test
|
Remove obsolete pk_key in test
|
Python
|
agpl-3.0
|
adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend
|
2b2401fcbefc5c385f5e84057a76a4fcdbed0030
|
serfnode/handler/handler.py
|
serfnode/handler/handler.py
|
#!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
handler = SerfHandlerProxy()
handler.register(os.environ.get('ROLE', 'no_role'), MyHandler())
handler.run()
|
#!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
handler = SerfHandlerProxy()
role = os.environ.get('ROLE') or 'no_role'
handler.register(role, MyHandler())
handler.run()
|
Set 'no_role' if role is not given
|
Set 'no_role' if role is not given
|
Python
|
mit
|
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
|
62a3ab3409dbc1dd22896fb7c3b5376c1b6432e2
|
AcmePlumbingSend.py
|
AcmePlumbingSend.py
|
import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(MouseCommand):
""" Sends the current selected text to the plumbing """
def run(self, edit):
file_name = self.view.file_name()
message = {
"data": self.view.substr(self.selection_at_cursor()),
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
self.remove_selection("1") # in case it was expanded
self.view.sel().clear()
self.view.run_command("acme_plumbing", message)
|
import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(MouseCommand):
""" Sends the current selected text to the plumbing """
def run(self, edit):
file_name = self.view.file_name()
message = {
"data": self.view.substr(self.selection_at_cursor()),
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
self.view.sel().clear()
self.view.run_command("acme_plumbing", message)
|
Remove artefact from earlier left mouse button selection
|
Remove artefact from earlier left mouse button selection
You used to be able to select with the left mouse button and then right click.
You can't now.
|
Python
|
mit
|
lionicsheriff/SublimeAcmePlumbing
|
ed2c56cd044f905c4325f42b4e9cf7a5df913bfd
|
books/models.py
|
books/models.py
|
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(auto_now=True)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
|
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
|
Set created time with default callback
|
Set created time with default callback
auto_now is evil, as any editing and overriding is
almost completely impossible (e.g. unittesting)
|
Python
|
mit
|
trimailov/finance,trimailov/finance,trimailov/finance
|
5bc51f525c702cd43d3d7bc3819d179815c41807
|
foliant/backends/pre.py
|
foliant/backends/pre.py
|
from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_dir_name = f'{self.get_slug()}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
|
from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
|
Allow to override the top-level slug.
|
Allow to override the top-level slug.
|
Python
|
mit
|
foliant-docs/foliant
|
4e3e1c3e70f5ba60ae9637febe4d95348561dd47
|
db/editjsonfile.py
|
db/editjsonfile.py
|
#!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
aesjsonfile.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = sys.stdin.readline()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
print len
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
#!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
aesjsonfile.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
Clean up input and output.
|
Clean up input and output.
|
Python
|
agpl-3.0
|
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
|
c37e3fe832ef3f584a60783a474b31f9f91e3735
|
github_webhook/test_webhook.py
|
github_webhook/test_webhook.py
|
"""Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# 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.
# ----------------------------- END-OF-FILE -----------------------------------
|
"""Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# 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.
# ----------------------------- END-OF-FILE -----------------------------------
|
Fix mock import for Python 3
|
Fix mock import for Python 3
|
Python
|
apache-2.0
|
fophillips/python-github-webhook
|
8adbb5c9cc089663bcdc62496415d666c9f818a3
|
service/inchi.py
|
service/inchi.py
|
import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
return None
print cjson
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
|
import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
|
Add log statement if REST API can't be accessed
|
Add log statement if REST API can't be accessed
|
Python
|
bsd-3-clause
|
OpenChemistry/mongochemweb,OpenChemistry/mongochemweb
|
94bcaa24f0dc1c0750023770574e26bb41183c6a
|
hangupsbot/plugins/namelock.py
|
hangupsbot/plugins/namelock.py
|
"""Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
|
"""Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
"""Rename Hangout"""
yield from bot._client.setchatname(event.conv_id, ' '.join(args))
|
Make hangout rename itself after setchatname is called
|
Make hangout rename itself after setchatname is called
|
Python
|
agpl-3.0
|
makiftasova/hangoutsbot,cd334/hangoutsbot,jhonnyam123/hangoutsbot
|
89b7b7f7fe1ec50f1d0bdfba7581f76326efe717
|
dacapo_analyzer.py
|
dacapo_analyzer.py
|
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
|
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
|
Use only msecs of dacapo output.
|
[client] Use only msecs of dacapo output.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
|
Python
|
mit
|
fhirschmann/penchy,fhirschmann/penchy
|
f5cc0d9327f35d818b10e200404c849a5527aa50
|
indra/databases/hgnc_client.py
|
indra/databases/hgnc_client.py
|
import urllib2
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
|
import urllib2
from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
|
Add caching to HGNC client
|
Add caching to HGNC client
|
Python
|
bsd-2-clause
|
johnbachman/belpy,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,jmuhlich/indra
|
3b3da9ffc5f8247020d2c6c58f83d95e8dbf8dd6
|
serrano/cors.py
|
serrano/cors.py
|
from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_CORS_ORIGINS', DeprecationWarning)
allowed_origins = [s.strip() for s in
settings.SERRANO_CORS_ORIGIN.split(',')]
else:
allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ())
origin = request.META.get('HTTP_ORIGIN')
if not allowed_origins or origin in allowed_origins:
# The origin must be explicitly listed when used with the
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
if request.method == 'OPTIONS':
response['Access-Control-Allow-Credentials'] = 'true'
response['Access-Control-Allow-Methods'] = ', '.join(methods)
headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa
if headers:
response['Access-Control-Allow-Headers'] = headers
return response
|
from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_CORS_ORIGINS', DeprecationWarning)
allowed_origins = [s.strip() for s in
settings.SERRANO_CORS_ORIGIN.split(',')]
else:
allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ())
origin = request.META.get('HTTP_ORIGIN')
if not allowed_origins or origin in allowed_origins:
# The origin must be explicitly listed when used with the
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
response['Access-Control-Allow-Credentials'] = 'true'
if request.method == 'OPTIONS':
response['Access-Control-Allow-Methods'] = ', '.join(methods)
headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa
if headers:
response['Access-Control-Allow-Headers'] = headers
return response
|
Set Access-Control-Allow-Credentials for all responses
|
Set Access-Control-Allow-Credentials for all responses
In order to inform the browser to set the Cookie header on requests, this
header must be set otherwise the session is reset on every request.
|
Python
|
bsd-2-clause
|
chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night
|
77a965f27f75a8a5268ad95538d6625cecb44bfa
|
south/models.py
|
south/models.py
|
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
|
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
|
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
|
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
|
Python
|
apache-2.0
|
matthiask/south,matthiask/south
|
3ff91625fc99e279078547220fb4358d647c828a
|
deflect/widgets.py
|
deflect/widgets.py
|
from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select style="display:none">')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
|
from __future__ import unicode_literals
from itertools import chain
from django.contrib.admin.widgets import AdminTextInputWidget
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(AdminTextInputWidget):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select style="display:none">')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
|
Change the superclass for admin DataList widget
|
Change the superclass for admin DataList widget
This adds an additional class so it displays the same as other
text fields in the admin interface.
|
Python
|
bsd-3-clause
|
jbittel/django-deflect
|
87cfac55b14083fdb8e346b9db1a95bb0f63881a
|
connect/config/factories.py
|
connect/config/factories.py
|
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
|
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
|
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
|
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
|
Python
|
bsd-3-clause
|
nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect
|
78ba73998168d8e723d1c62942b19dabfd9ab229
|
src/constants.py
|
src/constants.py
|
#!/usr/bin/env python
SIMULATION_TIME_IN_SECONDS = 40
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
TRAJECTORY_TYPE = 'linear'
|
#!/usr/bin/env python
TRAJECTORY_TYPE = 'circular'
if TRAJECTORY_TYPE == 'linear':
SIMULATION_TIME_IN_SECONDS = 40
elif TRAJECTORY_TYPE == 'circular':
SIMULATION_TIME_IN_SECONDS = 120
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
|
Define simulation time for linear and circular trajectories
|
Define simulation time for linear and circular trajectories
|
Python
|
mit
|
bit0001/trajectory_tracking,bit0001/trajectory_tracking
|
b3413818bf651c13cef047132813fb26a185cd33
|
indra/tests/test_reading_files.py
|
indra/tests/test_reading_files.py
|
from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
Fix the reading files test.
|
Fix the reading files test.
|
Python
|
bsd-2-clause
|
johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy
|
fd951edbef26dcab2a4b89036811520b22e77fcf
|
marry-fuck-kill/main.py
|
marry-fuck-kill/main.py
|
#!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
# TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
Remove TODO -- handlers have been cleaned up.
|
Remove TODO -- handlers have been cleaned up.
|
Python
|
apache-2.0
|
hjfreyer/marry-fuck-kill,hjfreyer/marry-fuck-kill
|
366937921cfb13fd83fb5964d0373be48e3c8564
|
cmsplugin_plain_text/models.py
|
cmsplugin_plain_text/models.py
|
# -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
|
# -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
|
Add `__str__` method to support Python 3
|
Add `__str__` method to support Python 3
|
Python
|
bsd-3-clause
|
chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text
|
d15bfddd59f0009852ff5f69a665c8858a5cdd40
|
__init__.py
|
__init__.py
|
r"""
============================================
msm - Markov state models (:mod:`pyemma.msm`)
============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
"""
from . import analysis
from . import estimation
from . import generation
from . import io
from . import flux
from .api import *
|
r"""
=============================================
msm - Markov state models (:mod:`pyemma.msm`)
=============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
its
msm
tpt
cktest
hmsm
"""
from . import analysis
from . import estimation
from . import generation
from . import io
from . import flux
from .api import *
|
Add autodoc for msm user-API
|
[doc] Add autodoc for msm user-API
|
Python
|
bsd-3-clause
|
clonker/ci-tests
|
08c2f9fe24b6ce7697bf725e70855e8d6861c370
|
pandas/__init__.py
|
pandas/__init__.py
|
"""This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from geopandas_data import GeopandasDataFrame
from geopandas_reader import GeopandasReader
from geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
"""This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from gaia.pandas.geopandas_data import GeopandasDataFrame
from gaia.pandas.geopandas_reader import GeopandasReader
from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
Use only absolute imports for python 3
|
Use only absolute imports for python 3
|
Python
|
apache-2.0
|
Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco
|
8e900343312fa644a21e5b209b83431ced3c3020
|
inet/constants.py
|
inet/constants.py
|
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ.get("OPS_KEY")
OPS_SECRET = os.environ.get("OPS_SECRET")
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_ACCESS']
TWITTER_SECRET = os.environ['TWITTER_SECRET']
|
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ["OPS_KEY"]
OPS_SECRET = os.environ["OPS_SECRET"]
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_ACCESS']
TWITTER_SECRET = os.environ['TWITTER_SECRET']
|
Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised
|
Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised
|
Python
|
mit
|
nestauk/inet
|
08247c2d4cb3cf1879b568697d7888728ebb1c3b
|
parse_rest/role.py
|
parse_rest/role.py
|
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
Role.Query = QueryManager(Role)
|
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
def removeRelation(self, key, className, objectsId):
self.manageRelation('RemoveRelation', key, className, objectsId)
def addRelation(self, key, className, objectsId):
self.manageRelation('AddRelation', key, className, objectsId)
def manageRelation(self, action, key, className, objectsId):
objects = [{
"__type": "Pointer",
"className": className,
"objectId": objectId
} for objectId in objectsId]
payload = {
key: {
"__op": action,
"objects": objects
}
}
self.__class__.PUT(self._absolute_url, **payload)
self.__dict__[key] = ''
Role.Query = QueryManager(Role)
|
Handle adding and removing relations from Roles.
|
Handle adding and removing relations from Roles.
This adds addRelation and removeRelation capabilities to Role, making it possible to add users to the users column and roles to the roles column in a Role object, for example. This prevents the error of Role not having the attribute addRelation or removeRelation when trying to add users or roles to a Role, which is critical for Role functionality.
|
Python
|
mit
|
alacroix/ParsePy,milesrichardson/ParsePy,milesrichardson/ParsePy,alacroix/ParsePy
|
02d67008d0f0bdc205ca9168384c4a951c106a28
|
nintendo/common/transport.py
|
nintendo/common/transport.py
|
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
|
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def bind(self, addr=("", 0)): self.s.bind(addr)
def sendto(self, data, addr): self.s.sendto(data, addr)
def recvfrom(self, num):
try:
return self.s.recvfrom(num)
except BlockingIOError:
return None, None
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
|
Add a few functions to Socket class
|
Add a few functions to Socket class
|
Python
|
mit
|
Kinnay/NintendoClients
|
60d8b38eac3c36bd754f5ed01aae6d3af1918adc
|
notifications/match_score.py
|
notifications/match_score.py
|
from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self._event_feed = match.event.id
# TODO Add notion of District to Match model?
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.match.event.get().name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
|
from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
|
Add district feed to match score notification
|
Add district feed to match score notification
|
Python
|
mit
|
phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance
|
f4c56937caacb4709847d67752f4ff3cba4568f6
|
tests/test_it.py
|
tests/test_it.py
|
import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
@skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, ])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
|
import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
|
Remove decorator 'skip_in_ci' from test_files
|
Remove decorator 'skip_in_ci' from test_files
Because implement stub of capture engine, 'Output slides pdf' test can run in CircleCI
|
Python
|
mit
|
attakei/deck2pdf-python,attakei/deck2pdf-python,attakei/slide2pdf,attakei/deck2pdf,attakei/slide2pdf,attakei/deck2pdf
|
d5b231fbc5dd32ded78e4499a49872487533cda4
|
tests/test_main.py
|
tests/test_main.py
|
from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
|
from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
def test_expand_abbreviations():
template = 'gh:audreyr/cookiecutter-pypackage'
# This is not a valid repo url just yet!
# First `main.expand_abbreviations` needs to translate it
assert is_repo_url(template) is False
expanded_template = expand_abbreviations(template, {})
assert is_repo_url(expanded_template) is True
|
Implement a test specifically for abbreviations
|
Implement a test specifically for abbreviations
|
Python
|
bsd-3-clause
|
willingc/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,pjbull/cookiecutter,cguardia/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,cguardia/cookiecutter,willingc/cookiecutter,ramiroluz/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter
|
1028afcdc1e8e1027b10fe5254f5fe5b9499eddd
|
tests/test_void.py
|
tests/test_void.py
|
"""test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
|
"""test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
|
Fix imports for void tests
|
Fix imports for void tests
|
Python
|
apache-2.0
|
ec-geolink/glharvest,ec-geolink/glharvest,ec-geolink/glharvest
|
43fd422599972f9385c9f3f9bc5a9a2e5947e0ea
|
web/webhooks.py
|
web/webhooks.py
|
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
|
import hashlib
import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def verify_signature(request, repo):
signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if not signature:
return False
repo_secret = jucybot.getSecretForRepo(repo)
h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
reference = 'sha1=%s' % h.hexdigest()
return reference == signature
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if not verify_signature(request, repo):
return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
|
Check HMAC digests in webhook notifications before handling them.
|
Check HMAC digests in webhook notifications before handling them.
Bump #1
|
Python
|
apache-2.0
|
Jucyio/Jucy,Jucyio/Jucy,Jucyio/Jucy
|
f9884fc274d2068051edb41f9ad13ad25a7f1c72
|
isogram/isogram.py
|
isogram/isogram.py
|
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
|
from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's marginally slower
|
Add note about str.isalpha() method as an alternative
|
Add note about str.isalpha() method as an alternative
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
d2c368995e33b375404e3c01f79fdc5a14a48282
|
polyaxon/libs/repos/utils.py
|
polyaxon/libs/repos/utils.py
|
from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_project_code_reference(project, commit=None):
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_code_reference(instance, commit):
return get_project_code_reference(instance.project, commit=commit)
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
if not commit and instance.specification and instance.specification.build:
commit = instance.specification.build.commit
code_reference = get_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
|
from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_code_reference(instance, commit=None, external_repo=None):
project = instance.project
repo = project.repo if project.has_code else external_repo
if not repo:
return None
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.commit
external_repo = build.git if build and build.git else None
code_reference = get_code_reference(instance=instance,
commit=commit,
external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
return instance
|
Extend code references with external repos
|
Extend code references with external repos
|
Python
|
apache-2.0
|
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
|
db93242b97eb8733192d38c4b0af0377759fd647
|
pysal/model/access/__init__.py
|
pysal/model/access/__init__.py
|
from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access_log_stream
from access import access
|
from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access
|
Update import for access changes
|
[BUG] Update import for access changes
|
Python
|
bsd-3-clause
|
pysal/pysal,weikang9009/pysal,lanselin/pysal,sjsrey/pysal
|
724335a9719174d3aeb745ed2d4c161507a08bd3
|
pysparkling/fileio/textfile.py
|
pysparkling/fileio/textfile.py
|
from __future__ import absolute_import, unicode_literals
import logging
from io import StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(stream.read().encode(encoding))
self.fs.dump(stream)
return self
|
from __future__ import absolute_import, unicode_literals
import logging
from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(
BytesIO(stream.read().encode(encoding))
)
self.fs.dump(stream)
return self
|
Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
|
Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
|
Python
|
mit
|
giserh/pysparkling
|
1b33866dd7f140efa035dfd32e0a912dfcf60f35
|
utils/kvtable.py
|
utils/kvtable.py
|
'''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
if self.table.contains(self.setting.key == key):
self.table.update({'value': value}, self.setting.key == key)
else:
self.table.insert({'key': key, 'value': value})
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
|
'''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
self.table.upsert({
'key': key,
'value': value
}, self.setting.key == key)
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
|
Use upsert to reduce chance of duplicates
|
Use upsert to reduce chance of duplicates
|
Python
|
mit
|
randomic/antinub-gregbot
|
d7db5b38bd90502575c68d7fd5548cb64cd7447a
|
services/disqus.py
|
services/disqus.py
|
from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'read and write data on your behalf'),
('admin', 'read and write data on your behalf and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
|
from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'access your contact info'),
('write', 'access your contact info and add comments'),
('admin', 'access your contact info, and comments and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
|
Reword the permissions for Disqus
|
Reword the permissions for Disqus
|
Python
|
bsd-3-clause
|
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
|
02ef2f1cb4e1e0bf3696ea68b73d0d9c3b9c8657
|
events/views.py
|
events/views.py
|
from datetime import date
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
return render_to_response('events/event_archive_month.html', {'month': month})
|
from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
previous = month - timedelta(days=15)
next = month + timedelta(days=45)
return render_to_response('events/event_archive_month.html', {
'month': month,
'previous_month': previous,
'next_month': next,
})
|
Add links to previous and next month
|
Add links to previous and next month
|
Python
|
agpl-3.0
|
vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre
|
bf1f62cb7d91458e768ac31c26deb9ff67ff3a1e
|
rcamp/rcamp/settings/auth.py
|
rcamp/rcamp/settings/auth.py
|
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
|
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
|
Change PAM stack back to login
|
Change PAM stack back to login
|
Python
|
mit
|
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
|
a18f948a6b11522425aace5a591b5f622a5534d3
|
payments/forms.py
|
payments/forms.py
|
from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
|
from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
# pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
|
Disable R0924 check on PlanForm
|
Disable R0924 check on PlanForm
This check fails on Django 1.4 but not Django 1.5
|
Python
|
mit
|
crehana/django-stripe-payments,aibon/django-stripe-payments,jawed123/django-stripe-payments,aibon/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,ZeevG/django-stripe-payments,jawed123/django-stripe-payments,grue/django-stripe-payments,boxysean/django-stripe-payments,ZeevG/django-stripe-payments,grue/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,crehana/django-stripe-payments,pinax/django-stripe-payments,boxysean/django-stripe-payments,wahuneke/django-stripe-payments
|
3ede075c812b116629c5f514596669b16c4784df
|
fulltext/backends/__json.py
|
fulltext/backends/__json.py
|
import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types):
text.write(obj)
text.write(u' ')
elif isinstance(obj, integer_types):
text.write(str(obj))
text.write(u' ')
def _get_file(f, **kwargs):
text, obj = StringIO(), json.loads(f.read().decode('utf8'))
_to_text(text, obj)
return text.getvalue()
|
import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types + integer_types):
text.write(u'%s ' % obj)
else:
raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
text, data = StringIO(), f.read()
obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
|
Use format string. Readability. ValueError.
|
Use format string. Readability. ValueError.
|
Python
|
mit
|
btimby/fulltext,btimby/fulltext
|
b6c8921b7281f24f5e8353cd0542d7ca1d18cf37
|
pymemcache/test/test_serde.py
|
pymemcache/test/test_serde.py
|
from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_str(self):
self.check('value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
|
from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
# pymemcache stores values as byte strings, so we immediately the value
# if needed so deserialized works as it would with a real server
if not isinstance(serialized, six.binary_type):
serialized = six.text_type(serialized).encode('ascii')
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_bytes(self):
self.check(b'value')
def test_unicode(self):
self.check(u'value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
|
Use byte strings after serializing with serde
|
Use byte strings after serializing with serde
The pymemcache client will return a byte string, so we'll do the same to test that the deserializer works as expected.
This currently fails with Python 3.
|
Python
|
apache-2.0
|
sontek/pymemcache,ewdurbin/pymemcache,sontek/pymemcache,bwalks/pymemcache,pinterest/pymemcache,pinterest/pymemcache
|
6e583085ac056b7df2b29a94cd6743493c151684
|
subjectivity_clues/clues.py
|
subjectivity_clues/clues.py
|
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
if __name__ == '__main__':
c = Clues()
|
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj': 1
}
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
def calculate(self, sentence):
related_words = 0
total_subjectivity = 0
total_priorpolarity = 0
for w in sentence.split(' '):
if w not in self.lexicons.keys():
continue
related_words += 1
total_subjectivity += self.TYPE[self.lexicons[w]['type']]
total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
return {
'sentence': sentence,
'related_words': related_words,
'total_subjectivity': total_subjectivity,
'total_priorpolarity': total_priorpolarity
}
if __name__ == '__main__':
c = Clues()
|
Add calculation to the lexicon
|
Add calculation to the lexicon
|
Python
|
apache-2.0
|
chuajiesheng/twitter-sentiment-analysis
|
0db4d0f3df3b9541aaf6301c11f83376debb41ff
|
lib/get_version.py
|
lib/get_version.py
|
#!/usr/bin/env python
""" Extracts the version of the khmer project. """
import sys
import pkg_resources
try:
print pkg_resources.get_distribution( # pylint: disable=E1103
'khmer').version
except pkg_resources.DistributionNotFound:
print 'To build the khmer library, the distribution information'
print 'has to be available. Either install the package into your'
print 'development environment or run "setup.py develop" to setup the'
print 'metadata. A virtualenv is recommended!'
sys.exit(1)
del pkg_resources
|
import sys
sys.path.insert(0, '../')
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = '../khmer/_version.py'
versioneer.versionfile_build = '../khmer/_version.py'
versioneer.tag_prefix = 'v' # tags are like v1.2.0
versioneer.parentdir_prefix = '..'
print versioneer.get_version()
|
Use versioneer for ./lib version
|
Use versioneer for ./lib version
- Allows the version to be obtained without khmer being installed.
|
Python
|
bsd-3-clause
|
Winterflower/khmer,kdmurray91/khmer,souravsingh/khmer,souravsingh/khmer,Winterflower/khmer,jas14/khmer,ged-lab/khmer,ged-lab/khmer,Winterflower/khmer,F1000Research/khmer,F1000Research/khmer,jas14/khmer,kdmurray91/khmer,souravsingh/khmer,ged-lab/khmer,kdmurray91/khmer,F1000Research/khmer,jas14/khmer
|
e046bbd4027275a94888bd70138000cdb2da67f3
|
pages/search_indexes.py
|
pages/search_indexes.py
|
"""Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
"""Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
Add a title attribute to the SearchIndex for pages.
|
Add a title attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can display the title of the result without hitting the database to
actually pull the page.
|
Python
|
bsd-3-clause
|
batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1
|
dcc5c7be6f8463f41e1d1697bdba7fd576382259
|
master/rc_force.py
|
master/rc_force.py
|
# Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
|
# Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
|
Add ppc64le tarball rc force builder
|
Add ppc64le tarball rc force builder
|
Python
|
mit
|
staticfloat/julia-buildbot,staticfloat/julia-buildbot
|
f4be8fd80b1aad9babdfbc56dec331af635f5554
|
migrations/versions/0165_another_letter_org.py
|
migrations/versions/0165_another_letter_org.py
|
"""empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
|
"""empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
('503', 'East Riding of Yorkshire Council'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
|
Add East Riding of Yorkshire Council to migration
|
Add East Riding of Yorkshire Council to migration
|
Python
|
mit
|
alphagov/notifications-api,alphagov/notifications-api
|
dc0dfd4a763dceef655d62e8364b92a8073b7751
|
chrome/chromehost.py
|
chrome/chromehost.py
|
#!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
|
#!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
|
Change chromhost to use normal sockets
|
Change chromhost to use normal sockets
|
Python
|
mit
|
CacheBrowser/cachebrowser,NewBie1993/cachebrowser
|
78ca616d611a6c9b8364cf25a21affd80e261ff8
|
cutplanner/planner.py
|
cutplanner/planner.py
|
import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed.reverse
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
|
import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
|
Set up list of needed pieces on init
|
Set up list of needed pieces on init
|
Python
|
mit
|
alanc10n/py-cutplanner
|
131f0d3a67bc6ba995d1f45dd8c85594d8d8e79c
|
tests/run_tests.py
|
tests/run_tests.py
|
"""Python script to run all tests"""
import pytest
if __name__ == '__main__':
pytest.main()
|
"""Python script to run all tests"""
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
|
Allow Jenkins to actually report build failures
|
Allow Jenkins to actually report build failures
|
Python
|
mit
|
gatkin/declxml
|
2d8ddb4ab59bc7198b637bcc9e51914379ff408b
|
tests/test_i18n.py
|
tests/test_i18n.py
|
import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
|
import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
try:
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
assert humanize.ordinal(5) == "5ый"
finally:
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
|
Add i18n test for humanize.ordinal
|
Add i18n test for humanize.ordinal
|
Python
|
mit
|
jmoiron/humanize,jmoiron/humanize
|
8e26fa46ffdb9442254712b4083a973ab9ce6577
|
Python/tangshi.py
|
Python/tangshi.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rstrip()
value, key = line.split(",")
#key = char.decode("utf-8")
#value = rhyme.decode("utf-8")
mydict[key] = value
f = codecs.open("../Data/SamplePoem.txt", "r", "utf-8")
for line in f:
line = line.rstrip()
for key in line:
if ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang"
elif qu.match(mydict[key]):
print key + " = " + " Qu"
elif ru.match(mydict[key]):
print key + " = " + " Ru"
else:
print key + " = " + " *"
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rstrip()
value, key = line.split(",")
#key = char.decode("utf-8")
#value = rhyme.decode("utf-8")
mydict[key] = value
f = codecs.open("../Data/SamplePoem.txt", "r", "utf-8")
for line in f:
line = line.rstrip()
for key in line:
if key not in mydict:
print key
elif ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang"
elif qu.match(mydict[key]):
print key + " = " + " Qu"
elif ru.match(mydict[key]):
print key + " = " + " Ru"
else:
print key + " = " + " *"
|
Print the character without Rhyme if it is not on the Rhyme Dictionary
|
Print the character without Rhyme if it is not on the Rhyme Dictionary
|
Python
|
apache-2.0
|
jmworsley/TangShi
|
a8f3491811bb639ebb59f79c55f461ae063b06b8
|
api/base/urls.py
|
api/base/urls.py
|
from django.conf import settings
from django.conf.urls import include, url
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^$', views.root),
url(r'^nodes/', include('api.nodes.urls', namespace='nodes')),
url(r'^users/', include('api.users.urls', namespace='users')),
url(r'^docs/', include('rest_framework_swagger.urls')),
] + static('/static/', document_root=settings.STATIC_ROOT)
|
from django.conf import settings
from django.conf.urls import include, url, patterns
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^v2/', include(patterns('',
url(r'^$', views.root),
url(r'^nodes/', include('api.nodes.urls', namespace='nodes')),
url(r'^users/', include('api.users.urls', namespace='users')),
url(r'^docs/', include('rest_framework_swagger.urls')),
)))] + static('/static/', document_root=settings.STATIC_ROOT)
|
Change API url prefix to 'v2'
|
Change API url prefix to 'v2'
|
Python
|
apache-2.0
|
TomBaxter/osf.io,cwisecarver/osf.io,pattisdr/osf.io,wearpants/osf.io,caseyrygt/osf.io,sbt9uc/osf.io,jmcarp/osf.io,adlius/osf.io,adlius/osf.io,GageGaskins/osf.io,dplorimer/osf,reinaH/osf.io,abought/osf.io,TomHeatwole/osf.io,petermalcolm/osf.io,hmoco/osf.io,pattisdr/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,acshi/osf.io,mattclark/osf.io,cldershem/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,samchrisinger/osf.io,samanehsan/osf.io,SSJohns/osf.io,Ghalko/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,sloria/osf.io,KAsante95/osf.io,mattclark/osf.io,danielneis/osf.io,crcresearch/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,kch8qx/osf.io,abought/osf.io,icereval/osf.io,samchrisinger/osf.io,amyshi188/osf.io,jeffreyliu3230/osf.io,leb2dg/osf.io,danielneis/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,caneruguz/osf.io,alexschiller/osf.io,saradbowman/osf.io,pattisdr/osf.io,jolene-esposito/osf.io,brianjgeiger/osf.io,brandonPurvis/osf.io,dplorimer/osf,reinaH/osf.io,jolene-esposito/osf.io,sloria/osf.io,barbour-em/osf.io,caneruguz/osf.io,samanehsan/osf.io,lyndsysimon/osf.io,jeffreyliu3230/osf.io,petermalcolm/osf.io,caseyrygt/osf.io,caseyrygt/osf.io,wearpants/osf.io,asanfilippo7/osf.io,Ghalko/osf.io,jolene-esposito/osf.io,TomBaxter/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,chennan47/osf.io,wearpants/osf.io,barbour-em/osf.io,SSJohns/osf.io,mluke93/osf.io,alexschiller/osf.io,caneruguz/osf.io,baylee-d/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,kch8qx/osf.io,mluke93/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,ZobairAlijan/osf.io,cosenal/osf.io,jinluyuan/osf.io,zamattiac/osf.io,fabianvf/osf.io,TomBaxter/osf.io,saradbowman/osf.io,laurenrevere/osf.io,hmoco/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,icereval/osf.io,jnayak1/osf.io,GageGaskins/osf.io,doublebits/osf.io,asanfilippo7/osf.io,sloria/osf.io,mfraezz/osf.io,jnayak1/osf.io,crcresearch/osf.io,acshi/osf.io,Ghalko/osf.io,Johnetordoff/osf.io,MerlinZhang/osf.io,cwisecarver/osf.io,cslzchen/osf.io,cldershem/osf.io,mluke93/osf.io,doublebits/osf.io,HarryRybacki/osf.io,njantrania/osf.io,SSJohns/osf.io,ckc6cz/osf.io,bdyetton/prettychart,bdyetton/prettychart,bdyetton/prettychart,CenterForOpenScience/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,lyndsysimon/osf.io,caneruguz/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,ckc6cz/osf.io,doublebits/osf.io,cslzchen/osf.io,brandonPurvis/osf.io,TomHeatwole/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,njantrania/osf.io,zachjanicki/osf.io,danielneis/osf.io,abought/osf.io,doublebits/osf.io,reinaH/osf.io,hmoco/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,cldershem/osf.io,billyhunt/osf.io,laurenrevere/osf.io,acshi/osf.io,doublebits/osf.io,njantrania/osf.io,asanfilippo7/osf.io,MerlinZhang/osf.io,DanielSBrown/osf.io,caseyrygt/osf.io,KAsante95/osf.io,felliott/osf.io,HarryRybacki/osf.io,brandonPurvis/osf.io,Nesiehr/osf.io,hmoco/osf.io,barbour-em/osf.io,zamattiac/osf.io,mluo613/osf.io,petermalcolm/osf.io,lyndsysimon/osf.io,zachjanicki/osf.io,binoculars/osf.io,mluke93/osf.io,ticklemepierce/osf.io,ZobairAlijan/osf.io,Johnetordoff/osf.io,billyhunt/osf.io,rdhyee/osf.io,mfraezz/osf.io,baylee-d/osf.io,Nesiehr/osf.io,emetsger/osf.io,jmcarp/osf.io,caseyrollins/osf.io,KAsante95/osf.io,mattclark/osf.io,zamattiac/osf.io,cosenal/osf.io,jnayak1/osf.io,emetsger/osf.io,rdhyee/osf.io,SSJohns/osf.io,mluo613/osf.io,binoculars/osf.io,ZobairAlijan/osf.io,jeffreyliu3230/osf.io,dplorimer/osf,brianjgeiger/osf.io,felliott/osf.io,DanielSBrown/osf.io,samchrisinger/osf.io,emetsger/osf.io,billyhunt/osf.io,barbour-em/osf.io,jinluyuan/osf.io,ckc6cz/osf.io,samchrisinger/osf.io,petermalcolm/osf.io,amyshi188/osf.io,erinspace/osf.io,adlius/osf.io,leb2dg/osf.io,haoyuchen1992/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,sbt9uc/osf.io,dplorimer/osf,cosenal/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,RomanZWang/osf.io,arpitar/osf.io,abought/osf.io,monikagrabowska/osf.io,samanehsan/osf.io,haoyuchen1992/osf.io,acshi/osf.io,arpitar/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,erinspace/osf.io,ticklemepierce/osf.io,adlius/osf.io,cosenal/osf.io,caseyrollins/osf.io,acshi/osf.io,erinspace/osf.io,jinluyuan/osf.io,cslzchen/osf.io,kwierman/osf.io,jolene-esposito/osf.io,samanehsan/osf.io,baylee-d/osf.io,mfraezz/osf.io,jmcarp/osf.io,KAsante95/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,felliott/osf.io,kch8qx/osf.io,danielneis/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,felliott/osf.io,leb2dg/osf.io,kch8qx/osf.io,chrisseto/osf.io,mluo613/osf.io,icereval/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,arpitar/osf.io,kwierman/osf.io,amyshi188/osf.io,cldershem/osf.io,HarryRybacki/osf.io,chennan47/osf.io,GageGaskins/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,MerlinZhang/osf.io,leb2dg/osf.io,njantrania/osf.io,monikagrabowska/osf.io,haoyuchen1992/osf.io,jmcarp/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,fabianvf/osf.io,fabianvf/osf.io,mfraezz/osf.io,laurenrevere/osf.io,arpitar/osf.io,zachjanicki/osf.io,emetsger/osf.io,bdyetton/prettychart,ckc6cz/osf.io,RomanZWang/osf.io,lyndsysimon/osf.io,KAsante95/osf.io,wearpants/osf.io,kwierman/osf.io,rdhyee/osf.io,reinaH/osf.io,fabianvf/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,mluo613/osf.io,TomHeatwole/osf.io,jinluyuan/osf.io,alexschiller/osf.io,chennan47/osf.io,rdhyee/osf.io,alexschiller/osf.io,RomanZWang/osf.io,sbt9uc/osf.io,chrisseto/osf.io
|
fb7754f15a8f0803c5417782e87d6fe153bf6d20
|
migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py
|
migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py
|
"""Added end_date to full text index events
Revision ID: 573faf4ac644
Revises: 342fa3076650
Create Date: 2015-03-06 17:26:54.718493
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
|
"""Added end_date to full text index events
Revision ID: 573faf4ac644
Revises: 342fa3076650
Create Date: 2015-03-06 17:26:54.718493
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_column('event_index', 'start_date', nullable=False, schema='events')
op.create_index('ix_events_event_index_start_date', 'event_index', ['start_date'], schema='events')
op.add_column('event_index',
sa.Column('end_date', sa.DateTime(), nullable=False, server_default='now()'),
schema='events')
op.alter_column('event_index', 'end_date', server_default=None, schema='events')
op.create_index('ix_events_event_index_end_date', 'event_index', ['end_date'], schema='events')
def downgrade():
op.alter_column('event_index', 'start_date', nullable=True, schema='events')
op.drop_index('ix_events_event_index_start_date', table_name='event_index', schema='events')
op.drop_column('event_index', 'end_date', schema='events')
|
Use index name matching the current naming schema
|
Use index name matching the current naming schema
|
Python
|
mit
|
OmeGak/indico,mvidalgarcia/indico,pferreir/indico,indico/indico,DirkHoffmann/indico,indico/indico,mic4ael/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,OmeGak/indico,DirkHoffmann/indico,mvidalgarcia/indico,DirkHoffmann/indico,mic4ael/indico,ThiefMaster/indico,mic4ael/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico
|
029a159fe3f920d59e0168af72177b343daa4256
|
phased/__init__.py
|
phased/__init__.py
|
from django.conf import settings
def generate_secret_delimiter():
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
|
from django.conf import settings
from django.utils.hashcompat import sha_constructor
def generate_secret_delimiter():
return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
|
Make use of Django's hashcompat module.
|
Make use of Django's hashcompat module.
|
Python
|
bsd-3-clause
|
OmarIthawi/django-phased,mab2k/django-phased,mab2k/django-phased,codysoyland/django-phased,OmarIthawi/django-phased
|
c5a7feb3000bb3e234a3b87e8b20262eb9b94dfe
|
books/models.py
|
books/models.py
|
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
|
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
class DebtLoan(models.Model):
DEBT = 0
LOAN = 1
CATEGORY_CHOICES = (
(DEBT, 'debt'),
(LOAN, 'loan'),
)
with_who = fields.CharField(max_length=255)
title = fields.CharField(max_length=255, null=True, blank=True)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
if self.title:
return "{}: {}".format(self.with_who, self.title)
else:
return "{}".format(self.with_who)
|
Create new model for debts and loans
|
Create new model for debts and loans
|
Python
|
mit
|
trimailov/finance,trimailov/finance,trimailov/finance
|
39c0dfd7821355c9d2ff2274f4dd6292e959ed87
|
pronto/__init__.py
|
pronto/__init__.py
|
# coding: utf-8
"""
**pronto**: a Python frontend to ontologies
===========================================
"""
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .parser import Parser
except ImportError:
pass
|
# coding: utf-8
"""
**pronto**: a Python frontend to ontologies
===========================================
"""
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
|
Remove Parser from __all__ (from pronto import *)
|
Remove Parser from __all__ (from pronto import *)
|
Python
|
mit
|
althonos/pronto
|
feefc687473b80adf30079e3ca23384459bb1558
|
protractor/test.py
|
protractor/test.py
|
# -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f)
cls.webdriver = subprocess.Popen(
['webdriver-manager', 'start'], stdout=f, stderr=f)
@classmethod
def tearDownClass(cls):
cls.webdriver.kill()
super(ProtractorTestCaseMixin, cls).tearDownClass()
def test_run(self):
protractor_command = 'protractor {}'.format(self.protractor_conf)
if self.specs:
protractor_command += ' --specs {}'.format(','.join(self.specs))
if self.suite:
protractor_command += ' --suite {}'.format(self.suite)
return_code = subprocess.call(protractor_command.split())
self.assertEqual(return_code, 0)
|
# -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f)
cls.webdriver = subprocess.Popen(
['webdriver-manager', 'start'], stdout=f, stderr=f)
@classmethod
def tearDownClass(cls):
cls.webdriver.kill()
super(ProtractorTestCaseMixin, cls).tearDownClass()
def test_run(self):
protractor_command = 'protractor {}'.format(self.protractor_conf)
if self.specs:
protractor_command += ' --specs {}'.format(','.join(self.specs))
if self.suite:
protractor_command += ' --suite {}'.format(self.suite)
protractor_command += ' --params.live_server_url={}'.format(self.live_server_url)
return_code = subprocess.call(protractor_command.split())
self.assertEqual(return_code, 0)
|
Update to pass live server url as param to protractor
|
Update to pass live server url as param to protractor
|
Python
|
mit
|
penguin359/django-protractor,jpulec/django-protractor
|
e78dd9bf1b9e1d20b8df34ee3328ee08afd45676
|
contrib/migrateticketmodel.py
|
contrib/migrateticketmodel.py
|
#!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more meaningful new defaults.
#
# Make sure to make a backup of the Trac environment before running this!
import sys
from trac.env import open_environment
from trac.ticket.model import Priority, Severity
priority_mapping = {
'highest': 'blocker',
'high': 'critical',
'normal': 'major',
'low': 'minor',
'lowest': 'trivial'
}
def main():
if len(sys.argv) < 2:
print >> sys.stderr, 'usage: %s /path/to/projenv' \
% os.path.basename(sys.argv[0])
sys.exit(2)
env = open_environment(sys.argv[1])
db = env.get_db_cnx()
for oldprio, newprio in priority_mapping.items():
priority = Priority(env, oldprio, db)
priority.name = newprio
priority.update(db)
for severity in list(Severity.select(env, db)):
severity.delete(db)
db.commit()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more meaningful new defaults.
#
# Make sure to make a backup of the Trac environment before running this!
import os
import sys
from trac.env import open_environment
from trac.ticket.model import Priority, Severity
priority_mapping = {
'highest': 'blocker',
'high': 'critical',
'normal': 'major',
'low': 'minor',
'lowest': 'trivial'
}
def main():
if len(sys.argv) < 2:
print >> sys.stderr, 'usage: %s /path/to/projenv' \
% os.path.basename(sys.argv[0])
sys.exit(2)
env = open_environment(sys.argv[1])
db = env.get_db_cnx()
for oldprio, newprio in priority_mapping.items():
priority = Priority(env, oldprio, db)
priority.name = newprio
priority.update(db)
for severity in list(Severity.select(env, db)):
severity.delete(db)
db.commit()
if __name__ == '__main__':
main()
|
Fix missing import in contrib script added in [2630].
|
Fix missing import in contrib script added in [2630].
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@2631 af82e41b-90c4-0310-8c96-b1721e28e2e2
|
Python
|
bsd-3-clause
|
netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac
|
8974dc36e6ea0ab7b5ce3c78e9827d41cf1abcec
|
appengine_config.py
|
appengine_config.py
|
"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if '/diff/' in path:
return '/X/diff/...'
if '/diff2/' in path:
return '/X/diff2/...'
if '/patch/' in path:
return '/X/patch/...'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Segregate Appstats by runtime (python vs. python27).
appstats_KEY_NAMESPACE = '__appstats_%s__' % os.getenv('APPENGINE_RUNTIME')
# Django 1.2+ requires DJANGO_SETTINGS_MODULE environment variable to be set
# http://code.google.com/appengine/docs/python/tools/libraries.html#Django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
# NOTE: All "main" scripts must import webapp.template before django.
|
"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if '/diff/' in path:
return '/X/diff/...'
if '/diff2/' in path:
return '/X/diff2/...'
if '/patch/' in path:
return '/X/patch/...'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Segregate Appstats by runtime (python vs. python27).
appstats_KEY_NAMESPACE = '__appstats_%s__' % os.getenv('APPENGINE_RUNTIME')
# Enable Interactive Playground.
appstats_SHELL_OK = True
# Django 1.2+ requires DJANGO_SETTINGS_MODULE environment variable to be set
# http://code.google.com/appengine/docs/python/tools/libraries.html#Django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
# NOTE: All "main" scripts must import webapp.template before django.
|
Enable the Appstats Interactive Playground.
|
Enable the Appstats Interactive Playground.
|
Python
|
apache-2.0
|
Koulio/rietveld,gco/rietveld,andyzsf/rietveld,google-code-export/rietveld,kscharding/integral-solutions-smxq,rietveld-codereview/rietveld,google-code-export/rietveld,v3ss0n/rietveld,ericmckean/rietveld,openlabs/cr.openlabs.co.in,aungzanbaw/rietveld,robfig/rietveld,Koulio/rietveld,arg0/rietveld,sajingeo/rietveld,openlabs/cr.openlabs.co.in,sajingeo/rietveld,supriyantomaftuh/rietveld,xtypebee/rietveld,DeanHere/rietveld,Koulio/rietveld,google-code-export/rietveld,gavioto/rietveld,ericmckean/rietveld,salomon1184/rietveld,dushmis/rietveld,draem0507/rietveld,gco/rietveld,foolonhill/rietveld,DeanHere/rietveld,andyzsf/rietveld,dushmis/rietveld,supriyantomaftuh/rietveld,dushmis/rietveld,openlabs/cr.openlabs.co.in,sajingeo/rietveld,ericmckean/rietveld,DeanHere/rietveld,robfig/rietveld,robfig/rietveld,salomon1184/rietveld,foolonhill/rietveld,v3ss0n/rietveld,salomon1184/rietveld,aungzanbaw/rietveld,fuzan/rietveld,fuzan/rietveld,fuzan/rietveld,rietveld-codereview/rietveld,aungzanbaw/rietveld,gco/rietveld,rietveld-codereview/rietveld,xtypebee/rietveld,kscharding/integral-solutions-smxq,berkus/rietveld,gavioto/rietveld,foolonhill/rietveld,berkus/rietveld,berkus/rietveld,v3ss0n/rietveld,andyzsf/rietveld,xtypebee/rietveld,arg0/rietveld,rietveld-codereview/rietveld,draem0507/rietveld,arg0/rietveld,supriyantomaftuh/rietveld,kscharding/integral-solutions-smxq,gavioto/rietveld,draem0507/rietveld
|
176c03e26f46bad73df39c11ea4a190baca6fe54
|
apps/authentication/tests.py
|
apps/authentication/tests.py
|
from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPELINE
pipeline_settings['PIPELINE_ENABLED'] = False
with override_settings(PIPELINE_SETTINGS=pipeline_settings):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(200, response.status_code, 'Expect root view to load without issues.')
|
Make test not depend on django-pipeline
|
Make test not depend on django-pipeline
|
Python
|
mit
|
microserv/microauth,microserv/microauth,microserv/microauth
|
b501ee5dc2a41bf51f9f91c29501792338bf7269
|
automatron/backend/controller.py
|
automatron/backend/controller.py
|
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
def proxy(*args):
self.plugins.emit(IAutomatronClientActions[item], *args)
return proxy
|
from functools import partial
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.plugins = None
def prepareService(self):
# Load plugins
self.plugins = PluginManager(self)
def __getattr__(self, item):
return partial(self.plugins.emit, IAutomatronClientActions[item])
|
Use functools.partial for client action proxy.
|
Use functools.partial for client action proxy.
|
Python
|
mit
|
automatron/automatron
|
7925afd27ead247a017baf7a7dff97986904055f
|
comics/views.py
|
comics/views.py
|
from django.views import generic
from gallery.models import GalleryImage
from gallery import queries
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
template_name = "comics/issue.html"
def get_queryset(self):
query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug"))
return query_set
class ComicPageView(generic.DetailView):
model = GalleryImage
template_name = "comics/comic_page.html"
def __init__(self):
super().__init__()
self.issue = None
def get_queryset(self):
# Find Issue, then get gallery
self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get(
slug=self.kwargs.get("issue_slug")
)
query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id)
return query_set
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["issue"] = self.issue # Set in get_queryset()
context["next"] = queries.get_next_image(
self.issue.gallery, self.object.sort_order
)
context["previous"] = queries.get_previous_image(
self.issue.gallery, self.object.sort_order
)
return context
|
from django.views import generic
from gallery.models import GalleryImage
from gallery import queries
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
template_name = "comics/issue.html"
def get_queryset(self):
query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug"))
return query_set
class ComicPageView(generic.DetailView):
model = GalleryImage
template_name = "comics/comic_page.html"
def __init__(self):
super().__init__()
self.issue = None
def get_queryset(self):
# Find Issue, then get gallery
self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get(
slug=self.kwargs.get("issue_slug")
)
query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id)
return query_set
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["issue"] = self.issue # Set in get_queryset()
gallery = self.issue.gallery
sort_order = self.object.sort_order
context["next"] = queries.get_next_image(gallery, sort_order)
context["previous"] = queries.get_previous_image(gallery, sort_order)
return context
|
Make it look nicer, possibly micro seconds faster
|
Make it look nicer, possibly micro seconds faster
|
Python
|
mit
|
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
|
04416cd9652a9fdc3ab58664ab4b96cbaff3f698
|
simuvex/s_event.py
|
simuvex/s_event.py
|
import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_addr = state.scratch.ins_addr
self.bbl_addr = state.scratch.bbl_addr
self.stmt_idx = state.scratch.stmt_idx
self.sim_procedure = state.scratch.sim_procedure.__class__
self.objects = dict(kwargs)
def __repr__(self):
return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys())
def _copy_event(self):
c = self.__class__.__new__(self.__class__)
c.id = self.id
c.type = self.type
c.bbl_addr = self.bbl_addr
c.stmt_idx = self.stmt_idx
c.sim_procedure = self.sim_procedure
c.objects = dict(self.objects)
return c
|
import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_addr = state.scratch.ins_addr
self.bbl_addr = state.scratch.bbl_addr
self.stmt_idx = state.scratch.stmt_idx
self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__
self.objects = dict(kwargs)
def __repr__(self):
return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys())
def _copy_event(self):
c = self.__class__.__new__(self.__class__)
c.id = self.id
c.type = self.type
c.bbl_addr = self.bbl_addr
c.stmt_idx = self.stmt_idx
c.sim_procedure = self.sim_procedure
c.objects = dict(self.objects)
return c
|
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
|
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
|
Python
|
bsd-2-clause
|
axt/angr,schieb/angr,angr/angr,tyb0807/angr,f-prettyland/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,f-prettyland/angr,angr/angr,axt/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,chubbymaggie/angr,angr/simuvex,schieb/angr,iamahuman/angr,axt/angr,angr/angr,f-prettyland/angr,schieb/angr
|
b1c1b28e58b59eac81954fb55570dfd389b99c0f
|
tests/acceptance/test_modify.py
|
tests/acceptance/test_modify.py
|
import datetime
from nose.tools import assert_raises
from scalymongo import Document
from scalymongo.errors import ModifyFailedError
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
class ModifyableDocument(Document):
__collection__ = __name__
__database__ = 'test'
structure = {
'field': basestring,
}
class WhenModifyingDocumentAndPreconditionFails(BaseAcceptanceTest):
def should_raise_ModifyFailedError(self):
doc = self.connection.models.ModifyableDocument({'field': 'foo'})
doc.save()
assert_raises(
ModifyFailedError,
doc.modify,
{'field': 'not the correct value'},
{'$set': {'field': 'new value'}},
)
|
import datetime
from nose.tools import assert_raises
from scalymongo import Document
from scalymongo.errors import ModifyFailedError
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
class BlogPostModifyExample(Document):
__collection__ = __name__
__database__ = 'test'
structure = {
'author': basestring,
'title': basestring,
'body': basestring,
'views': int,
'comments': [{
'author': basestring,
'comment': basestring,
'rank': int,
}],
}
default_values = {
'views': 0,
}
EXAMPLE_POST = {
'author': 'Alice',
'title': 'Writing Scalable Services with Python and MongoDB',
'body': 'Use ScalyMongo!',
}
class BlogPostTestCase(BaseAcceptanceTest):
def setup(self):
self.doc = self.connection.models.BlogPostModifyExample(EXAMPLE_POST)
self.doc.save()
def teardown(self):
self.connection.models.BlogPostModifyExample.collection.drop()
def is_document_up_to_date(self):
"""True if and only if ``self.doc`` reflects what's in the database."""
fresh_copy = self.connection.models.BlogPostModifyExample.find_one(
self.doc.shard_key)
return self.doc == fresh_copy
def when_no_precondition_given_should_increment(self):
self.doc.modify({'$inc': {'views': 1}})
assert self.doc.views == 1
self.doc.modify({'$inc': {'views': 5}})
assert self.doc.views == 6
assert self.is_document_up_to_date()
def when_precondition_fails_should_raise_ModifyFailedError(self):
assert_raises(
ModifyFailedError,
self.doc.modify,
{'$set': {'author': 'Bob'}},
{'author': 'Not Alice'},
)
# The doc should not have been altered.
assert self.doc.author == 'Alice'
assert self.is_document_up_to_date()
def when_precondition_passes_should_update_field(self):
self.doc.modify(
{'$set': {'views': 15}},
{'author': 'Alice'},
)
assert self.is_document_up_to_date()
|
Add more comprehensive testing of `modify`
|
acceptance: Add more comprehensive testing of `modify`
|
Python
|
bsd-3-clause
|
allancaffee/scaly-mongo
|
445a150982f2119b340d95edc66940e0ec54afbd
|
lib/ansiblelint/rules/NoFormattingInWhenRule.py
|
lib/ansiblelint/rules/NoFormattingInWhenRule.py
|
from ansiblelint import AnsibleLintRule
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']
def _is_valid(self, when):
if not isinstance(when, (str, unicode)):
return True
return when.find('{{') == -1 and when.find('}}') == -1
def matchplay(self, file, play):
errors = []
if isinstance(play, dict):
if 'roles' not in play:
return errors
for role in play['roles']:
if self.matchtask(file, role):
errors.append(({'when': role},
'role "when" clause has Jinja2 templates'))
if isinstance(play, list):
for play_item in play:
sub_errors = self.matchplay(file, play_item)
if sub_errors:
errors = errors + sub_errors
return errors
def matchtask(self, file, task):
return 'when' in task and not self._is_valid(task['when'])
|
from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']
def _is_valid(self, when):
if not isinstance(when, StringTypes):
return True
return when.find('{{') == -1 and when.find('}}') == -1
def matchplay(self, file, play):
errors = []
if isinstance(play, dict):
if 'roles' not in play:
return errors
for role in play['roles']:
if self.matchtask(file, role):
errors.append(({'when': role},
'role "when" clause has Jinja2 templates'))
if isinstance(play, list):
for play_item in play:
sub_errors = self.matchplay(file, play_item)
if sub_errors:
errors = errors + sub_errors
return errors
def matchtask(self, file, task):
return 'when' in task and not self._is_valid(task['when'])
|
Fix Python3 unicode test error
|
Fix Python3 unicode test error
|
Python
|
mit
|
willthames/ansible-lint,dataxu/ansible-lint,MatrixCrawler/ansible-lint
|
0e48b2130cc53caa9beb9a5f8ce09edbcc40f1b8
|
ggplotx/tests/test_geom_point.py
|
ggplotx/tests/test_geom_point.py
|
from __future__ import absolute_import, division, print_function
import pandas as pd
from ggplotx import ggplot, aes, geom_point
def test_aesthetics():
df = pd.DataFrame({
'a': range(5),
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9
})
p = (ggplot(df, aes(y='a')) +
geom_point(aes(x='b')) +
geom_point(aes(x='c', size='a')) +
geom_point(aes(x='d', alpha='a'),
size=10, show_legend=False) +
geom_point(aes(x='e', shape='factor(a)'),
size=10, show_legend=False) +
geom_point(aes(x='f', color='factor(a)'),
size=10, show_legend=False) +
geom_point(aes(x='g', fill='a'), stroke=0,
size=10, show_legend=False) +
geom_point(aes(x='h', stroke='a'), fill='white',
color='green', size=10) +
geom_point(aes(x='i', shape='factor(a)'),
fill='brown', stroke=2, size=10, show_legend=False))
assert p == 'aesthetics'
|
from __future__ import absolute_import, division, print_function
import pandas as pd
from ggplotx import ggplot, aes, geom_point, theme
def test_aesthetics():
df = pd.DataFrame({
'a': range(5),
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9
})
p = (ggplot(df, aes(y='a')) +
geom_point(aes(x='b')) +
geom_point(aes(x='c', size='a')) +
geom_point(aes(x='d', alpha='a'),
size=10, show_legend=False) +
geom_point(aes(x='e', shape='factor(a)'),
size=10, show_legend=False) +
geom_point(aes(x='f', color='factor(a)'),
size=10, show_legend=False) +
geom_point(aes(x='g', fill='a'), stroke=0,
size=10, show_legend=False) +
geom_point(aes(x='h', stroke='a'), fill='white',
color='green', size=10) +
geom_point(aes(x='i', shape='factor(a)'),
fill='brown', stroke=2, size=10, show_legend=False) +
theme(facet_spacing={'right': 0.85}))
assert p == 'aesthetics'
|
Add space on the RHS of geom_point test
|
Add space on the RHS of geom_point test
|
Python
|
mit
|
has2k1/plotnine,has2k1/plotnine
|
614a996dd8227808e796a369ed0faf1f9427f780
|
organizer/views.py
|
organizer/views.py
|
from django.http.response import HttpResponse
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
html_output = "<html>\n"
html_output += "<head>\n"
html_output += " <title>"
html_output += "Don't Do This!</title>\n"
html_output += "</head>\n"
html_output += "<body>\n"
html_output += " <ul>\n"
for tag in tag_list:
html_output += " <li>"
html_output += tag.name.title()
html_output += "</li>\n"
html_output += " </ul>\n"
html_output += "</body>\n"
html_output += "</html>\n"
return HttpResponse(html_output)
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
|
Use template in homepage view.
|
Ch04: Use template in homepage view.
|
Python
|
bsd-2-clause
|
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
|
7a24f314c426e55735836dd2f805d9e0364dc871
|
tarbell/hooks.py
|
tarbell/hooks.py
|
# -*- coding: utf-8 -*-
hooks = {
'newproject': [], # (site)
'generate': [], # (site, dir, extra_context)
'publish': [], # (site, s3)
'install': [], # (site, project)
'preview': [], # (site)
'server_start': [], # (site)
'server_stop': [], # (site)
}
class register_hook(object):
"""
Register hook with @register_hook("EVENT") where EVENT is "newproject" etc.
"""
def __init__(self, event):
self.event = event
def __call__(self, f):
# Avoid weird duplication
names = ['{0}.{1}'.format(func.__module__, func.func_name) for func in hooks[self.event]]
if '{0}.{1}'.format(f.__module__, f.func_name) not in names:
hooks[self.event].append(f)
return f
|
# -*- coding: utf-8 -*-
hooks = {
'newproject': [], # (site)
'generate': [], # (site, dir, extra_context)
'publish': [], # (site, s3)
'install': [], # (site, project)
'preview': [], # (site)
'server_start': [], # (site)
'server_stop': [], # (site)
}
class register_hook(object):
"""
Register hook with @register_hook("EVENT") where EVENT is "newproject" etc.
"""
def __init__(self, event):
self.event = event
def __call__(self, f):
# Avoid weird duplication
names = ['{0}.{1}'.format(func.__module__, func.__name__) for func in hooks[self.event]]
if '{0}.{1}'.format(f.__module__, f.__name__) not in names:
hooks[self.event].append(f)
return f
|
Switch to Python 3-friendly `function.__name__`
|
Switch to Python 3-friendly `function.__name__`
|
Python
|
bsd-3-clause
|
tarbell-project/tarbell,eyeseast/tarbell,tarbell-project/tarbell,eyeseast/tarbell
|
e08395a35c37fa7f7c0311cc4c7a71537b8b4227
|
tests/misc/print_exception.py
|
tests/misc/print_exception.py
|
try:
import uio as io
except ImportError:
import io
import sys
if hasattr(sys, 'print_exception'):
print_exception = sys.print_exception
else:
import traceback
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
def print_exc(e):
buf = io.StringIO()
print_exception(e, buf)
s = buf.getvalue()
for l in s.split("\n"):
# uPy on pyboard prints <stdin> as file, so remove filename.
if l.startswith(" File "):
l = l.split('"')
print(l[0], l[2])
# uPy and CPy tracebacks differ in that CPy prints a source line for
# each traceback entry. In this case, we know that offending line
# has 4-space indent, so filter it out.
elif not l.startswith(" "):
print(l)
# basic exception message
try:
1/0
except Exception as e:
print('caught')
print_exc(e)
# exception message with more than 1 source-code line
def f():
g()
def g():
2/0
try:
f()
except Exception as e:
print('caught')
print_exc(e)
|
try:
import uio as io
except ImportError:
import io
import sys
if hasattr(sys, 'print_exception'):
print_exception = sys.print_exception
else:
import traceback
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
def print_exc(e):
buf = io.StringIO()
print_exception(e, buf)
s = buf.getvalue()
for l in s.split("\n"):
# uPy on pyboard prints <stdin> as file, so remove filename.
if l.startswith(" File "):
l = l.split('"')
print(l[0], l[2])
# uPy and CPy tracebacks differ in that CPy prints a source line for
# each traceback entry. In this case, we know that offending line
# has 4-space indent, so filter it out.
elif not l.startswith(" "):
print(l)
# basic exception message
try:
1/0
except Exception as e:
print('caught')
print_exc(e)
# exception message with more than 1 source-code line
def f():
g()
def g():
2/0
try:
f()
except Exception as e:
print('caught')
print_exc(e)
# Here we have a function with lots of bytecode generated for a single source-line, and
# there is an error right at the end of the bytecode. It should report the correct line.
def f():
f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X})
return 1
try:
f()
except Exception as e:
print_exc(e)
|
Add test for line number printing with large bytecode chunk.
|
tests/misc: Add test for line number printing with large bytecode chunk.
|
Python
|
mit
|
henriknelson/micropython,AriZuu/micropython,AriZuu/micropython,micropython/micropython-esp32,micropython/micropython-esp32,PappaPeppar/micropython,MrSurly/micropython,MrSurly/micropython-esp32,infinnovation/micropython,trezor/micropython,micropython/micropython-esp32,lowRISC/micropython,torwag/micropython,PappaPeppar/micropython,swegener/micropython,MrSurly/micropython,Peetz0r/micropython-esp32,TDAbboud/micropython,hiway/micropython,kerneltask/micropython,cwyark/micropython,adafruit/micropython,trezor/micropython,adafruit/micropython,bvernoux/micropython,henriknelson/micropython,pramasoul/micropython,kerneltask/micropython,MrSurly/micropython-esp32,trezor/micropython,cwyark/micropython,torwag/micropython,hiway/micropython,adafruit/circuitpython,cwyark/micropython,tobbad/micropython,MrSurly/micropython,adafruit/circuitpython,henriknelson/micropython,MrSurly/micropython-esp32,pramasoul/micropython,tralamazza/micropython,pozetroninc/micropython,deshipu/micropython,cwyark/micropython,chrisdearman/micropython,adafruit/circuitpython,HenrikSolver/micropython,hiway/micropython,oopy/micropython,henriknelson/micropython,ryannathans/micropython,dmazzella/micropython,swegener/micropython,pramasoul/micropython,adafruit/circuitpython,pozetroninc/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,toolmacher/micropython,ryannathans/micropython,alex-robbins/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,chrisdearman/micropython,oopy/micropython,selste/micropython,pozetroninc/micropython,infinnovation/micropython,selste/micropython,pfalcon/micropython,puuu/micropython,SHA2017-badge/micropython-esp32,tralamazza/micropython,Peetz0r/micropython-esp32,Peetz0r/micropython-esp32,dmazzella/micropython,puuu/micropython,pfalcon/micropython,tobbad/micropython,chrisdearman/micropython,lowRISC/micropython,oopy/micropython,PappaPeppar/micropython,hiway/micropython,pfalcon/micropython,alex-robbins/micropython,cwyark/micropython,AriZuu/micropython,SHA2017-badge/micropython-esp32,TDAbboud/micropython,HenrikSolver/micropython,swegener/micropython,Peetz0r/micropython-esp32,MrSurly/micropython,torwag/micropython,alex-robbins/micropython,blazewicz/micropython,kerneltask/micropython,torwag/micropython,chrisdearman/micropython,trezor/micropython,alex-robbins/micropython,MrSurly/micropython-esp32,blazewicz/micropython,lowRISC/micropython,bvernoux/micropython,dmazzella/micropython,ryannathans/micropython,puuu/micropython,tobbad/micropython,ryannathans/micropython,pramasoul/micropython,AriZuu/micropython,Timmenem/micropython,blazewicz/micropython,bvernoux/micropython,tralamazza/micropython,MrSurly/micropython,swegener/micropython,blazewicz/micropython,deshipu/micropython,deshipu/micropython,trezor/micropython,selste/micropython,puuu/micropython,hiway/micropython,tralamazza/micropython,puuu/micropython,infinnovation/micropython,TDAbboud/micropython,TDAbboud/micropython,henriknelson/micropython,toolmacher/micropython,TDAbboud/micropython,selste/micropython,Timmenem/micropython,alex-robbins/micropython,pfalcon/micropython,oopy/micropython,AriZuu/micropython,lowRISC/micropython,pozetroninc/micropython,pramasoul/micropython,lowRISC/micropython,torwag/micropython,Timmenem/micropython,infinnovation/micropython,swegener/micropython,bvernoux/micropython,toolmacher/micropython,kerneltask/micropython,PappaPeppar/micropython,pfalcon/micropython,HenrikSolver/micropython,PappaPeppar/micropython,dmazzella/micropython,pozetroninc/micropython,tobbad/micropython,SHA2017-badge/micropython-esp32,deshipu/micropython,toolmacher/micropython,adafruit/micropython,HenrikSolver/micropython,SHA2017-badge/micropython-esp32,HenrikSolver/micropython,chrisdearman/micropython,adafruit/circuitpython,adafruit/micropython,Timmenem/micropython,micropython/micropython-esp32,infinnovation/micropython,micropython/micropython-esp32,deshipu/micropython,adafruit/circuitpython,adafruit/micropython,kerneltask/micropython,selste/micropython,Timmenem/micropython,toolmacher/micropython,ryannathans/micropython,oopy/micropython,tobbad/micropython,MrSurly/micropython-esp32
|
9d0b1990b979de19939cc37cbefb86e1a0cd4e0f
|
test/perf/perf.py
|
test/perf/perf.py
|
import numpy as np
import pylab as pl
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observation_covariance = [0.1]
initial_state_mean = [1.0,0.0]
initial_state_covariance = [[1,0.1],[-0.1,1]]
kf = KalmanFilter(
transition_matrices=transition_matrix,observation_matrices=observation_matrix, transition_covariance=transition_covariance,
observation_covariance=observation_covariance, transition_offsets=transition_offset, observation_offsets=observation_offset,
initial_state_mean=initial_state_mean, initial_state_covariance=initial_state_covariance,
random_state=random_state
)
ts = np.linspace(0,0.01*1000,1000)
observations = np.cos(ts) + np.sqrt(0.1) * random_state.randn(1000)
states = np.cos(ts)
t = timeit.timeit('filtered_state_estimates = kf.filter(observations)[0]','from __main__ import kf,observations',number=N)
print t
|
import numpy as np
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observation_covariance = [0.1]
initial_state_mean = [1.0,0.0]
initial_state_covariance = [[1,0.1],[-0.1,1]]
kf = KalmanFilter(
transition_matrices=transition_matrix,observation_matrices=observation_matrix, transition_covariance=transition_covariance,
observation_covariance=observation_covariance, transition_offsets=transition_offset, observation_offsets=observation_offset,
initial_state_mean=initial_state_mean, initial_state_covariance=initial_state_covariance,
random_state=random_state
)
ts = np.linspace(0,0.01*1000,1000)
observations = np.cos(ts) + np.sqrt(0.1) * random_state.randn(1000)
states = np.cos(ts)
t = timeit.timeit('filtered_state_estimates = kf.filter(observations)[0]','from __main__ import kf,observations',number=N)
print t
|
Remove pylab from import statements
|
Remove pylab from import statements
|
Python
|
mit
|
wkearn/Kalman.jl,wkearn/Kalman.jl
|
5f4155201afa92f048f28b9cd53681a6bc7966ab
|
vendor/eventlet-0.9.15/eventlet/convenience.py
|
vendor/eventlet-0.9.15/eventlet/convenience.py
|
# The history of this repository has been rewritten to erase the vendor/ directory
# Below is the md5sum and size of the file that was in the original commit
bde0e3a3a15c9bbb8d96f4d8a370d8c7
5753
|
# The history of this repository has been rewritten to erase the vendor/ directory
# Below is the md5sum and size of the file that was in the original commit
5b7615cc9b13cf39cfa39db53e86977a
5751
|
Drop eventlet bundle back to released state. Will workaround the bug we fixed there, in our own code.
|
Drop eventlet bundle back to released state. Will workaround the bug we fixed
there, in our own code.
|
Python
|
mit
|
gratipay/aspen.py,gratipay/aspen.py
|
e5b503d0e66f8422412d0cdeac4ba4f55f14e420
|
spectrum/object.py
|
spectrum/object.py
|
# -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if two objects are equal. |
+-----------+--------------------------------------+
| x != y | Checks if two objects are not equal. |
+-----------+--------------------------------------+
This is the class that will be the base class of most objects, since most
have an ID number.
id : int
The ID of the object
"""
def __init__(self, id):
self.id = int(id)
def __eq__(self, other):
return isinstance(other, self.__class__) and other.id == self.id
def __ne__(self, other):
if isinstance(other, self.__class__):
return other.id != self.id
return True
|
# -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if two objects are equal. |
+-----------+--------------------------------------+
| x != y | Checks if two objects are not equal. |
+-----------+--------------------------------------+
This class is the base class of most objects, since most
have an ID number.
id : int
The ID of the object
"""
def __init__(self, id):
self.id = int(id)
def __eq__(self, other):
return isinstance(other, self.__class__) and other.id == self.id
def __ne__(self, other):
if isinstance(other, self.__class__):
return other.id != self.id
return True
|
Change wording from future to present tense
|
Documentation: Change wording from future to present tense
|
Python
|
mit
|
treefroog/spectrum.py
|
9578081d1c6ce378687d605ba2350e08eddb6959
|
scipy/ndimage/segment/setup.py
|
scipy/ndimage/segment/setup.py
|
#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('segment', parent_package, top_path)
config.add_extension('_segmenter',
sources=['Segmenter_EXT.c',
'Segmenter_IMPL.c'],
depends = ['ndImage_Segmenter_structs.h']
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('segment', parent_package, top_path)
config.add_extension('_segmenter',
sources=['Segmenter_EXT.c',
'Segmenter_IMPL.c'],
depends = ['ndImage_Segmenter_structs.h']
)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Add tests as data_dir to ndimage.segment
|
Add tests as data_dir to ndimage.segment
|
Python
|
bsd-3-clause
|
jamestwebber/scipy,mdhaber/scipy,ChanderG/scipy,Kamp9/scipy,Stefan-Endres/scipy,rmcgibbo/scipy,gdooper/scipy,mtrbean/scipy,petebachant/scipy,matthewalbani/scipy,fredrikw/scipy,efiring/scipy,apbard/scipy,ales-erjavec/scipy,mikebenfield/scipy,Eric89GXL/scipy,Newman101/scipy,sriki18/scipy,andyfaff/scipy,Stefan-Endres/scipy,anntzer/scipy,jseabold/scipy,lukauskas/scipy,jor-/scipy,felipebetancur/scipy,befelix/scipy,jsilter/scipy,petebachant/scipy,mortada/scipy,mhogg/scipy,pyramania/scipy,niknow/scipy,zxsted/scipy,giorgiop/scipy,vhaasteren/scipy,anntzer/scipy,giorgiop/scipy,gef756/scipy,zerothi/scipy,fredrikw/scipy,grlee77/scipy,zaxliu/scipy,pschella/scipy,trankmichael/scipy,nmayorov/scipy,tylerjereddy/scipy,sonnyhu/scipy,aarchiba/scipy,surhudm/scipy,ilayn/scipy,mhogg/scipy,WarrenWeckesser/scipy,ilayn/scipy,mtrbean/scipy,sargas/scipy,richardotis/scipy,newemailjdm/scipy,Newman101/scipy,sauliusl/scipy,futurulus/scipy,e-q/scipy,vberaudi/scipy,pyramania/scipy,rgommers/scipy,nvoron23/scipy,FRidh/scipy,aarchiba/scipy,jor-/scipy,Newman101/scipy,ndchorley/scipy,teoliphant/scipy,trankmichael/scipy,newemailjdm/scipy,aman-iitj/scipy,niknow/scipy,giorgiop/scipy,WarrenWeckesser/scipy,juliantaylor/scipy,efiring/scipy,dch312/scipy,ndchorley/scipy,sargas/scipy,andim/scipy,raoulbq/scipy,mortonjt/scipy,ortylp/scipy,rgommers/scipy,pnedunuri/scipy,Eric89GXL/scipy,endolith/scipy,andim/scipy,ChanderG/scipy,fredrikw/scipy,jjhelmus/scipy,jjhelmus/scipy,minhlongdo/scipy,anielsen001/scipy,Shaswat27/scipy,Srisai85/scipy,pbrod/scipy,pbrod/scipy,jsilter/scipy,rmcgibbo/scipy,jjhelmus/scipy,richardotis/scipy,vanpact/scipy,ales-erjavec/scipy,Stefan-Endres/scipy,mikebenfield/scipy,vhaasteren/scipy,cpaulik/scipy,mdhaber/scipy,kalvdans/scipy,vanpact/scipy,newemailjdm/scipy,Srisai85/scipy,kleskjr/scipy,nvoron23/scipy,zxsted/scipy,mhogg/scipy,pizzathief/scipy,petebachant/scipy,matthewalbani/scipy,scipy/scipy,niknow/scipy,vberaudi/scipy,lhilt/scipy,matthewalbani/scipy,teoliphant/scipy,gfyoung/scipy,gertingold/scipy,matthewalbani/scipy,ogrisel/scipy,zaxliu/scipy,vhaasteren/scipy,mortonjt/scipy,jor-/scipy,vberaudi/scipy,vberaudi/scipy,scipy/scipy,endolith/scipy,FRidh/scipy,anntzer/scipy,pbrod/scipy,josephcslater/scipy,e-q/scipy,kleskjr/scipy,sonnyhu/scipy,efiring/scipy,andim/scipy,pbrod/scipy,pbrod/scipy,zxsted/scipy,felipebetancur/scipy,aeklant/scipy,sriki18/scipy,Kamp9/scipy,Gillu13/scipy,haudren/scipy,piyush0609/scipy,hainm/scipy,cpaulik/scipy,njwilson23/scipy,dominicelse/scipy,sauliusl/scipy,juliantaylor/scipy,mgaitan/scipy,sauliusl/scipy,lhilt/scipy,jamestwebber/scipy,mingwpy/scipy,nvoron23/scipy,matthewalbani/scipy,petebachant/scipy,matthew-brett/scipy,Eric89GXL/scipy,befelix/scipy,bkendzior/scipy,tylerjereddy/scipy,richardotis/scipy,lukauskas/scipy,fernand/scipy,befelix/scipy,juliantaylor/scipy,vanpact/scipy,ilayn/scipy,sonnyhu/scipy,mingwpy/scipy,fernand/scipy,vigna/scipy,ortylp/scipy,petebachant/scipy,e-q/scipy,nmayorov/scipy,andyfaff/scipy,behzadnouri/scipy,Kamp9/scipy,matthew-brett/scipy,Dapid/scipy,pschella/scipy,aman-iitj/scipy,trankmichael/scipy,mtrbean/scipy,cpaulik/scipy,dch312/scipy,aeklant/scipy,argriffing/scipy,chatcannon/scipy,vhaasteren/scipy,kleskjr/scipy,vhaasteren/scipy,sargas/scipy,bkendzior/scipy,rgommers/scipy,mdhaber/scipy,kalvdans/scipy,sauliusl/scipy,ndchorley/scipy,Shaswat27/scipy,maniteja123/scipy,gef756/scipy,kalvdans/scipy,dominicelse/scipy,arokem/scipy,ChanderG/scipy,arokem/scipy,mgaitan/scipy,mingwpy/scipy,Gillu13/scipy,zxsted/scipy,futurulus/scipy,aeklant/scipy,niknow/scipy,mdhaber/scipy,felipebetancur/scipy,perimosocordiae/scipy,ortylp/scipy,FRidh/scipy,aman-iitj/scipy,arokem/scipy,sonnyhu/scipy,arokem/scipy,apbard/scipy,Newman101/scipy,jseabold/scipy,andyfaff/scipy,jakevdp/scipy,pizzathief/scipy,scipy/scipy,andyfaff/scipy,dch312/scipy,jamestwebber/scipy,aeklant/scipy,lukauskas/scipy,piyush0609/scipy,apbard/scipy,lukauskas/scipy,woodscn/scipy,fredrikw/scipy,bkendzior/scipy,aarchiba/scipy,giorgiop/scipy,lhilt/scipy,andyfaff/scipy,josephcslater/scipy,pizzathief/scipy,jonycgn/scipy,sauliusl/scipy,niknow/scipy,mortonjt/scipy,perimosocordiae/scipy,richardotis/scipy,pschella/scipy,maniteja123/scipy,jjhelmus/scipy,woodscn/scipy,jsilter/scipy,pschella/scipy,woodscn/scipy,niknow/scipy,Eric89GXL/scipy,ales-erjavec/scipy,Dapid/scipy,jjhelmus/scipy,rmcgibbo/scipy,maciejkula/scipy,njwilson23/scipy,minhlongdo/scipy,lhilt/scipy,Shaswat27/scipy,ogrisel/scipy,tylerjereddy/scipy,mingwpy/scipy,mikebenfield/scipy,Kamp9/scipy,mortonjt/scipy,nmayorov/scipy,dch312/scipy,andim/scipy,kleskjr/scipy,minhlongdo/scipy,befelix/scipy,witcxc/scipy,nonhermitian/scipy,andim/scipy,zerothi/scipy,felipebetancur/scipy,WillieMaddox/scipy,sriki18/scipy,Srisai85/scipy,anntzer/scipy,aarchiba/scipy,chatcannon/scipy,surhudm/scipy,jakevdp/scipy,zaxliu/scipy,gertingold/scipy,perimosocordiae/scipy,aarchiba/scipy,rmcgibbo/scipy,pyramania/scipy,arokem/scipy,mhogg/scipy,endolith/scipy,maniteja123/scipy,fredrikw/scipy,kalvdans/scipy,behzadnouri/scipy,teoliphant/scipy,sonnyhu/scipy,fernand/scipy,perimosocordiae/scipy,bkendzior/scipy,behzadnouri/scipy,Newman101/scipy,Dapid/scipy,mortada/scipy,fernand/scipy,chatcannon/scipy,vanpact/scipy,jakevdp/scipy,person142/scipy,WarrenWeckesser/scipy,jseabold/scipy,maniteja123/scipy,tylerjereddy/scipy,mortada/scipy,cpaulik/scipy,ogrisel/scipy,josephcslater/scipy,vigna/scipy,jakevdp/scipy,FRidh/scipy,Kamp9/scipy,ortylp/scipy,zxsted/scipy,person142/scipy,juliantaylor/scipy,larsmans/scipy,nonhermitian/scipy,person142/scipy,perimosocordiae/scipy,gdooper/scipy,hainm/scipy,matthew-brett/scipy,pyramania/scipy,newemailjdm/scipy,richardotis/scipy,befelix/scipy,teoliphant/scipy,gdooper/scipy,tylerjereddy/scipy,njwilson23/scipy,zerothi/scipy,piyush0609/scipy,endolith/scipy,argriffing/scipy,gertingold/scipy,mortada/scipy,maniteja123/scipy,gef756/scipy,witcxc/scipy,mdhaber/scipy,njwilson23/scipy,grlee77/scipy,matthew-brett/scipy,vigna/scipy,nonhermitian/scipy,gef756/scipy,dominicelse/scipy,pnedunuri/scipy,ogrisel/scipy,raoulbq/scipy,pizzathief/scipy,raoulbq/scipy,mortada/scipy,anielsen001/scipy,gef756/scipy,hainm/scipy,behzadnouri/scipy,maniteja123/scipy,maciejkula/scipy,josephcslater/scipy,chatcannon/scipy,zxsted/scipy,WarrenWeckesser/scipy,grlee77/scipy,hainm/scipy,pbrod/scipy,vberaudi/scipy,anntzer/scipy,Srisai85/scipy,minhlongdo/scipy,jseabold/scipy,Srisai85/scipy,chatcannon/scipy,minhlongdo/scipy,Gillu13/scipy,mgaitan/scipy,teoliphant/scipy,woodscn/scipy,mhogg/scipy,matthew-brett/scipy,jseabold/scipy,futurulus/scipy,larsmans/scipy,lhilt/scipy,rgommers/scipy,mtrbean/scipy,Gillu13/scipy,scipy/scipy,surhudm/scipy,FRidh/scipy,pnedunuri/scipy,anntzer/scipy,newemailjdm/scipy,nonhermitian/scipy,Shaswat27/scipy,bkendzior/scipy,mortonjt/scipy,trankmichael/scipy,pizzathief/scipy,raoulbq/scipy,petebachant/scipy,mingwpy/scipy,larsmans/scipy,person142/scipy,futurulus/scipy,dominicelse/scipy,aeklant/scipy,trankmichael/scipy,nvoron23/scipy,ales-erjavec/scipy,haudren/scipy,nmayorov/scipy,anielsen001/scipy,woodscn/scipy,sonnyhu/scipy,gef756/scipy,FRidh/scipy,sriki18/scipy,pnedunuri/scipy,vanpact/scipy,lukauskas/scipy,e-q/scipy,pyramania/scipy,WillieMaddox/scipy,sargas/scipy,richardotis/scipy,felipebetancur/scipy,argriffing/scipy,gertingold/scipy,chatcannon/scipy,efiring/scipy,raoulbq/scipy,ortylp/scipy,Shaswat27/scipy,witcxc/scipy,mgaitan/scipy,gfyoung/scipy,efiring/scipy,mortonjt/scipy,jor-/scipy,WillieMaddox/scipy,ogrisel/scipy,ChanderG/scipy,mhogg/scipy,person142/scipy,kalvdans/scipy,pnedunuri/scipy,gfyoung/scipy,haudren/scipy,rmcgibbo/scipy,ndchorley/scipy,sargas/scipy,nvoron23/scipy,aman-iitj/scipy,ilayn/scipy,Srisai85/scipy,Dapid/scipy,Stefan-Endres/scipy,nvoron23/scipy,njwilson23/scipy,andim/scipy,andyfaff/scipy,nonhermitian/scipy,Eric89GXL/scipy,Gillu13/scipy,grlee77/scipy,mtrbean/scipy,Newman101/scipy,kleskjr/scipy,ortylp/scipy,ales-erjavec/scipy,zerothi/scipy,mikebenfield/scipy,gfyoung/scipy,jamestwebber/scipy,surhudm/scipy,ndchorley/scipy,aman-iitj/scipy,argriffing/scipy,jsilter/scipy,Eric89GXL/scipy,njwilson23/scipy,endolith/scipy,fernand/scipy,anielsen001/scipy,jor-/scipy,efiring/scipy,Dapid/scipy,jonycgn/scipy,felipebetancur/scipy,apbard/scipy,behzadnouri/scipy,larsmans/scipy,pnedunuri/scipy,Gillu13/scipy,fernand/scipy,mdhaber/scipy,sriki18/scipy,hainm/scipy,endolith/scipy,mgaitan/scipy,ilayn/scipy,larsmans/scipy,anielsen001/scipy,mortada/scipy,argriffing/scipy,gfyoung/scipy,WarrenWeckesser/scipy,larsmans/scipy,giorgiop/scipy,gdooper/scipy,jseabold/scipy,surhudm/scipy,zerothi/scipy,ales-erjavec/scipy,jonycgn/scipy,juliantaylor/scipy,zaxliu/scipy,sauliusl/scipy,behzadnouri/scipy,dch312/scipy,anielsen001/scipy,scipy/scipy,gertingold/scipy,Stefan-Endres/scipy,piyush0609/scipy,cpaulik/scipy,mtrbean/scipy,vigna/scipy,rgommers/scipy,rmcgibbo/scipy,jonycgn/scipy,piyush0609/scipy,woodscn/scipy,futurulus/scipy,argriffing/scipy,zaxliu/scipy,maciejkula/scipy,grlee77/scipy,WillieMaddox/scipy,hainm/scipy,lukauskas/scipy,WillieMaddox/scipy,witcxc/scipy,zerothi/scipy,vanpact/scipy,WillieMaddox/scipy,minhlongdo/scipy,kleskjr/scipy,gdooper/scipy,ChanderG/scipy,piyush0609/scipy,ilayn/scipy,vhaasteren/scipy,Stefan-Endres/scipy,Dapid/scipy,trankmichael/scipy,jakevdp/scipy,aman-iitj/scipy,sriki18/scipy,haudren/scipy,nmayorov/scipy,apbard/scipy,jonycgn/scipy,haudren/scipy,scipy/scipy,maciejkula/scipy,jonycgn/scipy,vberaudi/scipy,fredrikw/scipy,perimosocordiae/scipy,jsilter/scipy,e-q/scipy,newemailjdm/scipy,dominicelse/scipy,josephcslater/scipy,Shaswat27/scipy,pschella/scipy,vigna/scipy,jamestwebber/scipy,raoulbq/scipy,witcxc/scipy,haudren/scipy,Kamp9/scipy,mingwpy/scipy,ChanderG/scipy,mikebenfield/scipy,zaxliu/scipy,mgaitan/scipy,futurulus/scipy,WarrenWeckesser/scipy,cpaulik/scipy,ndchorley/scipy,giorgiop/scipy,maciejkula/scipy,surhudm/scipy
|
c06e28dae894823c0ae5385e0f9c047ceab8561c
|
zombies/tests.py
|
zombies/tests.py
|
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
|
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story, StoryPoint
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
def test_ensure_storyPoints_is_inserted(self):
storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2')
storyPoint.save()
self.assertEquals((storyPoint.description=='You are in the library'),True)
self.assertEquals((storyPoint.choiceText=='yes'),True)
self.assertEquals((storyPoint.experience==10),True)
self.assertEquals((storyPoint.story_type=='start'),True)
self.assertEquals((storyPoint.story_point_id==1),True)
self.assertEquals((storyPoint.picture=='testpic2'),True)
self.assertEquals((storyPoint.visits==1),True)
self.assertEquals((storyPoint.main_story_id_id==5),True)
|
Test case 2 for table storypoint
|
Test case 2 for table storypoint
|
Python
|
apache-2.0
|
ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project
|
2baed20067fed71987bf7582fa9c9a5e53a63cb5
|
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
|
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
|
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
|
s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
sw = s.startswith # $f-:checks=s $f-:branch=true
if sw("safe"):
pass
|
Test false negative from review
|
Python: Test false negative from review
|
Python
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
46ae5bbeab37f8e2fe14607c01e385d746c2d163
|
pymt/components.py
|
pymt/components.py
|
from __future__ import print_function
__all__ = []
import os
import sys
import warnings
import importlib
from glob import glob
from .framework.bmi_bridge import bmi_factory
from .babel import setup_babel_environ
def import_csdms_components():
debug = os.environ.get('PYMT_DEBUG', False)
setup_babel_environ()
if debug:
print('Importing components with the following environment')
for k, v in os.environ.items():
print('- {key}: {val}'.format(key=k, val=v))
try:
csdms_module = importlib.import_module('csdms')
except ImportError:
warnings.warn('Unable to import csdms. Not loading components.')
else:
if debug:
print('imported csdms module')
files = glob(os.path.join(csdms_module.__path__[0], '*so'))
_COMPONENT_NAMES = [
os.path.splitext(os.path.basename(f))[0] for f in files]
if debug:
print('found the following components')
for name in _COMPONENT_NAMES:
print('- {name}'.format(name=name))
for name in _COMPONENT_NAMES:
module_name = '.'.join(['csdms', name])
try:
module = importlib.import_module(module_name)
except ImportError:
if debug:
print('unable to import {mod}'.format(mod=module_name))
else:
if debug:
print('imported {mod}'.format(mod=module_name))
if name in module.__dict__:
try:
setattr(sys.modules[__name__], name,
bmi_factory(module.__dict__[name]))
__all__.append(name)
except Exception as err:
print('warning: found csdms.{name} but was unable '
'to wrap it'.format(name=name))
if debug:
print(err)
import_csdms_components()
|
__all__ = []
import sys
from .plugin import load_csdms_plugins
for plugin in load_csdms_plugins():
__all__.append(plugin.__name__)
setattr(sys.modules[__name__], plugin.__name__, plugin)
|
Move csdms-plugin loading to plugin module.
|
Move csdms-plugin loading to plugin module.
|
Python
|
mit
|
csdms/pymt,csdms/coupling,csdms/coupling
|
1e66aba5a2c82b09a6485842948aad49c654efb4
|
scripts/load_topics_to_mongodb.py
|
scripts/load_topics_to_mongodb.py
|
import os
import csv
from pymongo import MongoClient
print('Parsing topics')
topics = {}
with open('topics.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
if line[0] == 1:
continue
topics[line[0]] = line[1:]
print('Connecting to MongoDB')
mongodb_client = MongoClient(os.environ['MONGODB_URL'])
db = mongodb_client.tvrain
articles = db.articles
for article in topics:
articles.update({'_id': article}, {'$set': {
'topics': topics[article]
}})
|
import os
import sys
import csv
from pymongo import MongoClient
print('Parsing topics')
topics = {}
with open(sys.argv[1], 'r') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
if line[0] == 1:
continue
topics[line[0]] = line[1:]
print('Connecting to MongoDB')
mongodb_client = MongoClient(os.environ['MONGODB_URL'])
db = mongodb_client.tvrain
articles = db.articles
for article in topics:
articles.update({'_id': article}, {'$set': {
'topics': topics[article]
}})
|
Fix script for loading topics into mongodb
|
Fix script for loading topics into mongodb
|
Python
|
mit
|
xenx/recommendation_system,xenx/recommendation_system
|
eefa28f06620d568eda641b08c1caa9cff9a0c96
|
resourcemanager.py
|
resourcemanager.py
|
# Manage resources here
import animation
sounds = {}
images = {}
animations = {}
loaded_resources = False
def load_resources():
"""Fills the structure above with the resources for the game.
"""
if loaded_resources:
return
loaded_resources = True
|
# Manage resources here
import pygame
from pygame.locals import *
import animation
sounds = {}
images = {}
animations = {}
loaded_resources = False
sound_defs = {
"aoe" : "aoe.wav",
"big hit" : "big_hit.wav",
"burstfire" : "burstfire.wav",
"explosion" : "explosion.wav",
"fireball" : "fireball.wav",
"hover" : "heavy_hover.wav",
"high pitch" : "high_pitch.wav",
"jump" : "jump.wav",
"long swing" : "longswing.wav",
"pickaxe" : "pickaxe.wav",
"pickup" : "pickup.wav",
"select" : "select.wav",
"short swing" : "shortswing.wav",
"spell" : "spell.wav",
"summon" : "summon.wav",
"teleport" : "teleport.wav"
}
def load_resources():
"""Fills the structure above with the resources for the game.
"""
if loaded_resources:
return
loaded_resources = True
for name, filename in sound_defs.iteritems():
sounds[name] = pygame.mixer.Sound(filename)
|
Add sound definitions to resource manager
|
Add sound definitions to resource manager
|
Python
|
mit
|
vwood/pyweek2013
|
e578c90cc542d3cf825645fa9376796a1e7c31f9
|
lib/cache.py
|
lib/cache.py
|
import functools
import logging
import redis
import config
# Default options
redis_opts = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
redis_conn = None
cache_prefix = None
def init():
global redis_conn, cache_prefix
cfg = config.load()
cache = cfg.cache
if not cache:
return
logging.info('Enabling storage cache on Redis')
if not isinstance(cache, dict):
cache = {}
for k, v in cache.iteritems():
redis_opts[k] = v
logging.info('Redis config: {0}'.format(redis_opts))
redis_conn = redis.StrictRedis(host=redis_opts['host'],
port=int(redis_opts['port']),
db=int(redis_opts['db']),
password=redis_opts['password'])
cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/'))
def cache_key(key):
return cache_prefix + key
def put(f):
@functools.wraps(f)
def wrapper(*args):
content = args[-1]
key = args[-2]
key = cache_key(key)
redis_conn.set(key, content)
return f(*args)
if redis_conn is None:
return f
return wrapper
def get(f):
@functools.wraps(f)
def wrapper(*args):
key = args[-1]
key = cache_key(key)
content = redis_conn.get(key)
if content is not None:
return content
# Refresh cache
content = f(*args)
redis_conn.set(key, content)
return content
if redis_conn is None:
return f
return wrapper
def remove(f):
@functools.wraps(f)
def wrapper(*args):
key = args[-1]
key = cache_key(key)
redis_conn.delete(key)
return f(*args)
if redis_conn is None:
return f
return wrapper
init()
|
import functools
import logging
import redis
import config
# Default options
redis_opts = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
redis_conn = None
cache_prefix = None
def init():
global redis_conn, cache_prefix
cfg = config.load()
cache = cfg.cache
if not cache:
return
logging.info('Enabling storage cache on Redis')
if not isinstance(cache, dict):
cache = {}
for k, v in cache.iteritems():
redis_opts[k] = v
logging.info('Redis config: {0}'.format(redis_opts))
redis_conn = redis.StrictRedis(host=redis_opts['host'],
port=int(redis_opts['port']),
db=int(redis_opts['db']),
password=redis_opts['password'])
cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/'))
init()
|
Remove unneeded lru specific helper methods
|
Remove unneeded lru specific helper methods
|
Python
|
apache-2.0
|
dalvikchen/docker-registry,atyenoria/docker-registry,atyenoria/docker-registry,ewindisch/docker-registry,docker/docker-registry,ken-saka/docker-registry,wakermahmud/docker-registry,Carrotzpc/docker-registry,kireal/docker-registry,ewindisch/docker-registry,yuriyf/docker-registry,whuwxl/docker-registry,Haitianisgood/docker-registry,GoogleCloudPlatform/docker-registry-driver-gcs,dedalusdev/docker-registry,cnh/docker-registry,HubSpot/docker-registry,yuriyf/docker-registry,deis/docker-registry,csrwng/docker-registry,wakermahmud/docker-registry,mdshuai/docker-registry,cnh/docker-registry,dalvikchen/docker-registry,dedalusdev/docker-registry,deis/docker-registry,alephcloud/docker-registry,depay/docker-registry,stormltf/docker-registry,docker/docker-registry,scrapinghub/docker-registry,pombredanne/docker-registry,depay/docker-registry,liggitt/docker-registry,atyenoria/docker-registry,dhiltgen/docker-registry,ken-saka/docker-registry,shipyard/docker-registry,stormltf/docker-registry,pombredanne/docker-registry,ActiveState/docker-registry,dhiltgen/docker-registry,nunogt/docker-registry,dalvikchen/docker-registry,HubSpot/docker-registry,andrew-plunk/docker-registry,shakamunyi/docker-registry,yuriyf/docker-registry,kireal/docker-registry,kireal/docker-registry,dhiltgen/docker-registry,mdshuai/docker-registry,HubSpot/docker-registry,fabianofranz/docker-registry,cnh/docker-registry,Haitianisgood/docker-registry,ptisserand/docker-registry,catalyst-zero/docker-registry,ken-saka/docker-registry,tangkun75/docker-registry,shakamunyi/docker-registry,mdshuai/docker-registry,GoogleCloudPlatform/docker-registry-driver-gcs,liggitt/docker-registry,dedalusdev/docker-registry,whuwxl/docker-registry,Carrotzpc/docker-registry,wakermahmud/docker-registry,deis/docker-registry,scrapinghub/docker-registry,hpcloud/docker-registry,ActiveState/docker-registry,viljaste/docker-registry-1,OnePaaS/docker-registry,OnePaaS/docker-registry,catalyst-zero/docker-registry,shakamunyi/docker-registry,hpcloud/docker-registry,tangkun75/docker-registry,csrwng/docker-registry,hpcloud/docker-registry,shipyard/docker-registry,mboersma/docker-registry,hex108/docker-registry,tangkun75/docker-registry,hex108/docker-registry,dine1987/Docker,Haitianisgood/docker-registry,fabianofranz/docker-registry,mboersma/docker-registry,Carrotzpc/docker-registry,ptisserand/docker-registry,nunogt/docker-registry,dine1987/Docker,ptisserand/docker-registry,docker/docker-registry,OnePaaS/docker-registry,andrew-plunk/docker-registry,scrapinghub/docker-registry,ActiveState/docker-registry,nunogt/docker-registry,mboersma/docker-registry,alephcloud/docker-registry,alephcloud/docker-registry,depay/docker-registry,csrwng/docker-registry,fabianofranz/docker-registry,shipyard/docker-registry,hex108/docker-registry,stormltf/docker-registry,whuwxl/docker-registry,viljaste/docker-registry-1,pombredanne/docker-registry,ewindisch/docker-registry,andrew-plunk/docker-registry,dine1987/Docker,viljaste/docker-registry-1,liggitt/docker-registry,catalyst-zero/docker-registry
|
52bb18cf1249e3f48764a7ed4e9546439692c5cb
|
packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
|
packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
|
import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self.valobj.GetChildMemberWithName('a');
if index == 1:
child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
if index == 2:
child = self.valobj.GetChildMemberWithName('r');
return child;
def get_child_index(self, name):
if name == 'a':
return 0;
if name == 'fake_a':
return 1;
return 2;
|
import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self.valobj.GetChildMemberWithName('a');
if index == 1:
child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
if index == 2:
child = self.valobj.GetChildMemberWithName('r');
return child;
def get_child_index(self, name):
if name == 'a':
return 0;
if name == 'fake_a':
return 1;
return 2;
|
Fix TestSyntheticCapping for Python 3.
|
Fix TestSyntheticCapping for Python 3.
In Python 3, whitespace inconsistences are errors. This synthetic
provider had mixed tabs and spaces, as well as inconsistent
indentation widths. This led to the file not being imported,
and naturally the test failing. No functional change here, just
whitespace.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@258751 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb
|
e6fa443412a909bc01e2dd8d9944ff3ddba35089
|
numpy/_array_api/_constants.py
|
numpy/_array_api/_constants.py
|
from .. import e, inf, nan, pi
|
from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
|
Make the array API constants into dimension 0 arrays
|
Make the array API constants into dimension 0 arrays
The spec does not actually specify whether these should be dimension 0 arrays
or Python floats (which they are in NumPy). However, making them dimension 0
arrays is cleaner, and ensures they also have all the methods and attributes
that are implemented on the ndarray object.
|
Python
|
mit
|
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
|
f012d59f163a8b8a693dc894d211f077ae015d11
|
Instanssi/kompomaatti/tests.py
|
Instanssi/kompomaatti/tests.py
|
from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v/asdf123456",
# must handle various other ways to define the video
"www.youtube.com/watch?v=asdf123456",
"http://youtu.be/asdf123456",
"http://youtu.be/asdf123456/"
]
class KompomaattiTests(TestCase):
def setUp(self):
pass
def test_youtube_urls(self):
"""Test that various YouTube URLs are parsed properly."""
for url in VALID_YOUTUBE_URLS:
print("Test URL: %s" % url)
self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456")
|
from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols and hostnames in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v/asdf123456",
"youtube.com/v/asdf123456/",
# must handle various other ways to define the video
"www.youtube.com/watch?v=asdf123456",
"http://youtu.be/asdf123456",
"https://youtu.be/asdf123456/"
]
class KompomaattiTests(TestCase):
def setUp(self):
pass
def test_youtube_urls(self):
"""Test YouTube video id extraction from URLs."""
for url in VALID_YOUTUBE_URLS:
self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456",
msg="failing URL: %s" % url)
|
Add more test data; improve feedback on failing case
|
kompomaatti: Add more test data; improve feedback on failing case
|
Python
|
mit
|
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
|
948c9c6ffb8a34e3acf00b8190bf65504f2bfaf6
|
app.py
|
app.py
|
import falcon
from resources.waifu_message_resource import WaifuMessageResource
api = falcon.API()
api.add_route('/waifu/messages', WaifuMessageResource())
|
import falcon
from resources.user_resource import UserResource, UserAuthResource
from resources.waifu_message_resource import WaifuMessageResource
from resources.waifu_resource import WaifuResource
api = falcon.API()
api.add_route('/user', UserResource())
api.add_route('/user/auth', UserAuthResource())
api.add_route('/waifu', WaifuResource())
api.add_route('/waifu/messages', WaifuMessageResource())
|
Add endpoints for all resources.
|
Add endpoints for all resources.
|
Python
|
cc0-1.0
|
sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend
|
bea8b07180e6e9b2c786dfe37e12e75090363a1c
|
run.py
|
run.py
|
import os
import json
default_conf = {
'reddit': {
'username': '',
'password': '',
},
'twitter': {
'consumer_key': '',
'consumer_secret': '',
'access_token': '',
'access_secret': '',
},
}
if __name__ == '__main__':
if not os.path.isfile('config.json'):
config = json.dumps(default_conf, indent=4, sort_keys=True)
with open('config.json', 'w') as f:
f.write(config)
print 'Created default config in config.json, please edit'
|
import os
import json
import sys
default_conf = {
'reddit': {
'username': '',
'password': '',
},
'twitter': {
'consumer_key': '',
'consumer_secret': '',
'access_token': '',
'access_secret': '',
},
}
def write_conf(conf):
config = json.dumps(conf, indent=4, sort_keys=True)
with open('config.json', 'w') as f:
f.write(config)
if __name__ == '__main__':
if not os.path.isfile('config.json'):
write_conf(default_conf)
print 'Created default config in config.json, please edit'
elif 'updateconf' in sys.argv:
with open('config.json', 'r') as f:
config = json.loads(f.read())
default_conf.update(config)
write_conf(default_conf)
|
Add twitter stuff to default config and allow easier merging of configs
|
Add twitter stuff to default config and allow easier merging of configs
|
Python
|
mit
|
r3m0t/TweetPoster,joealcorn/TweetPoster,tytek2012/TweetPoster,aperson/TweetPoster
|
9d65eaa14bc3f04ea998ed7bc43b7c71e5d232f7
|
v3/scripts/testing/create-8gb-metadata.py
|
v3/scripts/testing/create-8gb-metadata.py
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = 'eric'
'''
Need to create some test data
'''
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = 'eric'
'''
Need to create some test data
8 gigabytes dataset
'''
|
Test script for generating metadata
|
Test script for generating metadata
|
Python
|
mit
|
TheShellLand/pies,TheShellLand/pies
|
53d09ddacc92a52219a3cd18bba606840b870fcd
|
vumi_http_proxy/test/test_servicemaker.py
|
vumi_http_proxy/test/test_servicemaker.py
|
from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.parseOptions([])
self.assertEqual(options["port"], 8080)
self.assertEqual(str(options["interface"]), "0.0.0.0")
def test_override(self):
options = Options()
options.parseOptions(["--port", 8000])
options.parseOptions(["--interface", "127.0.0.1"])
self.assertEqual(options["port"], "8000")
self.assertEqual(str(options["interface"]), "127.0.0.1")
class TestProxyWorkerServiceMaker(unittest.TestCase):
def test_makeService(self):
options = Options()
options.parseOptions([])
servicemaker = ProxyWorkerServiceMaker()
service = servicemaker.makeService(options)
self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory))
self.assertEqual(service.endpoint._interface, '0.0.0.0')
self.assertEqual(service.endpoint._port, 8080)
|
from vumi_http_proxy.servicemaker import (
Options, ProxyWorkerServiceMaker, client)
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
from vumi_http_proxy.test import helpers
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.parseOptions([])
self.assertEqual(options["port"], 8080)
self.assertEqual(str(options["interface"]), "0.0.0.0")
def test_override(self):
options = Options()
options.parseOptions(["--port", 8000])
options.parseOptions(["--interface", "127.0.0.1"])
self.assertEqual(options["port"], "8000")
self.assertEqual(str(options["interface"]), "127.0.0.1")
class TestProxyWorkerServiceMaker(unittest.TestCase):
def test_makeService(self):
options = Options()
options.parseOptions([])
self.patch(client, 'createResolver', lambda: helpers.TestResolver())
servicemaker = ProxyWorkerServiceMaker()
service = servicemaker.makeService(options)
self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory))
self.assertEqual(service.endpoint._interface, '0.0.0.0')
self.assertEqual(service.endpoint._port, 8080)
|
Patch out DNS resolver in makeService tests.
|
Patch out DNS resolver in makeService tests.
|
Python
|
bsd-3-clause
|
praekelt/vumi-http-proxy,praekelt/vumi-http-proxy
|
2cc55a25b13ac6575424ba70857a8419b796ca76
|
_tests/macro_testing/runner.py
|
_tests/macro_testing/runner.py
|
# -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(tests_path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
|
# -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
|
Make the paths not relative, so tests can be run from anywhere.
|
Make the paths not relative, so tests can be run from anywhere.
|
Python
|
cc0-1.0
|
imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh
|
2cde3dbb69077054c6422cbe96e9b996be700d29
|
pulldb/api/subscriptions.py
|
pulldb/api/subscriptions.py
|
import json
import logging
from google.appengine.api import oauth
from google.appengine.ext import ndb
from pulldb import users
from pulldb.api.base import OauthHandler, JsonModel
from pulldb.base import create_app, Route
from pulldb.models.subscriptions import Subscription, subscription_context
class ListSubs(OauthHandler):
def get(self):
user_key = users.user_key(oauth.get_current_user(self.scope))
query = Subscription.query(ancestor=user_key)
results = query.map(subscription_context)
self.response.write(JsonModel().encode(list(results)))
app = create_app([
Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'),
])
|
import json
import logging
from google.appengine.api import oauth
from google.appengine.ext import ndb
from pulldb import users
from pulldb.api.base import OauthHandler, JsonModel
from pulldb.base import create_app, Route
from pulldb.models.subscriptions import Subscription, subscription_context
class ListSubs(OauthHandler):
def get(self):
user_key = users.user_key(self.user)
query = Subscription.query(ancestor=user_key)
results = query.map(subscription_context)
self.response.write(JsonModel().encode(list(results)))
app = create_app([
Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'),
])
|
Make subscription handler less oauth dependant
|
Make subscription handler less oauth dependant
|
Python
|
mit
|
xchewtoyx/pulldb
|
a18eb7509619914cd0565255730ed6bb40f14c9b
|
ovp_users/emails.py
|
ovp_users/emails.py
|
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, user, async_mail=None):
self.user = user
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
class UserMail(BaseMail):
"""
This class is responsible for firing emails for Users
"""
def sendWelcome(self, context={}):
"""
Sent when user registers
"""
return self.sendEmail('welcome', 'Welcome', context)
def sendRecoveryToken(self, context):
"""
Sent when volunteer requests recovery token
"""
return self.sendEmail('recoveryToken', 'Password recovery', context)
|
from ovp_core.emails import BaseMail
class UserMail(BaseMail):
"""
This class is responsible for firing emails for Users
"""
def sendWelcome(self, context={}):
"""
Sent when user registers
"""
return self.sendEmail('welcome', 'Welcome', context)
def sendRecoveryToken(self, context):
"""
Sent when volunteer requests recovery token
"""
return self.sendEmail('recoveryToken', 'Password recovery', context)
|
Move BaseMail from ovp-users to ovp-core
|
Move BaseMail from ovp-users to ovp-core
|
Python
|
agpl-3.0
|
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
|
709d4386a308ce8c0767eab1f2174ec321ea59fd
|
client/main.py
|
client/main.py
|
import requests
import yaml
def runLoop( config ):
"""
Runs indefinitely. On user input (card swipe), will gather the card number,
send it to the server configured, and if it has been authorized, open the
relay with a GPIO call.
"""
while True:
swipe = input()
cardNumber = swipe
print( 'The last input was ' + cardNumber )
try:
res = queryServer( cardNumber, config )
except requests.exceptions.Timeout:
print( "Server timeout!" )
continue
if res['isAuthorized']:
# open the relay here
pass
def queryServer( cardNumber, config ):
url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] )
req = requests.get( url, {
'cardNumber': cardNumber,
'machineID': config['machineID'],
'machineType': config['machineType']
}, timeout=config['timeout'] )
return req.json()
if __name__ == '__main__':
# read and return a yaml file (called 'config.yaml' by default) and give it
# back as a dictionary
with open( 'config.yaml' ) as f:
config = yaml.load( f )
# run the main loop
runLoop( config )
|
import requests
import yaml
def runLoop( config ):
"""
Runs indefinitely. On user input (card swipe), will gather the card number,
send it to the server configured, and if it has been authorized, open the
relay with a GPIO call.
"""
while True:
swipe = input()
cardNumber = swipe
print( 'The last input was ' + cardNumber )
try:
res = requestAuthorization( cardNumber, config )
except requests.exceptions.Timeout:
print( "Server timeout!" )
continue
if res['isAuthorized']:
# open the relay here
pass
def requestAuthorization( cardNumber, config ):
url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] )
path = '/users/checkAuthorization'
req = requests.get( url + path, {
'cardNumber': cardNumber,
'machineID': config['machineID'],
'machineType': config['machineType']
}, timeout=config['timeout'] )
return req.json()
if __name__ == '__main__':
# read and return a yaml file (called 'config.yaml' by default) and give it
# back as a dictionary
with open( 'config.yaml' ) as f:
config = yaml.load( f )
# run the main loop
runLoop( config )
|
Rename funciton to match corresponding HTTP request
|
Rename funciton to match corresponding HTTP request
|
Python
|
mit
|
aradler/Card-lockout,aradler/Card-lockout,aradler/Card-lockout
|
7206d68648c91790ac4fa14a3074c77c97c01636
|
mopidy/backends/base/__init__.py
|
mopidy/backends/base/__init__.py
|
import logging
from .current_playlist import CurrentPlaylistController
from .library import LibraryController, BaseLibraryProvider
from .playback import PlaybackController, BasePlaybackProvider
from .stored_playlists import (StoredPlaylistsController,
BaseStoredPlaylistsProvider)
logger = logging.getLogger('mopidy.backends.base')
class Backend(object):
#: The current playlist controller. An instance of
#: :class:`mopidy.backends.base.CurrentPlaylistController`.
current_playlist = None
#: The library controller. An instance of
# :class:`mopidy.backends.base.LibraryController`.
library = None
#: The sound mixer. An instance of :class:`mopidy.mixers.BaseMixer`.
mixer = None
#: The playback controller. An instance of
#: :class:`mopidy.backends.base.PlaybackController`.
playback = None
#: The stored playlists controller. An instance of
#: :class:`mopidy.backends.base.StoredPlaylistsController`.
stored_playlists = None
#: List of URI prefixes this backend can handle.
uri_handlers = []
|
import logging
from .current_playlist import CurrentPlaylistController
from .library import LibraryController, BaseLibraryProvider
from .playback import PlaybackController, BasePlaybackProvider
from .stored_playlists import (StoredPlaylistsController,
BaseStoredPlaylistsProvider)
logger = logging.getLogger('mopidy.backends.base')
class Backend(object):
#: The current playlist controller. An instance of
#: :class:`mopidy.backends.base.CurrentPlaylistController`.
current_playlist = None
#: The library controller. An instance of
# :class:`mopidy.backends.base.LibraryController`.
library = None
#: The playback controller. An instance of
#: :class:`mopidy.backends.base.PlaybackController`.
playback = None
#: The stored playlists controller. An instance of
#: :class:`mopidy.backends.base.StoredPlaylistsController`.
stored_playlists = None
#: List of URI prefixes this backend can handle.
uri_handlers = []
|
Remove mixer from the Backend API as it is independent
|
Remove mixer from the Backend API as it is independent
|
Python
|
apache-2.0
|
adamcik/mopidy,vrs01/mopidy,pacificIT/mopidy,jmarsik/mopidy,jcass77/mopidy,glogiotatidis/mopidy,kingosticks/mopidy,ZenithDK/mopidy,rawdlite/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,tkem/mopidy,kingosticks/mopidy,jmarsik/mopidy,SuperStarPL/mopidy,bencevans/mopidy,diandiankan/mopidy,quartz55/mopidy,glogiotatidis/mopidy,quartz55/mopidy,priestd09/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,bacontext/mopidy,rawdlite/mopidy,mopidy/mopidy,bencevans/mopidy,pacificIT/mopidy,jodal/mopidy,diandiankan/mopidy,mopidy/mopidy,abarisain/mopidy,tkem/mopidy,SuperStarPL/mopidy,abarisain/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,bacontext/mopidy,adamcik/mopidy,swak/mopidy,ZenithDK/mopidy,quartz55/mopidy,hkariti/mopidy,vrs01/mopidy,ali/mopidy,vrs01/mopidy,woutervanwijk/mopidy,ali/mopidy,jodal/mopidy,dbrgn/mopidy,jmarsik/mopidy,jcass77/mopidy,ali/mopidy,jcass77/mopidy,liamw9534/mopidy,pacificIT/mopidy,hkariti/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,swak/mopidy,adamcik/mopidy,priestd09/mopidy,dbrgn/mopidy,mokieyue/mopidy,kingosticks/mopidy,tkem/mopidy,liamw9534/mopidy,rawdlite/mopidy,quartz55/mopidy,priestd09/mopidy,vrs01/mopidy,ali/mopidy,mokieyue/mopidy,bencevans/mopidy,bencevans/mopidy,mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,jodal/mopidy,mopidy/mopidy,hkariti/mopidy,dbrgn/mopidy,ZenithDK/mopidy,tkem/mopidy,swak/mopidy,bacontext/mopidy,swak/mopidy,mokieyue/mopidy,rawdlite/mopidy,diandiankan/mopidy,hkariti/mopidy,SuperStarPL/mopidy
|
b24af9c3e4105d7acd2e9e13545f24d5a69ae230
|
saleor/product/migrations/0018_auto_20161212_0725.py
|
saleor/product/migrations/0018_auto_20161212_0725.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 13:25
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def create_slugs(apps, schema_editor):
Value = apps.get_model('product', 'AttributeChoiceValue')
for value in Value.objects.all():
value.slug = slugify(value.display)
value.save()
class Migration(migrations.Migration):
dependencies = [
('product', '0017_attributechoicevalue_slug'),
]
operations = [
migrations.RunPython(create_slugs),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 13:25
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def create_slugs(apps, schema_editor):
Value = apps.get_model('product', 'AttributeChoiceValue')
for value in Value.objects.all():
value.slug = slugify(value.display)
value.save()
class Migration(migrations.Migration):
dependencies = [
('product', '0017_attributechoicevalue_slug'),
]
operations = [
migrations.RunPython(create_slugs, migrations.RunPython.noop),
]
|
Allow to revert data migaration
|
Allow to revert data migaration
|
Python
|
bsd-3-clause
|
KenMutemi/saleor,maferelo/saleor,jreigel/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,tfroehlich82/saleor,KenMutemi/saleor,mociepka/saleor,car3oon/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,car3oon/saleor,jreigel/saleor,mociepka/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,tfroehlich82/saleor
|
9d0e9af5844772c18ca24d4012642d4518b66dfc
|
tests/test_judicious.py
|
tests/test_judicious.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import pytest
import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import random
import pytest
import judicious
def test_seeding():
r1 = random.random()
r2 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r3 = random.random()
r4 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r5 = random.random()
r6 = random.random()
judicious.seed()
r7 = random.random()
r8 = random.random()
assert(r1 != r3)
assert(r2 != r4)
assert(r3 == r5)
assert(r4 == r6)
assert(r5 != r7)
assert(r6 != r8)
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
Add test of seeding PRNG
|
Add test of seeding PRNG
|
Python
|
mit
|
suchow/judicious,suchow/judicious,suchow/judicious
|
d46d908f5cfafcb6962207c45f923d3afb7f35a7
|
pyrobus/__init__.py
|
pyrobus/__init__.py
|
from .robot import Robot
from .modules import *
|
import logging
from .robot import Robot
from .modules import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
|
Add null handler as default for logging.
|
Add null handler as default for logging.
|
Python
|
mit
|
pollen/pyrobus
|
c220c0a474a660c4c1167d42fdd0d48599b1b593
|
tests/test_pathutils.py
|
tests/test_pathutils.py
|
from os.path import join
import sublime
import sys
from unittest import TestCase
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
def test_grep_r(self):
pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
from os.path import join, realpath
import os
import sublime
import sys
from unittest import TestCase
from functools import wraps
def subl_patch(pkg, obj=None):
def subl_deco(fn):
@wraps(fn)
def wrap(*args):
nonlocal pkg
o = []
if obj != None:
o += [obj]
pkg = pkg + '.' + obj
try:
mock = __import__(pkg, globals(), locals(), o, 0)
except ImportError:
pkg = realpath(__file__).split(os.sep)[-3] + '.' + pkg
mock = __import__(pkg, globals(), locals(), o, 0)
args += (mock,)
fn(*args)
return wrap
return subl_deco
class TestPathutils(TestCase):
@subl_patch('libsass', 'pathutils')
def test_subpaths(self, pathutils):
path = join('/foo','bar','baz')
exprmt = pathutils.subpaths(path)
expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ]
self.assertEqual(exprmt, expect)
@subl_patch('libsass', 'pathutils')
def test_grep_r(self, pathutils):
pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])]
self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp'])
self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), [])
self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
|
Make custom patch in package to test
|
Make custom patch in package to test
|
Python
|
mit
|
blitzrk/sublime_libsass,blitzrk/sublime_libsass
|
9eddd3b5c4635637faead9d7eae73efd2e324bdb
|
recipes/tests/test_views.py
|
recipes/tests/test_views.py
|
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_inherits_from_base_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'rotd/base.html')
def test_home_page_uses_correct_template(self):
request = HttpRequest()
response = home_page(request)
expected = render_to_string('recipes/home.html')
self.assertEqual(response.content.decode(), expected)
def test_home_page_has_recipe(self):
Recipe.objects.create(name='test')
response = self.client.get('/')
self.assertIsInstance(response.context['recipe'], Recipe)
def test_home_page_shows_any_recipe_name(self):
Recipe.objects.create(name='test recipe')
request = HttpRequest()
response = home_page(request).content.decode()
self.assertTrue(any([(recipe.name in response)
for recipe in Recipe.objects.all()]))
|
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_inherits_from_base_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'rotd/base.html')
def test_home_page_uses_correct_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'recipes/home.html')
def test_home_page_has_recipe(self):
Recipe.objects.create(name='test')
response = self.client.get('/')
self.assertIsInstance(response.context['recipe'], Recipe)
def test_home_page_shows_any_recipe_name(self):
Recipe.objects.create(name='test recipe')
request = HttpRequest()
response = home_page(request).content.decode()
self.assertTrue(any([(recipe.name in response)
for recipe in Recipe.objects.all()]))
|
Use the test client to check all templates for correctness
|
Use the test client to check all templates for correctness
|
Python
|
agpl-3.0
|
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
|
c1edc666630c03b6d85d9749e0695a9f19dd7c13
|
src/collectd_scripts/handle_collectd_notification.py
|
src/collectd_scripts/handle_collectd_notification.py
|
#!/usr/bin/python
import sys
import os
import salt.client
def getNotification():
notification_dict = {}
isEndOfDictionary = False
for line in sys.stdin:
if not line.strip():
isEndOfDictionary = True
continue
if isEndOfDictionary:
break
key, value = line.split(':')
notification_dict[key] = value.lstrip()[:-1]
return notification_dict, line
def postTheNotificationToSaltMaster():
salt_payload = {}
threshold_dict = {}
caller = salt.client.Caller()
threshold_dict['tags'], threshold_dict['message'] = getNotification()
tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format(
threshold_dict['tags']["Host"],
threshold_dict['tags']["Plugin"],
threshold_dict['tags']["Severity"])
caller.sminion.functions['event.send'](tag, threshold_dict)
if __name__ == '__main__':
postTheNotificationToSaltMaster()
|
#!/usr/bin/python
import sys
import os
import salt.client
def getNotification():
notification_dict = {}
isEndOfDictionary = False
for line in sys.stdin:
if not line.strip():
isEndOfDictionary = True
continue
if isEndOfDictionary:
break
key, value = line.split(':')
notification_dict[key] = value.lstrip()[:-1]
return notification_dict, line
def postTheNotificationToSaltMaster():
salt_payload = {}
threshold_dict = {}
caller = salt.client.Caller()
threshold_dict['tags'], threshold_dict['message'] = getNotification()
threshold_dict['severity'] = threshold_dict['tags']["Severity"]
tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format(
threshold_dict['tags']["Host"],
threshold_dict['tags']["Plugin"],
threshold_dict['tags']["Severity"])
caller.sminion.functions['event.send'](tag, threshold_dict)
if __name__ == '__main__':
postTheNotificationToSaltMaster()
|
Fix in collectd event notifier script.
|
Skynet: Fix in collectd event notifier script.
This patch adds a fix to collectd event notifier script,
by providing a value the "severity" field in the event
that it sends to salt-master event bus. with out that
event listener in the skyring server will fail to
process it.
Change-Id: I20b738468c8022a25024e4327434ae6dab43a123
Signed-off-by: nnDarshan <d2c6d450ab98b078f2f1942c995e6d92dd504bc8@gmail.com>
|
Python
|
apache-2.0
|
skyrings/skynet,skyrings/skynet
|
545812b5e31b4894c600b2b172640bea27947db8
|
ecmd-core/pyecmd/test_api.py
|
ecmd-core/pyecmd/test_api.py
|
from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId()
#unit_id_string = unitIdToString(2)
#clock_state = t.queryClockState("SOMECLOCK")
t.relatedTargets("pu.c")
retval = t.queryFileLocationHidden2(ECMD_FILE_SCANDEF, "")
for loc in retval.fileLocations:
testval = loc.textFile + loc.hashFile + retval.version
try:
t.fapi2GetAttr("ATTR_DOES_NOT_EXIST")
assert(""=="That was supposed to throw!")
except KeyError:
pass
t.fapi2SetAttr("ATTR_CHIP_ID", 42)
assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
|
from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId()
#unit_id_string = unitIdToString(2)
#clock_state = t.queryClockState("SOMECLOCK")
t.relatedTargets("pu.c")
retval = t.queryFileLocationHidden2(ECMD_FILE_SCANDEF, "")
for loc in retval.fileLocations:
testval = loc.textFile + loc.hashFile + retval.version
if "fapi2" in extensions:
try:
t.fapi2GetAttr("ATTR_DOES_NOT_EXIST")
assert(""=="That was supposed to throw!")
except KeyError:
pass
t.fapi2SetAttr("ATTR_CHIP_ID", 42)
assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
|
Make fapi2 test conditional on fapi2 being built into ecmd
|
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
|
Python
|
apache-2.0
|
mklight/eCMD,mklight/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD
|
01e9df01bc17561d0f489f1647ce5e0c566372e5
|
flocker/provision/__init__.py
|
flocker/provision/__init__.py
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Provisioning for acceptance tests.
"""
from ._common import PackageSource
from ._install import provision
from ._rackspace import rackspace_provisioner
from ._aws import aws_provisioner
# import digitalocean_provisioner
__all__ = [
'PackageSource', 'provision',
'rackspace_provisioner', 'aws_provisioner'
# digitalocean_provisioner
]
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Provisioning for acceptance tests.
"""
from ._common import PackageSource
from ._install import provision
from ._rackspace import rackspace_provisioner
from ._aws import aws_provisioner
from ._digitalocean import digitalocean_provisioner
__all__ = [
'PackageSource', 'provision',
'rackspace_provisioner', 'aws_provisioner', 'digitalocean_provisioner'
]
|
Make the digitalocean provisioner public
|
Make the digitalocean provisioner public
|
Python
|
apache-2.0
|
wallnerryan/flocker-profiles,1d4Nf6/flocker,hackday-profilers/flocker,moypray/flocker,mbrukman/flocker,hackday-profilers/flocker,agonzalezro/flocker,1d4Nf6/flocker,w4ngyi/flocker,moypray/flocker,agonzalezro/flocker,mbrukman/flocker,adamtheturtle/flocker,moypray/flocker,AndyHuu/flocker,achanda/flocker,lukemarsden/flocker,LaynePeng/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,achanda/flocker,adamtheturtle/flocker,jml/flocker,runcom/flocker,w4ngyi/flocker,agonzalezro/flocker,Azulinho/flocker,LaynePeng/flocker,w4ngyi/flocker,1d4Nf6/flocker,LaynePeng/flocker,runcom/flocker,runcom/flocker,mbrukman/flocker,Azulinho/flocker,lukemarsden/flocker,AndyHuu/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,achanda/flocker,adamtheturtle/flocker,AndyHuu/flocker,jml/flocker,jml/flocker
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.