commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
528edba420089249bd58c0621e06225db84e223f
opps/contrib/logging/models.py
opps/contrib/logging/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, verbose_name=_(u'User') ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) class Meta: verbose_name = _(u'Logging') verbose_name_plural = _(u'Loggings')
Add missing translation on logging contrib app
Add missing translation on logging contrib app
Python
mit
jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps
--- +++ @@ -11,6 +11,7 @@ user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, + verbose_name=_(u'User') ) application = models.CharField( _(u"Application"), @@ -30,3 +31,7 @@ def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) + + class Meta: + verbose_name = _(u'Logging') + verbose_name_plural = _(u'Loggings')
411decbdb193b28bb3060e02e81bfa29483e85a9
staticgen_demo/blog/staticgen_views.py
staticgen_demo/blog/staticgen_views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog:posts_list', ) def _get_paginator(self, url): response = self.client.get(url) print 'status_code: %s' % response.status_code if not response.status_code == 200: pass else: context = {} if hasattr(response, 'context_data'): context = response.context_data elif hasattr(response, 'context'): context = response.context print context try: return context['paginator'], context['is_paginated'] except KeyError: pass return None, False class BlogPostDetailView(StaticgenView): i18n = True def items(self): return Post.objects.all() staticgen_pool.register(BlogPostListView) staticgen_pool.register(BlogPostDetailView)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog:posts_list', ) class BlogPostDetailView(StaticgenView): i18n = True def items(self): return Post.objects.all() staticgen_pool.register(BlogPostListView) staticgen_pool.register(BlogPostDetailView)
Remove debug code from staticgen views.
Remove debug code from staticgen views.
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
--- +++ @@ -15,25 +15,6 @@ def items(self): return ('blog:posts_list', ) - def _get_paginator(self, url): - response = self.client.get(url) - print 'status_code: %s' % response.status_code - if not response.status_code == 200: - pass - else: - context = {} - if hasattr(response, 'context_data'): - context = response.context_data - elif hasattr(response, 'context'): - context = response.context - - print context - try: - return context['paginator'], context['is_paginated'] - except KeyError: - pass - return None, False - class BlogPostDetailView(StaticgenView): i18n = True
673d6cecfaeb0e919f30997f793ee2bb18e399ee
tempest/api_schema/response/compute/v2/hypervisors.py
tempest/api_schema/response/compute/v2/hypervisors.py
# Copyright 2014 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy from tempest.api_schema.response.compute import hypervisors hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail) # Defining extra attributes for V3 show hypervisor schema hypervisors_servers['response_body']['properties']['hypervisors']['items'][ 'properties']['servers'] = { 'type': 'array', 'items': { 'type': 'object', 'properties': { # NOTE: Now the type of 'id' is integer, # but here allows 'string' also because we # will be able to change it to 'uuid' in # the future. 'id': {'type': ['integer', 'string']}, 'name': {'type': 'string'} } } } # In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers' # attribute will not be present in response body So it is not 'required'.
# Copyright 2014 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy from tempest.api_schema.response.compute import hypervisors hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail) # Defining extra attributes for V3 show hypervisor schema hypervisors_servers['response_body']['properties']['hypervisors']['items'][ 'properties']['servers'] = { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'uuid': {'type': 'string'}, 'name': {'type': 'string'} } } } # In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers' # attribute will not be present in response body So it is not 'required'.
Fix V2 hypervisor server schema attribute
Fix V2 hypervisor server schema attribute Nova v2 hypervisor server API return attribute "uuid" in response's server dict. Current response schema does not have this attribute instead it contain "id" which is wrong. This patch fix the above issue. NOTE- "uuid" attribute in this API response is always a uuid. Change-Id: I78c67834de930012b70874938f345524d69264ba
Python
apache-2.0
jaspreetw/tempest,openstack/tempest,Vaidyanath/tempest,vedujoshi/tempest,NexusIS/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,tonyli71/tempest,hayderimran7/tempest,xbezdick/tempest,akash1808/tempest,roopali8/tempest,tudorvio/tempest,alinbalutoiu/tempest,flyingfish007/tempest,manasi24/jiocloud-tempest-qatempest,flyingfish007/tempest,izadorozhna/tempest,afaheem88/tempest_neutron,queria/my-tempest,pczerkas/tempest,afaheem88/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,yamt/tempest,sebrandon1/tempest,bigswitch/tempest,masayukig/tempest,Tesora/tesora-tempest,manasi24/jiocloud-tempest-qatempest,hpcloud-mon/tempest,bigswitch/tempest,ebagdasa/tempest,openstack/tempest,neerja28/Tempest,izadorozhna/tempest,Tesora/tesora-tempest,NexusIS/tempest,jamielennox/tempest,eggmaster/tempest,roopali8/tempest,rzarzynski/tempest,yamt/tempest,queria/my-tempest,rzarzynski/tempest,vedujoshi/tempest,manasi24/tempest,redhat-cip/tempest,Juniper/tempest,varunarya10/tempest,redhat-cip/tempest,hpcloud-mon/tempest,rakeshmi/tempest,masayukig/tempest,JioCloud/tempest,Juniper/tempest,Juraci/tempest,cisco-openstack/tempest,dkalashnik/tempest,LIS/lis-tempest,rakeshmi/tempest,CiscoSystems/tempest,dkalashnik/tempest,nunogt/tempest,Lilywei123/tempest,tudorvio/tempest,tonyli71/tempest,pandeyop/tempest,danielmellado/tempest,neerja28/Tempest,Juraci/tempest,LIS/lis-tempest,JioCloud/tempest,danielmellado/tempest,zsoltdudas/lis-tempest,pczerkas/tempest,zsoltdudas/lis-tempest,eggmaster/tempest,manasi24/tempest,jamielennox/tempest,sebrandon1/tempest,afaheem88/tempest,varunarya10/tempest,afaheem88/tempest_neutron,Lilywei123/tempest,cisco-openstack/tempest,nunogt/tempest,pandeyop/tempest,hayderimran7/tempest,Vaidyanath/tempest,alinbalutoiu/tempest,ebagdasa/tempest,akash1808/tempest,xbezdick/tempest,jaspreetw/tempest,CiscoSystems/tempest
--- +++ @@ -26,11 +26,7 @@ 'items': { 'type': 'object', 'properties': { - # NOTE: Now the type of 'id' is integer, - # but here allows 'string' also because we - # will be able to change it to 'uuid' in - # the future. - 'id': {'type': ['integer', 'string']}, + 'uuid': {'type': 'string'}, 'name': {'type': 'string'} } }
69c6759625c8faacd2ce5194c9845349c61dda7f
tests/py39compat.py
tests/py39compat.py
try: from test.support.os_helpers import FS_NONASCII except ImportError: from test.support import FS_NONASCII # noqa
try: from test.support.os_helper import FS_NONASCII except ImportError: from test.support import FS_NONASCII # noqa
Use os_helper to fix ImportError in Python 3.10
Use os_helper to fix ImportError in Python 3.10
Python
apache-2.0
python/importlib_metadata
--- +++ @@ -1,4 +1,4 @@ try: - from test.support.os_helpers import FS_NONASCII + from test.support.os_helper import FS_NONASCII except ImportError: from test.support import FS_NONASCII # noqa
6de1083784d8a73e234dd14cabd17e7ee5852949
tools/clean_output_directory.py
tools/clean_output_directory.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import shutil import sys import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import shutil import sys import subprocess import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())
Add missing import to utility python script
Add missing import to utility python script BUG= [email protected] Review URL: https://codereview.chromium.org//1222793010.
Python
bsd-3-clause
dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk
--- +++ @@ -7,6 +7,7 @@ import shutil import sys +import subprocess import utils def Main():
13c968f9f345f58775750f1f83ca7881cee2755a
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://pcawg_admin:pcawg@localhost:5432/germline_genotype_tracking') df.to_sql("pcawg_samples", engine)
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://pcawg_admin:[email protected]:5432/germline_genotype_tracking') df.to_sql("pcawg_samples", engine)
Use Tracking DB Service URL rather than localhost in the DB connection string.
Use Tracking DB Service URL rather than localhost in the DB connection string.
Python
mit
llevar/germline-regenotyper,llevar/germline-regenotyper
--- +++ @@ -6,6 +6,6 @@ df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine -engine = create_engine('postgresql://pcawg_admin:pcawg@localhost:5432/germline_genotype_tracking') +engine = create_engine('postgresql://pcawg_admin:[email protected]:5432/germline_genotype_tracking') df.to_sql("pcawg_samples", engine)
fedff2e76d8d96f1ea407f7a3a48aa8dc7a7e50a
analysis/opensimulator-stats-analyzer/src/ostagraph.py
analysis/opensimulator-stats-analyzer/src/ostagraph.py
#!/usr/bin/python import argparse import matplotlib.pyplot as plt from pylab import * from osta.osta import * ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--select', help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")") parser.add_argument( '--out', help = "Path to output the graph rather the interactively display. Filename extension determines graphics type (e.g. \"graph.jpg\")", default = argparse.SUPPRESS) parser.add_argument( 'statsLogPath', help = "Path to the stats log file.", metavar = "stats-log-path") opts = parser.parse_args() osta = Osta() osta.parse(opts.statsLogPath) stat = osta.getStat(opts.select) if not stat == None: plt.plot(stat['abs']['values']) plt.title(stat['fullName']) plt.ylabel(stat['name']) if 'out' in opts: savefig(opts.out) else: plt.show() else: print "No such stat as %s" % (opts.select)
#!/usr/bin/python import argparse import matplotlib.pyplot as plt from pylab import * from osta.osta import * ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--select', help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")") parser.add_argument( '--out', help = "Path to output the graph rather the interactively display. Filename extension determines graphics type (e.g. \"graph.jpg\")", default = argparse.SUPPRESS) parser.add_argument( 'statsLogPath', help = "Path to the stats log file.", metavar = "stats-log-path") opts = parser.parse_args() osta = Osta() osta.parse(opts.statsLogPath) stat = osta.getStat(opts.select) if not stat == None: plt.plot(stat['abs']['values']) plt.title(stat['fullName']) plt.xlabel("samples") plt.ylabel(stat['name']) if 'out' in opts: savefig(opts.out) else: plt.show() else: print "No such stat as %s" % (opts.select)
Make x axis label samples for now, though eventually should have a date option
Make x axis label samples for now, though eventually should have a date option
Python
bsd-3-clause
justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools
--- +++ @@ -34,6 +34,7 @@ if not stat == None: plt.plot(stat['abs']['values']) plt.title(stat['fullName']) + plt.xlabel("samples") plt.ylabel(stat['name']) if 'out' in opts:
114b3f3403e970943618e7096b0b898b8aa5589f
microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py
microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py
from datetime import datetime import logging from path_helpers import path from pip_helpers import install if __name__ == '__main__': logging.basicConfig(level=logging.INFO) logging.info(str(datetime.now())) requirements_file = path(__file__).parent.joinpath('requirements.txt') if requirements_file.exists(): logging.info(install(['-U', '-r', requirements_file], verbose=True))
from datetime import datetime import logging from path_helpers import path from pip_helpers import install if __name__ == '__main__': logging.basicConfig(level=logging.INFO) logging.info(str(datetime.now())) requirements_file = path(__file__).parent.joinpath('requirements.txt') if requirements_file.exists(): logging.info(install(['-U', '-r', requirements_file]))
Remove verbose keywork for pip install
Remove verbose keywork for pip install
Python
bsd-3-clause
wheeler-microfluidics/microdrop
--- +++ @@ -10,4 +10,4 @@ logging.info(str(datetime.now())) requirements_file = path(__file__).parent.joinpath('requirements.txt') if requirements_file.exists(): - logging.info(install(['-U', '-r', requirements_file], verbose=True)) + logging.info(install(['-U', '-r', requirements_file]))
a35c2c4e3d332c8ee581608317c4496722fb9b77
us_ignite/advertising/models.py
us_ignite/advertising/models.py
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), (DRAFT, 'Draft'), (REMOVED, 'Removed'), ) name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='name') status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT) url = models.URLField(max_length=500) image = models.ImageField(upload_to="ads") is_featured = models.BooleanField( default=False, help_text='Marking this Advert as featured will publish' ' it and show it on the site.') created = CreationDateTimeField() modified = ModificationDateTimeField() # managers: objects = models.Manager() published = managers.AdvertPublishedManager() class Meta: ordering = ('-is_featured', '-created') def __unicode__(self): return self.name
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), (DRAFT, 'Draft'), (REMOVED, 'Removed'), ) name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='name') status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT) url = models.URLField(max_length=500) image = models.ImageField(upload_to="featured") is_featured = models.BooleanField( default=False, help_text='Marking this Advert as featured will publish' ' it and show it on the site.') created = CreationDateTimeField() modified = ModificationDateTimeField() # managers: objects = models.Manager() published = managers.AdvertPublishedManager() class Meta: ordering = ('-is_featured', '-created') def __unicode__(self): return self.name
Update wording on path of the image.
Update wording on path of the image.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
--- +++ @@ -20,7 +20,7 @@ slug = AutoSlugField(populate_from='name') status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT) url = models.URLField(max_length=500) - image = models.ImageField(upload_to="ads") + image = models.ImageField(upload_to="featured") is_featured = models.BooleanField( default=False, help_text='Marking this Advert as featured will publish' ' it and show it on the site.')
aaa88075d4cf799509584de439f207476e092584
doc/conf.py
doc/conf.py
import os import sys import qirest extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo'] autoclass_content = "both" autodoc_default_flags= ['members', 'show-inheritance'] source_suffix = '.rst' master_doc = 'index' project = u'qirest' copyright = u'2014, OHSU Knight Cancer Institute. This software is not intended for clinical use' pygments_style = 'sphinx' htmlhelp_basename = 'qirestdoc' html_title = "qirest" def skip(app, what, name, obj, skip, options): return False if name == "__init__" else skip def setup(app): app.connect("autodoc-skip-member", skip)
import os import sys try: import qirest except ImportError: # A ReadTheDocs build does not install qirest. In that case, # load the module directly. src_dir = os.path.join(os.path.dirname(__file__), '..') sys.path.append(src_dir) import qirest extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo'] autoclass_content = "both" autodoc_default_flags= ['members', 'show-inheritance'] source_suffix = '.rst' master_doc = 'index' project = u'qirest' copyright = u'2014, OHSU Knight Cancer Institute. This software is not intended for clinical use' pygments_style = 'sphinx' htmlhelp_basename = 'qirestdoc' html_title = "qirest" def skip(app, what, name, obj, skip, options): return False if name == "__init__" else skip def setup(app): app.connect("autodoc-skip-member", skip)
Use alternate import for RTD.
Use alternate import for RTD.
Python
bsd-2-clause
ohsu-qin/qiprofile-rest,ohsu-qin/qirest
--- +++ @@ -1,6 +1,13 @@ import os import sys -import qirest +try: + import qirest +except ImportError: + # A ReadTheDocs build does not install qirest. In that case, + # load the module directly. + src_dir = os.path.join(os.path.dirname(__file__), '..') + sys.path.append(src_dir) + import qirest extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo'] autoclass_content = "both"
0ac28421fe8ed4234db13ebdbb95c700191ba042
bugle_project/bugle/templatetags/bugle.py
bugle_project/bugle/templatetags/bugle.py
from django import template from django.contrib.auth.models import User from django.utils.safestring import mark_safe import re import urllib register = template.Library() username_re = re.compile('@[0-9a-zA-Z]+') hashtag_re = re.compile('(?:^|\s)(#\S+)') @register.filter def buglise(s): s = unicode(s) usernames = set(User.objects.values_list('username', flat=True)) def replace_username(match): username = match.group(0)[1:] if username.lower() == 'all': return '<strong>@all</strong>' if username in usernames: return '<a href="/%s/">@%s</a>' % (username, username) else: return '@' + username s = username_re.sub(replace_username, s) s = hashtag_re.sub( lambda m: '<a href="/search/?q=%s">%s</a>' % ( urllib.quote(m.group(0)), m.group(0), ), s ) return mark_safe(s)
from django import template from django.contrib.auth.models import User from django.utils.safestring import mark_safe import re import urllib register = template.Library() username_re = re.compile('@[0-9a-zA-Z]+') hashtag_re = re.compile('(^|\s)(#\S+)') @register.filter def buglise(s): s = unicode(s) usernames = set(User.objects.values_list('username', flat=True)) def replace_username(match): username = match.group(0)[1:] if username.lower() == 'all': return '<strong>@all</strong>' if username in usernames: return '<a href="/%s/">@%s</a>' % (username, username) else: return '@' + username s = username_re.sub(replace_username, s) s = hashtag_re.sub( lambda m: '%s<a href="/search/?q=%s">%s</a>' % ( m.group(1), urllib.quote(m.group(2)), m.group(2), ), s ) return mark_safe(s)
Remove spaces from hash tag links
Remove spaces from hash tag links
Python
bsd-2-clause
devfort/bugle,devfort/bugle,simonw/bugle_project,devfort/bugle,simonw/bugle_project
--- +++ @@ -7,7 +7,7 @@ register = template.Library() username_re = re.compile('@[0-9a-zA-Z]+') -hashtag_re = re.compile('(?:^|\s)(#\S+)') +hashtag_re = re.compile('(^|\s)(#\S+)') @register.filter def buglise(s): @@ -26,9 +26,10 @@ s = username_re.sub(replace_username, s) s = hashtag_re.sub( - lambda m: '<a href="/search/?q=%s">%s</a>' % ( - urllib.quote(m.group(0)), - m.group(0), + lambda m: '%s<a href="/search/?q=%s">%s</a>' % ( + m.group(1), + urllib.quote(m.group(2)), + m.group(2), ), s )
7a78525bb8cc6176dfbe348e5f95373c1d70628f
functions.py
functions.py
#-*- coding: utf-8 -*- def getClientIP( req ): ''' Get the client ip address ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string ''' if val: return str(val).upper() in trueOpts return False
#-*- coding: utf-8 -*- def getClientIP( req ): ''' Get the client ip address @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string @param val The value to be parse to bool @param defVal The default value if the val is None @param trueOpts The available values of TRUE ''' if val: return str(val).upper() in trueOpts return defVal def checkRecaptcha( req, secret, simple=True ): ''' Checking the recaptcha and return the result. @param req The request; @param secret The secret retreived from Google reCaptcha registration; @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; ''' import requests apiurl='https://www.google.com/recaptcha/api/siteverify' fieldname='g-recaptcha-response' answer=req.POST.get(fieldname, None) clientIP=getClientIP( req ) rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() if simple: return getBool(rst.get('success', 'False')) return r.json()
Add the checkRecaptcha( req, secret, simple=True ) function
Add the checkRecaptcha( req, secret, simple=True ) function
Python
apache-2.0
kensonman/webframe,kensonman/webframe,kensonman/webframe
--- +++ @@ -3,6 +3,8 @@ def getClientIP( req ): ''' Get the client ip address + + @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: @@ -11,10 +13,34 @@ ip=req.META.get('REMOTE_ADDR') return ip -def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): +def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string + + @param val The value to be parse to bool + @param defVal The default value if the val is None + @param trueOpts The available values of TRUE ''' if val: return str(val).upper() in trueOpts - return False + return defVal + +def checkRecaptcha( req, secret, simple=True ): + ''' + Checking the recaptcha and return the result. + + @param req The request; + @param secret The secret retreived from Google reCaptcha registration; + @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; + ''' + import requests + apiurl='https://www.google.com/recaptcha/api/siteverify' + fieldname='g-recaptcha-response' + + answer=req.POST.get(fieldname, None) + clientIP=getClientIP( req ) + rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() + if simple: + return getBool(rst.get('success', 'False')) + return r.json() +
f2f74f53fe8f5b4ac4cd728c4181b3a66b4e873d
euler009.py
euler009.py
# euler 009 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
# Project Euler # 9 - Special Pythagorean triplet # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
Change problem description so it actually makes sense
Change problem description so it actually makes sense
Python
mit
josienb/project_euler,josienb/project_euler
--- +++ @@ -1,10 +1,11 @@ -# euler 009 +# Project Euler +# 9 - Special Pythagorean triplet # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # -# For example, 32 + 42 = 9 + 16 = 25 = 52. -# +# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. +# # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
87f892731678049b5a706a36487982ebb9da3991
pybossa_discourse/globals.py
pybossa_discourse/globals.py
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app.jinja_env.globals.update(discourse=self) def comments(self): """Return an HTML snippet used to embed Discourse comments.""" return Markup(""" <div id="discourse-comments"></div> <script type="text/javascript"> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """).format(self.url, request.base_url) def notifications(self): """Return a count of unread notifications for the current user.""" notifications = discourse_client.user_notifications() if not notifications: return 0 return sum([1 for n in notifications['notifications'] if not n['read']])
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] self.api = discourse_client app.jinja_env.globals.update(discourse=self) def comments(self): """Return an HTML snippet used to embed Discourse comments.""" return Markup(""" <div id="discourse-comments"></div> <script type="text/javascript"> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """).format(self.url, request.base_url) def notifications(self): """Return a count of unread notifications for the current user.""" notifications = discourse_client.user_notifications() if not notifications: return 0 return sum([1 for n in notifications['notifications'] if not n['read']])
Add API client to global envar
Add API client to global envar
Python
bsd-3-clause
alexandermendes/pybossa-discourse
--- +++ @@ -10,6 +10,7 @@ def __init__(self, app): self.url = app.config['DISCOURSE_URL'] + self.api = discourse_client app.jinja_env.globals.update(discourse=self) def comments(self):
edb07b507aa93ead278cecd168da83a4be68b2ba
bluebottle/settings/travis.py
bluebottle/settings/travis.py
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # # Disable Selenium testing for now on Travis because it fails inconsistent. # SELENIUM_TESTS = True
Disable front-end testing on Travis
Disable front-end testing on Travis Travis has dificulty running the front-end tests. For now we'll disable them.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
--- +++ @@ -15,4 +15,5 @@ # Put the travis-ci environment specific overrides below. # -SELENIUM_TESTS = True +# Disable Selenium testing for now on Travis because it fails inconsistent. +# SELENIUM_TESTS = True
f3f428480a8e61bf22532503680e718fd5f0d286
fb/views.py
fb/views.py
from django.shortcuts import render # Create your views here.
from django.shortcuts import render from fb.models import UserPost def index(request): if request.method == 'GET': posts = UserPost.objects.all() context = { 'posts': posts, } return render(request, 'index.html', context)
Write the first view - news feed.
Write the first view - news feed.
Python
apache-2.0
pure-python/brainmate
--- +++ @@ -1,3 +1,12 @@ from django.shortcuts import render -# Create your views here. +from fb.models import UserPost + + +def index(request): + if request.method == 'GET': + posts = UserPost.objects.all() + context = { + 'posts': posts, + } + return render(request, 'index.html', context)
e978b8be7ccfd9206d618f5a3de855a306ceccfe
test.py
test.py
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('U', rotor.encode_reverse('A')) def test_rotor_different_setting(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', setting='B') self.assertEqual('K', rotor.encode('A')) self.assertEqual('K', rotor.encode_reverse('A')) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('U', rotor.encode_reverse('A')) def test_rotor_different_setting(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', setting='B') self.assertEqual('K', rotor.encode('A')) self.assertEqual('K', rotor.encode_reverse('A')) def test_rotor_different_offset(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', offset='B') self.assertEqual('D', rotor.encode('A')) self.assertEqual('W', rotor.encode_reverse('A')) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
Test if rotor encodes with different offset properly
Test if rotor encodes with different offset properly
Python
mit
ranisalt/enigma
--- +++ @@ -19,6 +19,12 @@ self.assertEqual('K', rotor.encode('A')) self.assertEqual('K', rotor.encode_reverse('A')) + def test_rotor_different_offset(self): + rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', + offset='B') + self.assertEqual('D', rotor.encode('A')) + self.assertEqual('W', rotor.encode_reverse('A')) + def run_tests(): runner = unittest.TextTestRunner()
691093e38598959f98b319f7c57852496a26ba90
apps/careers/models.py
apps/careers/models.py
import watson from cms.apps.pages.models import ContentBase from cms.models import HtmlField, SearchMetaBase from django.db import models class Careers(ContentBase): # The heading that the admin places this content under. classifier = "apps" # The urlconf used to power this content's views. urlconf = "phixflow.apps.careers.urls" standfirst = models.TextField( blank=True, null=True ) per_page = models.IntegerField( "careers per page", default=5, blank=True, null=True ) def __unicode__(self): return self.page.title class Career(SearchMetaBase): page = models.ForeignKey( Careers ) title = models.CharField( max_length=256, ) slug = models.CharField( max_length=256, unique=True ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ('order',) def __unicode__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career', kwargs={ 'slug': self.slug, }) watson.register(Career)
import watson from cms.apps.pages.models import ContentBase from cms.models import HtmlField, SearchMetaBase from django.db import models class Careers(ContentBase): # The heading that the admin places this content under. classifier = "apps" # The urlconf used to power this content's views. urlconf = "{{ project_name }}.apps.careers.urls" standfirst = models.TextField( blank=True, null=True ) per_page = models.IntegerField( "careers per page", default=5, blank=True, null=True ) def __unicode__(self): return self.page.title class Career(SearchMetaBase): page = models.ForeignKey( Careers ) title = models.CharField( max_length=256, ) slug = models.CharField( max_length=256, unique=True ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ('order',) def __unicode__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career', kwargs={ 'slug': self.slug, }) watson.register(Career)
Fix project name in urlconf
Fix project name in urlconf
Python
mit
onespacemedia/cms-jobs,onespacemedia/cms-jobs
--- +++ @@ -10,7 +10,7 @@ classifier = "apps" # The urlconf used to power this content's views. - urlconf = "phixflow.apps.careers.urls" + urlconf = "{{ project_name }}.apps.careers.urls" standfirst = models.TextField( blank=True,
88e0ec5ff58f7dabb531749472a410498c8e7827
py_skiplist/iterators.py
py_skiplist/iterators.py
from itertools import dropwhile, count, cycle import random def geometric(p): return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1])) def uniform(n): """ Simple deterministic distribution for testing internal of the skiplist """ return (n for _ in cycle([1]))
from itertools import dropwhile, count, repeat import random def geometric(p): return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1)) # Simple deterministic distribution for testing internals of the skiplist. uniform = repeat
Use itertools.repeat over slower alternatives.
Use itertools.repeat over slower alternatives.
Python
mit
ZhukovAlexander/skiplist-python
--- +++ @@ -1,13 +1,10 @@ -from itertools import dropwhile, count, cycle +from itertools import dropwhile, count, repeat import random def geometric(p): - return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1])) + return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1)) -def uniform(n): - """ - Simple deterministic distribution for testing internal of the skiplist - """ - return (n for _ in cycle([1])) +# Simple deterministic distribution for testing internals of the skiplist. +uniform = repeat
52d65ff926a079b4e07e8bc0fda3e3c3fe8f9437
thumbor/detectors/queued_detector/__init__.py
thumbor/detectors/queued_detector/__init__.py
from remotecv import pyres_tasks from remotecv.unique_queue import UniqueQueue from thumbor.detectors import BaseDetector class QueuedDetector(BaseDetector): queue = UniqueQueue() def detect(self, callback): engine = self.context.modules.engine self.queue.enqueue_unique(pyres_tasks.DetectTask, args=[self.detection_type, self.context.request.image_url], key=self.context.request.image_url) self.context.prevent_result_storage = True callback([])
from remotecv.unique_queue import UniqueQueue from thumbor.detectors import BaseDetector class QueuedDetector(BaseDetector): queue = UniqueQueue() def detect(self, callback): engine = self.context.modules.engine self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect', args=[self.detection_type, self.context.request.image_url], key=self.context.request.image_url) self.context.prevent_result_storage = True callback([])
Remove dependency from remotecv worker on queued detector
Remove dependency from remotecv worker on queued detector
Python
mit
fanhero/thumbor,fanhero/thumbor,fanhero/thumbor,fanhero/thumbor
--- +++ @@ -1,4 +1,3 @@ -from remotecv import pyres_tasks from remotecv.unique_queue import UniqueQueue from thumbor.detectors import BaseDetector @@ -8,7 +7,7 @@ def detect(self, callback): engine = self.context.modules.engine - self.queue.enqueue_unique(pyres_tasks.DetectTask, + self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect', args=[self.detection_type, self.context.request.image_url], key=self.context.request.image_url) self.context.prevent_result_storage = True
c9f8663e6b0bf38f6c041a3a6b77b8a0007a9f09
urls.py
urls.py
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.views.generic.simple import direct_to_template admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^i4p/', include('i4p.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^$', direct_to_template, {'template' : 'base.html'}), (r'^accounts/', include('registration.backends.default.urls')), )
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.views.generic.simple import direct_to_template admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^i4p/', include('i4p.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), url(r'^$', direct_to_template, {'template' : 'base.html'}, name="i4p-index"), (r'^accounts/', include('registration.backends.default.urls')), )
Add a name to the index URL
Add a name to the index URL
Python
agpl-3.0
ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople
--- +++ @@ -14,6 +14,6 @@ # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), - (r'^$', direct_to_template, {'template' : 'base.html'}), + url(r'^$', direct_to_template, {'template' : 'base.html'}, name="i4p-index"), (r'^accounts/', include('registration.backends.default.urls')), )
73ff56f4b8859e82b0d69a6505c982e26de27859
util.py
util.py
def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
import colorsys import random def randcolor(): hue = random.random() sat = random.randint(700, 1000) / 1000 val = random.randint(700, 1000) / 1000 return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
Add randcolor function to uitl
Add randcolor function to uitl
Python
unlicense
joseph346/cellular
--- +++ @@ -1,3 +1,11 @@ +import colorsys +import random + +def randcolor(): + hue = random.random() + sat = random.randint(700, 1000) / 1000 + val = random.randint(700, 1000) / 1000 + return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1
7801c5d7430233eb78ab8b2a91f5960bd808b2c7
app/admin/views.py
app/admin/views.py
from flask import Blueprint, render_template from flask_security import login_required admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') @login_required def index(): return render_template('admin/index.html', title='Admin')
from flask import Blueprint, render_template, redirect, url_for from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') def index(): return render_template('admin/index.html', title='Admin') @admin.before_request def require_login(): if not current_user.is_authenticated: return redirect(url_for('security.login', next='admin'))
Move admin authentication into before_request handler
Move admin authentication into before_request handler
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
--- +++ @@ -1,11 +1,16 @@ -from flask import Blueprint, render_template -from flask_security import login_required +from flask import Blueprint, render_template, redirect, url_for +from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') -@login_required def index(): return render_template('admin/index.html', title='Admin') + + [email protected]_request +def require_login(): + if not current_user.is_authenticated: + return redirect(url_for('security.login', next='admin'))
6ce14f21cec2c37939f68aaf40d5227c80636e53
app_bikes/forms.py
app_bikes/forms.py
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),) def validate_unique(self): super(BikeModelForm, self).validate_unique() if self.errors and 'id_station' in self.data: # A station was chosen, reinit choices with it self.fields['id_station'].widget.choices = ((self.cleaned_data['id_station'], self.data['station']),) class Meta: widgets = { 'id_station': autocomplete.ListSelect2(url='station-autocomplete', forward=('provider',), attrs={'data-allow-clear': 'false'}) } class Media: js = ('js/admin_form.js',)
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),) def validate_unique(self): """If the form had an error and a station was chosen, we need to setup the widget choices to the previously selected value for the autocomplete to display it properly""" super(BikeModelForm, self).validate_unique() if self.errors and 'id_station' in self.data: self.fields['id_station'].widget.choices = ((self.cleaned_data['id_station'], self.data['station']),) class Meta: widgets = { 'id_station': autocomplete.ListSelect2(url='station-autocomplete', forward=('provider',), attrs={'data-allow-clear': 'false'}) } class Media: js = ('js/admin_form.js',)
Add docstring to explain the code
Add docstring to explain the code
Python
agpl-3.0
laboiteproject/laboite-backend,laboiteproject/laboite-backend,bgaultier/laboitepro,bgaultier/laboitepro,bgaultier/laboitepro,laboiteproject/laboite-backend
--- +++ @@ -10,9 +10,9 @@ self.fields['id_station'].widget.choices = ((self.instance.id_station, self.instance.station),) def validate_unique(self): + """If the form had an error and a station was chosen, we need to setup the widget choices to the previously selected value for the autocomplete to display it properly""" super(BikeModelForm, self).validate_unique() if self.errors and 'id_station' in self.data: - # A station was chosen, reinit choices with it self.fields['id_station'].widget.choices = ((self.cleaned_data['id_station'], self.data['station']),) class Meta:
0b1f38b8354a0ad6a021f247a7bc1336ae5d50fb
arcade/__init__.py
arcade/__init__.py
""" The Arcade Library A Python simple, easy to use module for creating 2D games. """ import arcade.key import arcade.color from .version import * from .window_commands import * from .draw_commands import * from .sprite import * from .physics_engines import * from .physics_engine_2d import * from .application import * from .sound import * from .shape_objects import *
""" The Arcade Library A Python simple, easy to use module for creating 2D games. """ import arcade.key import arcade.color from arcade.version import * from arcade.window_commands import * from arcade.draw_commands import * from arcade.sprite import * from arcade.physics_engines import * from arcade.physics_engine_2d import * from arcade.application import * from arcade.sound import * from arcade.shape_objects import *
Change some of the relative imports, which fail in doctests, to absolute imports.
Change some of the relative imports, which fail in doctests, to absolute imports.
Python
mit
mikemhenry/arcade,mikemhenry/arcade
--- +++ @@ -6,12 +6,12 @@ import arcade.key import arcade.color -from .version import * -from .window_commands import * -from .draw_commands import * -from .sprite import * -from .physics_engines import * -from .physics_engine_2d import * -from .application import * -from .sound import * -from .shape_objects import * +from arcade.version import * +from arcade.window_commands import * +from arcade.draw_commands import * +from arcade.sprite import * +from arcade.physics_engines import * +from arcade.physics_engine_2d import * +from arcade.application import * +from arcade.sound import * +from arcade.shape_objects import *
ed4f786de54dde50cb26cfe4859507579806a14b
portal_sale_distributor/models/ir_action_act_window.py
portal_sale_distributor/models/ir_action_act_window.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, api from odoo.tools.safe_eval import safe_eval class ActWindowView(models.Model): _inherit = 'ir.actions.act_window' def read(self, fields=None, load='_classic_read'): result = super().read(fields, load=load) if result and result[0].get('context'): ctx = safe_eval(result[0].get('context', '{}')) if ctx.get('portal_products'): pricelist = self.env.user.partner_id.property_product_pricelist ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id}) result[0].update({'context': ctx}) return result
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, api from odoo.tools.safe_eval import safe_eval class ActWindowView(models.Model): _inherit = 'ir.actions.act_window' def read(self, fields=None, load='_classic_read'): result = super().read(fields, load=load) for value in result: if value.get('context') and 'portal_products' in value.get('context'): eval_ctx = dict(self.env.context) try: ctx = safe_eval(value.get('context', '{}'), eval_ctx) except: ctx = {} pricelist = self.env.user.partner_id.property_product_pricelist ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id.id}) value.update({'context': str(ctx)}) return result
Adjust to avoid bugs with other values in context
[FIX] portal_sale_distributor: Adjust to avoid bugs with other values in context closes ingadhoc/sale#493 X-original-commit: 441d30af0c3fa8cbbe129893107436ea69cca740 Signed-off-by: Juan José Scarafía <[email protected]>
Python
agpl-3.0
ingadhoc/sale,ingadhoc/sale,ingadhoc/sale,ingadhoc/sale
--- +++ @@ -11,10 +11,14 @@ def read(self, fields=None, load='_classic_read'): result = super().read(fields, load=load) - if result and result[0].get('context'): - ctx = safe_eval(result[0].get('context', '{}')) - if ctx.get('portal_products'): + for value in result: + if value.get('context') and 'portal_products' in value.get('context'): + eval_ctx = dict(self.env.context) + try: + ctx = safe_eval(value.get('context', '{}'), eval_ctx) + except: + ctx = {} pricelist = self.env.user.partner_id.property_product_pricelist - ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id}) - result[0].update({'context': ctx}) + ctx.update({'pricelist': pricelist.id, 'partner': self.env.user.partner_id.id}) + value.update({'context': str(ctx)}) return result
cf0d928cffc86e7ba2a68a7e95c54c7e530d2da8
packages/Python/lldbsuite/test/lang/swift/accelerate_simd/TestAccelerateSIMD.py
packages/Python/lldbsuite/test/lang/swift/accelerate_simd/TestAccelerateSIMD.py
# TestAccelerateSIMD.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ------------------------------------------------------------------------------ import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest,skipUnlessDarwin])
# TestAccelerateSIMD.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ------------------------------------------------------------------------------ import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest,skipUnlessDarwin, skipIf(bugnumber=46330565)])
Disable accelerate_simd test for now.
Disable accelerate_simd test for now.
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
--- +++ @@ -13,4 +13,5 @@ from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), - decorators=[swiftTest,skipUnlessDarwin]) + decorators=[swiftTest,skipUnlessDarwin, + skipIf(bugnumber=46330565)])
4f3234433b97e7f243d54e9e95399f5cabecd315
common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py
common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.RemoveField( model_name='coursemode', name='expiration_datetime', ), migrations.AddField( model_name='coursemode', name='_expiration_datetime', field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.SeparateDatabaseAndState( database_operations=[], state_operations=[ migrations.RemoveField( model_name='coursemode', name='expiration_datetime', ), migrations.AddField( model_name='coursemode', name='_expiration_datetime', field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), ), ] ) ]
Change broken course_modes migration to not touch the database.
Change broken course_modes migration to not touch the database. Changing a field name in the way that we did (updating the Python variable name and switching it to point to the old DB column) confuses Django's migration autodetector. No DB changes are actually necessary, but it thinks that a field has been removed and a new one added. This means that Django will ask users to generate the migration it thinks is necessary, which ended up with us dropping data. The fix is to run the same migration on Django's internal model of the DB state, but not actually touch the DB.
Python
agpl-3.0
antoviaque/edx-platform,pepeportela/edx-platform,edx/edx-platform,teltek/edx-platform,ahmedaljazzar/edx-platform,mitocw/edx-platform,edx-solutions/edx-platform,hastexo/edx-platform,IndonesiaX/edx-platform,pepeportela/edx-platform,Lektorium-LLC/edx-platform,mitocw/edx-platform,marcore/edx-platform,romain-li/edx-platform,philanthropy-u/edx-platform,amir-qayyum-khan/edx-platform,angelapper/edx-platform,UOMx/edx-platform,jzoldak/edx-platform,10clouds/edx-platform,defance/edx-platform,antoviaque/edx-platform,Edraak/edraak-platform,JioEducation/edx-platform,10clouds/edx-platform,tanmaykm/edx-platform,Stanford-Online/edx-platform,Lektorium-LLC/edx-platform,raccoongang/edx-platform,pabloborrego93/edx-platform,ESOedX/edx-platform,defance/edx-platform,analyseuc3m/ANALYSE-v1,ahmedaljazzar/edx-platform,edx-solutions/edx-platform,mbareta/edx-platform-ft,cecep-edu/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,MakeHer/edx-platform,jjmiranda/edx-platform,teltek/edx-platform,edx-solutions/edx-platform,CourseTalk/edx-platform,franosincic/edx-platform,solashirai/edx-platform,franosincic/edx-platform,CredoReference/edx-platform,CredoReference/edx-platform,caesar2164/edx-platform,pepeportela/edx-platform,kmoocdev2/edx-platform,marcore/edx-platform,naresh21/synergetics-edx-platform,philanthropy-u/edx-platform,solashirai/edx-platform,franosincic/edx-platform,arbrandes/edx-platform,philanthropy-u/edx-platform,gymnasium/edx-platform,analyseuc3m/ANALYSE-v1,ampax/edx-platform,franosincic/edx-platform,MakeHer/edx-platform,louyihua/edx-platform,alu042/edx-platform,waheedahmed/edx-platform,angelapper/edx-platform,lduarte1991/edx-platform,synergeticsedx/deployment-wipro,cpennington/edx-platform,EDUlib/edx-platform,teltek/edx-platform,Endika/edx-platform,philanthropy-u/edx-platform,a-parhom/edx-platform,TeachAtTUM/edx-platform,synergeticsedx/deployment-wipro,jolyonb/edx-platform,kmoocdev2/edx-platform,deepsrijit1105/edx-platform,eduNEXT/edx-platform,shabab12/edx-platform,procangroup/edx-platform,cpennington/edx-platform,wwj718/edx-platform,ESOedX/edx-platform,fintech-circle/edx-platform,lduarte1991/edx-platform,proversity-org/edx-platform,teltek/edx-platform,shabab12/edx-platform,raccoongang/edx-platform,EDUlib/edx-platform,msegado/edx-platform,defance/edx-platform,mitocw/edx-platform,a-parhom/edx-platform,caesar2164/edx-platform,a-parhom/edx-platform,proversity-org/edx-platform,waheedahmed/edx-platform,JioEducation/edx-platform,cpennington/edx-platform,alu042/edx-platform,franosincic/edx-platform,edx/edx-platform,analyseuc3m/ANALYSE-v1,CredoReference/edx-platform,wwj718/edx-platform,doganov/edx-platform,Livit/Livit.Learn.EdX,devs1991/test_edx_docmode,10clouds/edx-platform,solashirai/edx-platform,ESOedX/edx-platform,eduNEXT/edx-platform,gymnasium/edx-platform,defance/edx-platform,prarthitm/edxplatform,cecep-edu/edx-platform,procangroup/edx-platform,tanmaykm/edx-platform,msegado/edx-platform,wwj718/edx-platform,synergeticsedx/deployment-wipro,jolyonb/edx-platform,devs1991/test_edx_docmode,analyseuc3m/ANALYSE-v1,devs1991/test_edx_docmode,chrisndodge/edx-platform,caesar2164/edx-platform,alu042/edx-platform,Endika/edx-platform,waheedahmed/edx-platform,JioEducation/edx-platform,Stanford-Online/edx-platform,edx/edx-platform,Endika/edx-platform,IndonesiaX/edx-platform,mbareta/edx-platform-ft,longmen21/edx-platform,naresh21/synergetics-edx-platform,longmen21/edx-platform,TeachAtTUM/edx-platform,jjmiranda/edx-platform,gsehub/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,jzoldak/edx-platform,prarthitm/edxplatform,itsjeyd/edx-platform,angelapper/edx-platform,jzoldak/edx-platform,chrisndodge/edx-platform,Lektorium-LLC/edx-platform,solashirai/edx-platform,Endika/edx-platform,doganov/edx-platform,UOMx/edx-platform,cecep-edu/edx-platform,naresh21/synergetics-edx-platform,eduNEXT/edx-platform,ampax/edx-platform,shabab12/edx-platform,CourseTalk/edx-platform,ESOedX/edx-platform,BehavioralInsightsTeam/edx-platform,CredoReference/edx-platform,appsembler/edx-platform,prarthitm/edxplatform,fintech-circle/edx-platform,MakeHer/edx-platform,hastexo/edx-platform,procangroup/edx-platform,amir-qayyum-khan/edx-platform,cecep-edu/edx-platform,Livit/Livit.Learn.EdX,miptliot/edx-platform,UOMx/edx-platform,IndonesiaX/edx-platform,devs1991/test_edx_docmode,procangroup/edx-platform,hastexo/edx-platform,pepeportela/edx-platform,miptliot/edx-platform,proversity-org/edx-platform,ahmedaljazzar/edx-platform,wwj718/edx-platform,romain-li/edx-platform,gsehub/edx-platform,synergeticsedx/deployment-wipro,10clouds/edx-platform,amir-qayyum-khan/edx-platform,gsehub/edx-platform,Livit/Livit.Learn.EdX,fintech-circle/edx-platform,BehavioralInsightsTeam/edx-platform,devs1991/test_edx_docmode,IndonesiaX/edx-platform,MakeHer/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,Livit/Livit.Learn.EdX,amir-qayyum-khan/edx-platform,angelapper/edx-platform,pabloborrego93/edx-platform,eduNEXT/edx-platform,gsehub/edx-platform,chrisndodge/edx-platform,devs1991/test_edx_docmode,TeachAtTUM/edx-platform,eduNEXT/edunext-platform,itsjeyd/edx-platform,solashirai/edx-platform,TeachAtTUM/edx-platform,a-parhom/edx-platform,jzoldak/edx-platform,antoviaque/edx-platform,lduarte1991/edx-platform,edx/edx-platform,doganov/edx-platform,devs1991/test_edx_docmode,miptliot/edx-platform,longmen21/edx-platform,ampax/edx-platform,edx-solutions/edx-platform,jolyonb/edx-platform,arbrandes/edx-platform,proversity-org/edx-platform,miptliot/edx-platform,marcore/edx-platform,CourseTalk/edx-platform,waheedahmed/edx-platform,BehavioralInsightsTeam/edx-platform,romain-li/edx-platform,ampax/edx-platform,appsembler/edx-platform,tanmaykm/edx-platform,pabloborrego93/edx-platform,longmen21/edx-platform,raccoongang/edx-platform,louyihua/edx-platform,louyihua/edx-platform,doganov/edx-platform,raccoongang/edx-platform,romain-li/edx-platform,arbrandes/edx-platform,kmoocdev2/edx-platform,UOMx/edx-platform,cecep-edu/edx-platform,prarthitm/edxplatform,mitocw/edx-platform,longmen21/edx-platform,romain-li/edx-platform,Stanford-Online/edx-platform,Edraak/edraak-platform,itsjeyd/edx-platform,appsembler/edx-platform,antoviaque/edx-platform,kmoocdev2/edx-platform,alu042/edx-platform,IndonesiaX/edx-platform,pabloborrego93/edx-platform,jolyonb/edx-platform,chrisndodge/edx-platform,kmoocdev2/edx-platform,hastexo/edx-platform,caesar2164/edx-platform,jjmiranda/edx-platform,Lektorium-LLC/edx-platform,CourseTalk/edx-platform,arbrandes/edx-platform,gymnasium/edx-platform,jjmiranda/edx-platform,doganov/edx-platform,cpennington/edx-platform,deepsrijit1105/edx-platform,msegado/edx-platform,appsembler/edx-platform,louyihua/edx-platform,BehavioralInsightsTeam/edx-platform,devs1991/test_edx_docmode,tanmaykm/edx-platform,JioEducation/edx-platform,ahmedaljazzar/edx-platform,itsjeyd/edx-platform,deepsrijit1105/edx-platform,mbareta/edx-platform-ft,deepsrijit1105/edx-platform,wwj718/edx-platform,fintech-circle/edx-platform,waheedahmed/edx-platform,Edraak/edraak-platform,Stanford-Online/edx-platform,Edraak/edraak-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,msegado/edx-platform,MakeHer/edx-platform,shabab12/edx-platform,msegado/edx-platform,mbareta/edx-platform-ft,naresh21/synergetics-edx-platform,gymnasium/edx-platform,marcore/edx-platform,lduarte1991/edx-platform,EDUlib/edx-platform
--- +++ @@ -11,13 +11,18 @@ ] operations = [ - migrations.RemoveField( - model_name='coursemode', - name='expiration_datetime', - ), - migrations.AddField( - model_name='coursemode', - name='_expiration_datetime', - field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), - ), + migrations.SeparateDatabaseAndState( + database_operations=[], + state_operations=[ + migrations.RemoveField( + model_name='coursemode', + name='expiration_datetime', + ), + migrations.AddField( + model_name='coursemode', + name='_expiration_datetime', + field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), + ), + ] + ) ]
b6937405a9b85026f3e9cffc94fa65c87ee793c0
kirppu/views/csv_utils.py
kirppu/views/csv_utils.py
# -*- coding: utf-8 -*- import functools import io from urllib.parse import quote from django.http import StreamingHttpResponse def strip_generator(fn): @functools.wraps(fn) def inner(output, event, generator=False): if generator: # Return the generator object only when using StringIO. return fn(output, event) for _ in fn(output, event): pass return inner def csv_streamer_view(request, generator, filename_base): def streamer(): output = io.StringIO() for a_string in generator(output): val = output.getvalue() yield val output.truncate(0) output.seek(0) response = StreamingHttpResponse(streamer(), content_type="text/plain; charset=utf-8") if request.GET.get("download") is not None: response["Content-Disposition"] = 'attachment; filename="%s.csv"' % quote(filename_base, safe="") response["Content-Type"] = "text/csv; charset=utf-8" return response
# -*- coding: utf-8 -*- import functools import html import io from urllib.parse import quote from django.conf import settings from django.http import HttpResponse, StreamingHttpResponse def strip_generator(fn): @functools.wraps(fn) def inner(output, event, generator=False): if generator: # Return the generator object only when using StringIO. return fn(output, event) for _ in fn(output, event): pass return inner def csv_streamer_view(request, generator, filename_base): debug = settings.DEBUG and request.GET.get("debug") is not None def streamer(): if debug: yield "<!DOCTYPE html>\n<html>\n<body>\n<pre>" output = io.StringIO() for a_string in generator(output): val = output.getvalue() if debug: yield html.escape(val, quote=False) else: yield val output.truncate(0) output.seek(0) if debug: yield "</pre>\n</body>\n</html>" if debug: response = HttpResponse("".join(streamer())) else: response = StreamingHttpResponse(streamer(), content_type="text/plain; charset=utf-8") if request.GET.get("download") is not None: response["Content-Disposition"] = 'attachment; filename="%s.csv"' % quote(filename_base, safe="") response["Content-Type"] = "text/csv; charset=utf-8" return response
Add possibility to debug csv streamer views.
Add possibility to debug csv streamer views.
Python
mit
jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu
--- +++ @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- import functools +import html import io from urllib.parse import quote - -from django.http import StreamingHttpResponse +from django.conf import settings +from django.http import HttpResponse, StreamingHttpResponse def strip_generator(fn): @@ -20,15 +21,28 @@ def csv_streamer_view(request, generator, filename_base): + debug = settings.DEBUG and request.GET.get("debug") is not None + def streamer(): + if debug: + yield "<!DOCTYPE html>\n<html>\n<body>\n<pre>" output = io.StringIO() for a_string in generator(output): val = output.getvalue() - yield val + if debug: + yield html.escape(val, quote=False) + else: + yield val output.truncate(0) output.seek(0) + if debug: + yield "</pre>\n</body>\n</html>" - response = StreamingHttpResponse(streamer(), content_type="text/plain; charset=utf-8") + if debug: + response = HttpResponse("".join(streamer())) + else: + response = StreamingHttpResponse(streamer(), content_type="text/plain; charset=utf-8") + if request.GET.get("download") is not None: response["Content-Disposition"] = 'attachment; filename="%s.csv"' % quote(filename_base, safe="") response["Content-Type"] = "text/csv; charset=utf-8"
faba2bc98f08cddea51d2e0093aa5c2981c8bf15
gdrived.py
gdrived.py
#!/usr/bin/env python # # Copyright 2012 Jim Lawton. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import time import daemon class GDriveDaemon(daemon.Daemon): def run(self): while True: time.sleep(1)
#!/usr/bin/env python # # Copyright 2012 Jim Lawton. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import time import daemon UPDATE_INTERVAL = 30 # Sync update interval in seconds. class GDriveDaemon(daemon.Daemon, object): def __init__(self): "Class constructor." # Use pidfile in Gdrive config directory. pidfile = None # Use loglevel from GDrive config. loglevel = None # Use logfile in GDrive config directory. stdout = None super(GDriveDaemon, self).__init__(pidfile, loglevel, stdout) def run(self): "Run the daemon." while True: time.sleep(UPDATE_INTERVAL)
Add update interval constant. Add detail to constructor.
Add update interval constant. Add detail to constructor.
Python
apache-2.0
babycaseny/gdrive-linux,jimlawton/gdrive-linux-googlecode,jimlawton/gdrive-linux,jmfield2/gdrive-linux
--- +++ @@ -19,8 +19,28 @@ import daemon -class GDriveDaemon(daemon.Daemon): +UPDATE_INTERVAL = 30 # Sync update interval in seconds. + +class GDriveDaemon(daemon.Daemon, object): + + def __init__(self): + "Class constructor." + + # Use pidfile in Gdrive config directory. + pidfile = None + + # Use loglevel from GDrive config. + loglevel = None + + # Use logfile in GDrive config directory. + stdout = None + + super(GDriveDaemon, self).__init__(pidfile, loglevel, stdout) + def run(self): + "Run the daemon." + while True: - time.sleep(1) + time.sleep(UPDATE_INTERVAL) +
ee3941e2c3a0355314b270c04de6a623f5a0730c
plugins/stats.py
plugins/stats.py
import operator class Plugin: def __call__(self, bot): bot.on_hear(r"(lol|:D|:P)", self.on_hear) bot.on_respond(r"stats", self.on_respond) bot.on_help("stats", self.on_help) def on_hear(self, bot, msg, reply): stats = bot.storage.get("stats", {}) for word in msg["match"]: word_stats = stats.get(word, {}) word_stats[msg["sender"]] = word_stats.get(msg["sender"], 0) + 1 stats[word] = word_stats bot.storage["stats"] = stats def on_respond(self, bot, msg, reply): def respond(word, description): stats = bot.storage.get("stats", {}).get(word, {}) if stats: person = max(stats.items(), key=operator.itemgetter(1))[0] reply(description.format(person)) respond("lol", "{0} laughs the most.") respond(":D", "{0} is the happiest.") respond(":P", "{0} sticks their tounge out the most.") def on_help(self, bot, msg, reply): reply("Syntax: stats")
import operator class Plugin: def __call__(self, bot): bot.on_hear(r".*", self.on_hear_anything) bot.on_hear(r"(lol|:D|:P)", self.on_hear) bot.on_respond(r"stats", self.on_respond) bot.on_help("stats", self.on_help) def on_hear_anything(self, bot, msg, reply): stats = bot.storage.get("stats", {}) word_stats = stats.get(word, {}) word_stats[""] = word_stats.get("", 0) + 1 stats[word] = word_stats bot.storage["stats"] = stats def on_hear(self, bot, msg, reply): stats = bot.storage.get("stats", {}) for word in msg["match"]: word_stats = stats.get(word, {}) word_stats[msg["sender"]] = word_stats.get(msg["sender"], 0) + 1 stats[word] = word_stats break # only allow one word bot.storage["stats"] = stats def on_respond(self, bot, msg, reply): def respond(word, description): stats = bot.storage.get("stats", {}).get(word, {}) if stats: person = max(stats.items(), key=operator.itemgetter(1))[0] reply(description.format(person)) respond("", "{0} is most talkative.") respond("lol", "{0} laughs the most.") respond(":D", "{0} is the happiest.") respond(":P", "{0} sticks their tounge out the most.") def on_help(self, bot, msg, reply): reply("Display statistics.") reply("Syntax: stats")
Add statistics about general speaking
Add statistics about general speaking
Python
mit
thomasleese/smartbot-old,Cyanogenoid/smartbot,tomleese/smartbot,Muzer/smartbot
--- +++ @@ -2,9 +2,17 @@ class Plugin: def __call__(self, bot): + bot.on_hear(r".*", self.on_hear_anything) bot.on_hear(r"(lol|:D|:P)", self.on_hear) bot.on_respond(r"stats", self.on_respond) bot.on_help("stats", self.on_help) + + def on_hear_anything(self, bot, msg, reply): + stats = bot.storage.get("stats", {}) + word_stats = stats.get(word, {}) + word_stats[""] = word_stats.get("", 0) + 1 + stats[word] = word_stats + bot.storage["stats"] = stats def on_hear(self, bot, msg, reply): stats = bot.storage.get("stats", {}) @@ -13,6 +21,7 @@ word_stats = stats.get(word, {}) word_stats[msg["sender"]] = word_stats.get(msg["sender"], 0) + 1 stats[word] = word_stats + break # only allow one word bot.storage["stats"] = stats @@ -23,9 +32,11 @@ person = max(stats.items(), key=operator.itemgetter(1))[0] reply(description.format(person)) + respond("", "{0} is most talkative.") respond("lol", "{0} laughs the most.") respond(":D", "{0} is the happiest.") respond(":P", "{0} sticks their tounge out the most.") def on_help(self, bot, msg, reply): + reply("Display statistics.") reply("Syntax: stats")
5efca5a3e8fb978cb47e986b1bd7296fe2cae3ce
helpers.py
helpers.py
def get_readable_list(passed_list, sep=', '): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) return output def get_list_as_english(passed_list): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) elif len(passed_list) is 2: output += str(item) if i is not (len(passed_list) - 1): output += " and " else: output += "" else: if i is not (len(passed_list) - 1): output += str(item) + ", " else: output += "and " + str(item) + ", " return output
def get_readable_list(passed_list, sep=', '): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) return output def get_list_as_english(passed_list): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) + ' ' elif len(passed_list) is 2: output += str(item) if i is not (len(passed_list) - 1): output += " and " else: output += " " else: if i is not (len(passed_list) - 1): output += str(item) + ", " else: output += "and " + str(item) + ", " return output
Add some spaces to get_list_as_english
Add some spaces to get_list_as_english
Python
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
--- +++ @@ -17,14 +17,14 @@ output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: - output += str(item) + output += str(item) + ' ' elif len(passed_list) is 2: output += str(item) if i is not (len(passed_list) - 1): output += " and " else: - output += "" + output += " " else: if i is not (len(passed_list) - 1):
f2fd7fa693b5be7ae37445fc185611e80aacddf3
pebble/PblBuildCommand.py
pebble/PblBuildCommand.py
import sh, os from PblCommand import PblCommand class PblBuildCommand(PblCommand): name = 'build' help = 'Build your Pebble project' def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') def run(self, args): waf_path = os.path.join(os.path.join(self.sdk_path(args), 'Pebble'), 'waf') print "Path to waf: {}".format(waf_path) os.system(waf_path + " configure build") def sdk_path(self, args): """ Tries to guess the location of the Pebble SDK """ if args.sdk: return args.sdk else: return os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.join('..', '..', '..')))
import sh, os from PblCommand import PblCommand class PblBuildCommand(PblCommand): name = 'build' help = 'Build your Pebble project' def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') def run(self, args): waf_path = os.path.join(os.path.join(self.sdk_path(args), 'Pebble'), 'waf') print "Path to waf: {}".format(waf_path) os.system(waf_path + " configure build") def sdk_path(self, args): """ Tries to guess the location of the Pebble SDK """ if args.sdk: return args.sdk else: return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
Fix bug to actually find the sdk
Fix bug to actually find the sdk
Python
mit
pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble
--- +++ @@ -21,4 +21,4 @@ if args.sdk: return args.sdk else: - return os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.join('..', '..', '..'))) + return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
898028dea2e04d52c32854752bda34d331c7696f
ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py
ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py
from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from candidatebot.helpers import CandidateBot from popolo.models import Person class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'filename', help='Path to the file with the email addresses' ) parser.add_argument( '--source', help='Source of the data. The source CSV column takes precedence' ) def handle(self, **options): with open(options['filename'], 'r') as fh: reader = csv.DictReader(fh) for row in reader: source = row.get('source', options.get('source')) if not row['democlub_id']: continue if not source: raise ValueError("A source is required") try: bot = CandidateBot(row['democlub_id']) bot.add_email(row['email']) bot.save(source) # print(person) except Person.DoesNotExist: print("Person ID {} not found".format( row['democlub_id'])) # print(row)
from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from candidatebot.helpers import CandidateBot from popolo.models import Person class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'filename', help='Path to the file with the email addresses' ) parser.add_argument( '--source', help='Source of the data. The source CSV column takes precedence' ) def handle(self, **options): with open(options['filename'], 'r') as fh: reader = csv.DictReader(fh) for row in reader: source = row.get('source', options.get('source')) if not row['democlub_id']: continue if not source: raise ValueError("A source is required") try: bot = CandidateBot(row['democlub_id']) try: bot.add_email(row['email']) bot.save(source) except ValueError: #Email exists, move on pass except Person.DoesNotExist: print("Person ID {} not found".format( row['democlub_id'])) # print(row)
Move on if email exists
Move on if email exists
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
--- +++ @@ -31,9 +31,12 @@ try: bot = CandidateBot(row['democlub_id']) - bot.add_email(row['email']) - bot.save(source) - # print(person) + try: + bot.add_email(row['email']) + bot.save(source) + except ValueError: + #Email exists, move on + pass except Person.DoesNotExist: print("Person ID {} not found".format( row['democlub_id']))
4616fdefc1c7df8acccdd89ea792fa24ecfa9ca6
perf-tests/src/perf-tests.py
perf-tests/src/perf-tests.py
def main(): pass if __name__ == "__main__": # execute only if run as a script main()
import json import time import datetime import subprocess import os.path import sys import queue import threading from coreapi import * from jobsapi import * import benchmarks import graph def check_environment_variable(env_var_name): print("Checking: {e} environment variable existence".format( e=env_var_name)) if os.environ.get(env_var_name) is None: print("Fatal: {e} environment variable has to be specified" .format(e=env_var_name)) sys.exit(1) else: print(" ok") def check_environment_variables(): environment_variables = [ "F8A_API_URL", "F8A_JOB_API_URL", "RECOMMENDER_API_TOKEN", "JOB_API_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "S3_REGION_NAME"] for environment_variable in environment_variables: check_environment_variable(environment_variable) def main(): check_environment_variables() pass if __name__ == "__main__": # execute only if run as a script main()
Check environment variables before the tests are started
Check environment variables before the tests are started
Python
apache-2.0
tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common
--- +++ @@ -1,4 +1,45 @@ +import json +import time +import datetime +import subprocess +import os.path +import sys +import queue +import threading + +from coreapi import * +from jobsapi import * +import benchmarks +import graph + + +def check_environment_variable(env_var_name): + print("Checking: {e} environment variable existence".format( + e=env_var_name)) + if os.environ.get(env_var_name) is None: + print("Fatal: {e} environment variable has to be specified" + .format(e=env_var_name)) + sys.exit(1) + else: + print(" ok") + + +def check_environment_variables(): + environment_variables = [ + "F8A_API_URL", + "F8A_JOB_API_URL", + "RECOMMENDER_API_TOKEN", + "JOB_API_TOKEN", + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "S3_REGION_NAME"] + for environment_variable in environment_variables: + check_environment_variable(environment_variable) + + def main(): + check_environment_variables() + pass
2a4d78be3df2d068431fe007b6f2d73956dc23d4
sitecontent/urls.py
sitecontent/urls.py
from django.conf.urls import patterns, url from sitecontent import views urlpatterns = patterns('', url("^rss/(?P<format>.*)$", "sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"), )
from django.conf.urls import patterns, url from sitecontent import views urlpatterns = patterns('', url("^feeds/(?P<format>.*)$", "sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"), )
Use feeds instead of rss
Use feeds instead of rss
Python
mit
vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune,vjousse/viserlalune
--- +++ @@ -4,6 +4,6 @@ urlpatterns = patterns('', - url("^rss/(?P<format>.*)$", + url("^feeds/(?P<format>.*)$", "sitecontent.views.blog_post_feed_richtext_filters", name="blog_post_feed_richtext_filters"), )
72f763d9759438abd731585a1b5ef67e62e27181
pyethapp/__init__.py
pyethapp/__init__.py
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = None else: __version__ = _dist.version if not __version__: try: # try to parse from setup.py for l in open(os.path.join(__path__[0], '..', 'setup.py')): if l.startswith("version = '"): __version__ = l.split("'")[1] break except: pass finally: if not __version__: __version__ = 'undefined' # add git revision and commit status try: rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' except: pass # ########### endversion ##################
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess import re GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$') __version__ = None try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound __version__ = _dist.version except DistributionNotFound: pass if not __version__: try: rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'], stderr=subprocess.STDOUT) match = GIT_DESCRIBE_RE.match(rev) if match: __version__ = "{}+git-{}".format(match.group("version"), match.group("git")) except: pass if not __version__: __version__ = 'undefined' # ########### endversion ##################
Use version gathering logic from hydrachain
Use version gathering logic from hydrachain
Python
mit
gsalgado/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,changwu-tw/pyethapp,changwu-tw/pyethapp,gsalgado/pyethapp
--- +++ @@ -3,6 +3,13 @@ from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess +import re + + +GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$') + + +__version__ = None try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems @@ -11,27 +18,21 @@ if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound + __version__ = _dist.version except DistributionNotFound: - __version__ = None -else: - __version__ = _dist.version + pass + if not __version__: try: - # try to parse from setup.py - for l in open(os.path.join(__path__[0], '..', 'setup.py')): - if l.startswith("version = '"): - __version__ = l.split("'")[1] - break + rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'], + stderr=subprocess.STDOUT) + match = GIT_DESCRIBE_RE.match(rev) + if match: + __version__ = "{}+git-{}".format(match.group("version"), match.group("git")) except: pass - finally: - if not __version__: - __version__ = 'undefined' - # add git revision and commit status - try: - rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) - is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) - __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' - except: - pass + +if not __version__: + __version__ = 'undefined' + # ########### endversion ##################
4541605e27c9fef6cc23b245de50867ff22ea6aa
erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py
erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestAccountingDimension(unittest.TestCase): pass
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry class TestAccountingDimension(unittest.TestCase): def setUp(self): frappe.set_user("Administrator") if not frappe.db.exists("Accounting Dimension", {"document_type": "Department"}): dimension = frappe.get_doc({ "doctype": "Accounting Dimension", "document_type": "Department", }).insert() def test_dimension_against_sales_invoice(self): si = create_sales_invoice(do_not_save=1) si.append("items", { "item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC", "qty": 1, "rate": 100, "income_account": "Sales - _TC", "expense_account": "Cost of Goods Sold - _TC", "cost_center": "_Test Cost Center - _TC", "department": "_Test Department - _TC" }) si.save() si.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": si.name, "account": "Sales - _TC"}) self.assertEqual(gle.department, "_Test Department - _TC") def test_dimension_against_journal_entry(self): je = make_journal_entry("Sales - _TC", "Sales Expenses - _TC", 500, save=False) je.accounts[0].update({"department": "_Test Department - _TC"}) je.accounts[1].update({"department": "_Test Department - _TC"}) je.save() je.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales - _TC"}) gle1 = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales Expenses - _TC"}) self.assertEqual(gle.department, "_Test Department - _TC") self.assertEqual(gle1.department, "_Test Department - _TC")
Test Case for accounting dimension
fix: Test Case for accounting dimension
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
--- +++ @@ -3,8 +3,52 @@ # See license.txt from __future__ import unicode_literals -# import frappe +import frappe import unittest +from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice +from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry class TestAccountingDimension(unittest.TestCase): - pass + def setUp(self): + frappe.set_user("Administrator") + + if not frappe.db.exists("Accounting Dimension", {"document_type": "Department"}): + dimension = frappe.get_doc({ + "doctype": "Accounting Dimension", + "document_type": "Department", + }).insert() + + def test_dimension_against_sales_invoice(self): + si = create_sales_invoice(do_not_save=1) + si.append("items", { + "item_code": "_Test Item", + "warehouse": "_Test Warehouse - _TC", + "qty": 1, + "rate": 100, + "income_account": "Sales - _TC", + "expense_account": "Cost of Goods Sold - _TC", + "cost_center": "_Test Cost Center - _TC", + "department": "_Test Department - _TC" + }) + + si.save() + si.submit() + + gle = frappe.get_doc("GL Entry", {"voucher_no": si.name, "account": "Sales - _TC"}) + + self.assertEqual(gle.department, "_Test Department - _TC") + + def test_dimension_against_journal_entry(self): + je = make_journal_entry("Sales - _TC", "Sales Expenses - _TC", 500, save=False) + je.accounts[0].update({"department": "_Test Department - _TC"}) + je.accounts[1].update({"department": "_Test Department - _TC"}) + + je.save() + je.submit() + + gle = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales - _TC"}) + gle1 = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales Expenses - _TC"}) + self.assertEqual(gle.department, "_Test Department - _TC") + self.assertEqual(gle1.department, "_Test Department - _TC") + +
27112881583e53d790e66d31a2bb4d2a996ee405
python/sparknlp/functions.py
python/sparknlp/functions.py
from pyspark.sql.functions import udf from pyspark.sql.types import * from pyspark.sql import DataFrame import sys import sparknlp def map_annotations(f, output_type: DataType): sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda content: f(content), output_type ) def map_annotations_strict(f): from sparknlp.annotation import Annotation sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda content: f(content), ArrayType(Annotation.dataType()) ) def map_annotations_col(dataframe: DataFrame, f, column, output_column, output_type): dataframe.withColumn(output_column, map_annotations(f, output_type)(column)) def filter_by_annotations_col(dataframe, f, column): this_udf = udf( lambda content: f(content), BooleanType() ) return dataframe.filter(this_udf(column)) def explode_annotations_col(dataframe: DataFrame, column, output_column): from pyspark.sql.functions import explode return dataframe.withColumn(output_column, explode(column))
from pyspark.sql.functions import udf from pyspark.sql.types import * from pyspark.sql import DataFrame from sparknlp.annotation import Annotation import sys import sparknlp def map_annotations(f, output_type: DataType): sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda content: f(content), output_type ) def map_annotations_strict(f): sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda content: f(content), ArrayType(Annotation.dataType()) ) def map_annotations_col(dataframe: DataFrame, f, column, output_column, output_type): dataframe.withColumn(output_column, map_annotations(f, output_type)(column)) def filter_by_annotations_col(dataframe, f, column): this_udf = udf( lambda content: f(content), BooleanType() ) return dataframe.filter(this_udf(column)) def explode_annotations_col(dataframe: DataFrame, column, output_column): from pyspark.sql.functions import explode return dataframe.withColumn(output_column, explode(column))
Move import to top level to avoid import fail after fist time on sys.modules hack
Move import to top level to avoid import fail after fist time on sys.modules hack
Python
apache-2.0
JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp
--- +++ @@ -1,6 +1,7 @@ from pyspark.sql.functions import udf from pyspark.sql.types import * from pyspark.sql import DataFrame +from sparknlp.annotation import Annotation import sys import sparknlp @@ -14,7 +15,6 @@ def map_annotations_strict(f): - from sparknlp.annotation import Annotation sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda content: f(content),
c266f5171e875d8dc3abe924e4b6c9ed2a486422
tests/sentry/web/frontend/test_organization_home.py
tests/sentry/web/frontend/test_organization_home.py
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationHomePermissionTest(PermissionTestCase): def setUp(self): super(OrganizationHomePermissionTest, self).setUp() self.path = reverse('sentry-organization-home', args=[self.organization.slug]) def test_teamless_member_can_load(self): self.assert_teamless_member_can_access(self.path) def test_org_member_can_load(self): self.assert_org_member_can_access(self.path) class OrganizationHomeTest(TestCase): def test_renders_with_context(self): organization = self.create_organization(name='foo', owner=self.user) team = self.create_team(organization=organization) project = self.create_project(team=team) path = reverse('sentry-organization-home', args=[organization.slug]) self.login_as(self.user) resp = self.client.get(path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/organization-home.html') assert resp.context['organization'] == organization assert resp.context['team_list'] == [(team, [project])]
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationHomePermissionTest(PermissionTestCase): def setUp(self): super(OrganizationHomePermissionTest, self).setUp() self.path = reverse('sentry-organization-home', args=[self.organization.slug]) def test_teamless_member_can_load(self): self.assert_teamless_member_can_access(self.path) def test_org_member_can_load(self): self.assert_org_member_can_access(self.path) def test_non_member_cannot_load(self): self.assert_non_member_cannot_access(self.path) class OrganizationHomeTest(TestCase): def test_renders_with_context(self): organization = self.create_organization(name='foo', owner=self.user) team = self.create_team(organization=organization) project = self.create_project(team=team) path = reverse('sentry-organization-home', args=[organization.slug]) self.login_as(self.user) resp = self.client.get(path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/organization-home.html') assert resp.context['organization'] == organization assert resp.context['team_list'] == [(team, [project])]
Add test for non-member access
Add test for non-member access
Python
bsd-3-clause
drcapulet/sentry,daevaorn/sentry,ifduyue/sentry,hongliang5623/sentry,Natim/sentry,wujuguang/sentry,jokey2k/sentry,korealerts1/sentry,llonchj/sentry,songyi199111/sentry,vperron/sentry,BayanGroup/sentry,BuildingLink/sentry,kevinlondon/sentry,fotinakis/sentry,imankulov/sentry,korealerts1/sentry,boneyao/sentry,jean/sentry,hongliang5623/sentry,kevinastone/sentry,fuziontech/sentry,fotinakis/sentry,korealerts1/sentry,pauloschilling/sentry,ifduyue/sentry,camilonova/sentry,argonemyth/sentry,argonemyth/sentry,daevaorn/sentry,jean/sentry,wujuguang/sentry,fotinakis/sentry,looker/sentry,mvaled/sentry,mitsuhiko/sentry,ngonzalvez/sentry,JTCunning/sentry,kevinastone/sentry,TedaLIEz/sentry,camilonova/sentry,jean/sentry,boneyao/sentry,fotinakis/sentry,wong2/sentry,Kryz/sentry,llonchj/sentry,Kryz/sentry,jokey2k/sentry,drcapulet/sentry,songyi199111/sentry,JackDanger/sentry,mvaled/sentry,kevinlondon/sentry,zenefits/sentry,ngonzalvez/sentry,kevinastone/sentry,wong2/sentry,alexm92/sentry,ifduyue/sentry,BayanGroup/sentry,hongliang5623/sentry,JTCunning/sentry,ifduyue/sentry,mitsuhiko/sentry,fuziontech/sentry,beeftornado/sentry,mvaled/sentry,daevaorn/sentry,1tush/sentry,nicholasserra/sentry,JackDanger/sentry,1tush/sentry,zenefits/sentry,Natim/sentry,ewdurbin/sentry,beeftornado/sentry,nicholasserra/sentry,looker/sentry,looker/sentry,wujuguang/sentry,daevaorn/sentry,ngonzalvez/sentry,BuildingLink/sentry,zenefits/sentry,camilonova/sentry,gg7/sentry,felixbuenemann/sentry,argonemyth/sentry,imankulov/sentry,ewdurbin/sentry,JamesMura/sentry,BuildingLink/sentry,pauloschilling/sentry,gencer/sentry,boneyao/sentry,nicholasserra/sentry,ifduyue/sentry,gg7/sentry,JamesMura/sentry,llonchj/sentry,TedaLIEz/sentry,mvaled/sentry,BuildingLink/sentry,drcapulet/sentry,BuildingLink/sentry,alexm92/sentry,JackDanger/sentry,BayanGroup/sentry,zenefits/sentry,gg7/sentry,songyi199111/sentry,mvaled/sentry,vperron/sentry,looker/sentry,gencer/sentry,kevinlondon/sentry,mvaled/sentry,alexm92/sentry,gencer/sentry,looker/sentry,ewdurbin/sentry,vperron/sentry,1tush/sentry,pauloschilling/sentry,beeftornado/sentry,Kryz/sentry,Natim/sentry,gencer/sentry,felixbuenemann/sentry,JamesMura/sentry,jean/sentry,JTCunning/sentry,JamesMura/sentry,imankulov/sentry,wong2/sentry,JamesMura/sentry,TedaLIEz/sentry,gencer/sentry,jokey2k/sentry,felixbuenemann/sentry,fuziontech/sentry,zenefits/sentry,jean/sentry
--- +++ @@ -15,6 +15,9 @@ def test_org_member_can_load(self): self.assert_org_member_can_access(self.path) + + def test_non_member_cannot_load(self): + self.assert_non_member_cannot_access(self.path) class OrganizationHomeTest(TestCase):
5e2aae6070d60f2149c49e1137ab2a99f3966b3a
python/volumeBars.py
python/volumeBars.py
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 4 pi = numpy.pi barHeights = numpy.array([0, pi / 4, pi / 2, pi * 3 / 4]) while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.sin(barHeights) barHeights += pi / 4 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: nextFrame.SetPixel(x, y, randint(0, 255), randint(0, 255), randint(0, 255)) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 4 pi = numpy.pi barHeights = numpy.array([0, pi / 4, pi / 2, pi * 3 / 4]) while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.sin(barHeights) barHeights += pi / 4 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y > 14 nextFrame.SetPixel(x, y, 255, 0, 0) else if y > 10 nextFrame.SetPixel(x, y, 200, 200, 0) else nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
Add specific colors for heights
Add specific colors for heights
Python
mit
DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix
--- +++ @@ -22,8 +22,13 @@ barHeights += pi / 4 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) - for y in range(height): + for y in range(height): if height - y <= barHeight: - nextFrame.SetPixel(x, y, randint(0, 255), randint(0, 255), randint(0, 255)) + if y > 14 + nextFrame.SetPixel(x, y, 255, 0, 0) + else if y > 10 + nextFrame.SetPixel(x, y, 200, 200, 0) + else + nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
214d5f7e09e9b5e854e7471c6dc337456f428647
quickavro/_compat.py
quickavro/_compat.py
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) if PY3: basestring = (str, bytes) def ensure_bytes(s): if type(s) == str: return bytes(s, default_encoding) else: return bytes(s) def ensure_str(s): if type(s) == bytes: return s.decode(default_encoding) else: return s else: range = xrange ensure_bytes = lambda s: s
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) if PY3: basestring = (str, bytes) def ensure_bytes(s): if type(s) == str: return bytes(s, default_encoding) else: return bytes(s) def ensure_str(s): if type(s) == bytes: return s.decode(default_encoding) else: return s else: range = xrange ensure_bytes = lambda s: s ensure_str = lambda s: s
Add missing ensure_str for PY2
Add missing ensure_str for PY2
Python
apache-2.0
ChrisRx/quickavro,ChrisRx/quickavro
--- +++ @@ -34,3 +34,4 @@ range = xrange ensure_bytes = lambda s: s + ensure_str = lambda s: s
a88eb2c7fc2c2d875836f0a4c201ede0c082aceb
selectable/tests/__init__.py
selectable/tests/__init__.py
from django.db import models from ..base import ModelLookup from ..registry import registry class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __unicode__(self): return self.name def __str__(self): return self.name class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __unicode__(self): return self.name def __str__(self): return self.name class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __unicode__(self): return self.name def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup) from .test_base import * from .test_decorators import * from .test_fields import * from .test_functional import * from .test_forms import * from .test_templatetags import * from .test_views import * from .test_widgets import *
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup) from .test_base import * from .test_decorators import * from .test_fields import * from .test_functional import * from .test_forms import * from .test_templatetags import * from .test_views import * from .test_widgets import *
Update the test model definitions.
Update the test model definitions.
Python
bsd-2-clause
affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable
--- +++ @@ -1,37 +1,32 @@ from django.db import models +from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry +@python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) - - def __unicode__(self): - return self.name def __str__(self): return self.name +@python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) - - def __unicode__(self): - return self.name def __str__(self): return self.name +@python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) - - def __unicode__(self): - return self.name def __str__(self): return self.name
c3b1f8c97f89e5b9e8b8e74992631bac33bdde5f
tests/test_read_user_choice.py
tests/test_read_user_choice.py
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = str(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1' )
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1)) def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = str(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1' ) @pytest.fixture(params=[1, True, False, None, [], {}]) def invalid_options(request): return ['foo', 'bar', request.param] def test_raise_on_non_str_options(invalid_options): with pytest.raises(TypeError): read_user_choice('foo', invalid_options)
Implement a test if read_user_choice raises on invalid options
Implement a test if read_user_choice raises on invalid options
Python
bsd-3-clause
lucius-feng/cookiecutter,foodszhang/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,Vauxoo/cookiecutter,sp1rs/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,benthomasson/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,vintasoftware/cookiecutter,nhomar/cookiecutter,dajose/cookiecutter,terryjbates/cookiecutter,lgp171188/cookiecutter,audreyr/cookiecutter,atlassian/cookiecutter,willingc/cookiecutter,christabor/cookiecutter,vintasoftware/cookiecutter,nhomar/cookiecutter,venumech/cookiecutter,sp1rs/cookiecutter,michaeljoseph/cookiecutter,takeflight/cookiecutter,willingc/cookiecutter,lucius-feng/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,christabor/cookiecutter,ramiroluz/cookiecutter,hackebrot/cookiecutter,lgp171188/cookiecutter,takeflight/cookiecutter,cguardia/cookiecutter,kkujawinski/cookiecutter,tylerdave/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,janusnic/cookiecutter,pjbull/cookiecutter,venumech/cookiecutter,agconti/cookiecutter,drgarcia1986/cookiecutter,agconti/cookiecutter,janusnic/cookiecutter,ionelmc/cookiecutter,moi65/cookiecutter,drgarcia1986/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,ionelmc/cookiecutter,Vauxoo/cookiecutter,cguardia/cookiecutter,Springerle/cookiecutter
--- +++ @@ -31,3 +31,13 @@ type=click.Choice(OPTIONS), default='1' ) + + [email protected](params=[1, True, False, None, [], {}]) +def invalid_options(request): + return ['foo', 'bar', request.param] + + +def test_raise_on_non_str_options(invalid_options): + with pytest.raises(TypeError): + read_user_choice('foo', invalid_options)
08d83f6999d8e5442acf8683bd8348baca386331
wsgi/config.py
wsgi/config.py
# see http://docs.gunicorn.org/en/latest/configure.html#configuration-file from os import getenv bind = f'0.0.0.0:{getenv("PORT", "8000")}' workers = getenv('WEB_CONCURRENCY', 2) accesslog = '-' errorlog = '-' loglevel = getenv('LOGLEVEL', 'info') # Larger keep-alive values maybe needed when directly talking to ELBs # See https://github.com/benoitc/gunicorn/issues/1194 keepalive = getenv("WSGI_KEEP_ALIVE", 118) worker_class = getenv("GUNICORN_WORKER_CLASS", "meinheld.gmeinheld.MeinheldWorker") worker_connections = getenv("APP_GUNICORN_WORKER_CONNECTIONS", "1000") worker_tmp_dir = "/dev/shm" # Called just after a worker has been forked. def post_fork(server, worker): server.log.info("Worker spawned (pid: %s)", worker.pid)
# see http://docs.gunicorn.org/en/latest/configure.html#configuration-file from os import getenv bind = f'0.0.0.0:{getenv("PORT", "8000")}' workers = getenv('WEB_CONCURRENCY', 2) accesslog = '-' errorlog = '-' loglevel = getenv('LOGLEVEL', 'info') # Larger keep-alive values maybe needed when directly talking to ELBs # See https://github.com/benoitc/gunicorn/issues/1194 keepalive = getenv("WSGI_KEEP_ALIVE", 2) worker_class = getenv("GUNICORN_WORKER_CLASS", "meinheld.gmeinheld.MeinheldWorker") worker_connections = getenv("APP_GUNICORN_WORKER_CONNECTIONS", "1000") worker_tmp_dir = "/dev/shm" # Called just after a worker has been forked. def post_fork(server, worker): server.log.info("Worker spawned (pid: %s)", worker.pid)
Revert wsgi keep alive as well
Revert wsgi keep alive as well it's one of the last remaining items different between our known good state and current wild cpu usage
Python
mpl-2.0
craigcook/bedrock,flodolo/bedrock,flodolo/bedrock,alexgibson/bedrock,MichaelKohler/bedrock,flodolo/bedrock,MichaelKohler/bedrock,alexgibson/bedrock,sylvestre/bedrock,mozilla/bedrock,MichaelKohler/bedrock,sylvestre/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,pascalchevrel/bedrock,alexgibson/bedrock,pascalchevrel/bedrock,pascalchevrel/bedrock,pascalchevrel/bedrock,flodolo/bedrock,MichaelKohler/bedrock,sylvestre/bedrock,mozilla/bedrock,mozilla/bedrock,craigcook/bedrock,sylvestre/bedrock,mozilla/bedrock
--- +++ @@ -11,7 +11,7 @@ # Larger keep-alive values maybe needed when directly talking to ELBs # See https://github.com/benoitc/gunicorn/issues/1194 -keepalive = getenv("WSGI_KEEP_ALIVE", 118) +keepalive = getenv("WSGI_KEEP_ALIVE", 2) worker_class = getenv("GUNICORN_WORKER_CLASS", "meinheld.gmeinheld.MeinheldWorker") worker_connections = getenv("APP_GUNICORN_WORKER_CONNECTIONS", "1000") worker_tmp_dir = "/dev/shm"
47e79b3a01ca4541d79412cdab856f84871e68f8
templates/vnc_api_lib_ini_template.py
templates/vnc_api_lib_ini_template.py
import string template = string.Template(""" [global] ;WEB_SERVER = 127.0.0.1 ;WEB_PORT = 9696 ; connection through quantum plugin WEB_SERVER = 127.0.0.1 WEB_PORT = 8082 ; connection to api-server directly BASE_URL = / ;BASE_URL = /tenants/infra ; common-prefix for all URLs ; Authentication settings (optional) [auth] AUTHN_TYPE = keystone AUTHN_SERVER=$__contrail_openstack_ip__ AUTHN_PORT = 35357 AUTHN_URL = /v2.0/tokens """)
import string template = string.Template(""" [global] ;WEB_SERVER = 127.0.0.1 ;WEB_PORT = 9696 ; connection through quantum plugin WEB_SERVER = 127.0.0.1 WEB_PORT = 8082 ; connection to api-server directly BASE_URL = / ;BASE_URL = /tenants/infra ; common-prefix for all URLs ; Authentication settings (optional) [auth] AUTHN_TYPE = keystone AUTHN_PROTOCOL = http AUTHN_SERVER=$__contrail_openstack_ip__ AUTHN_PORT = 35357 AUTHN_URL = /v2.0/tokens """)
Add auth protocol for keystone connection in vnc_api
Add auth protocol for keystone connection in vnc_api
Python
apache-2.0
Juniper/contrail-provisioning,Juniper/contrail-provisioning
--- +++ @@ -13,6 +13,7 @@ ; Authentication settings (optional) [auth] AUTHN_TYPE = keystone +AUTHN_PROTOCOL = http AUTHN_SERVER=$__contrail_openstack_ip__ AUTHN_PORT = 35357 AUTHN_URL = /v2.0/tokens
e8b50a70fc7de1842ebe8bc796736459bf154432
dyconnmap/cluster/__init__.py
dyconnmap/cluster/__init__.py
# -*- coding: utf-8 -*- """ """ # Author: Avraam Marimpis <[email protected]> from .ng import NeuralGas from .mng import MergeNeuralGas from .rng import RelationalNeuralGas from .gng import GrowingNeuralGas from .som import SOM from .umatrix import umatrix __all__ = [ "NeuralGas", "MergeNeuralGas", "RelationalNeuralGas", "GrowingNeuralGas", "SOM", "umatrix", ]
# -*- coding: utf-8 -*- """ """ # Author: Avraam Marimpis <[email protected]> from .ng import NeuralGas from .mng import MergeNeuralGas from .rng import RelationalNeuralGas from .gng import GrowingNeuralGas from .som import SOM from .umatrix import umatrix from .validity import ray_turi, davies_bouldin __all__ = [ "NeuralGas", "MergeNeuralGas", "RelationalNeuralGas", "GrowingNeuralGas", "SOM", "umatrix", "ray_turi", "davies_bouldin", ]
Add the new cluster validity methods in the module.
Add the new cluster validity methods in the module.
Python
bsd-3-clause
makism/dyfunconn
--- +++ @@ -11,6 +11,7 @@ from .gng import GrowingNeuralGas from .som import SOM from .umatrix import umatrix +from .validity import ray_turi, davies_bouldin __all__ = [ @@ -20,4 +21,6 @@ "GrowingNeuralGas", "SOM", "umatrix", + "ray_turi", + "davies_bouldin", ]
f1099e777d2e14fa1429f72352dfd90fc08250e6
pentagon/filters.py
pentagon/filters.py
import re def register_filters(): """Register a function with decorator""" registry = {} def registrar(func): registry[func.__name__] = func return func registrar.all = registry return registrar filter = register_filters() def get_jinja_filters(): """Return all registered custom jinja filters""" return filter.all @filter def regex_trim(input, regex, replace=''): """ Trims or replaces the regex match in an input string. input (string): the input string to search for matches regex (string): regex to match replace (string - optional): a string to replace any matches with. Defaults to trimming the match. """ return re.sub(regex, replace, input)
import re def register_filters(): """Register a function with decorator""" registry = {} def registrar(func): registry[func.__name__] = func return func registrar.all = registry return registrar filter = register_filters() def get_jinja_filters(): """Return all registered custom jinja filters""" return filter.all @filter def regex_trim(input, regex, replace=''): """ Trims or replaces the regex match in an input string. input (string): the input string to search for matches regex (string): regex to match replace (string - optional): a string to replace any matches with. Defaults to trimming the match. """ return re.sub(regex, replace, input)
Fix newlines to match formatting in the rest of project.
Fix newlines to match formatting in the rest of project.
Python
apache-2.0
reactiveops/pentagon,reactiveops/pentagon,reactiveops/pentagon
--- +++ @@ -1,5 +1,4 @@ import re - def register_filters(): @@ -13,7 +12,6 @@ filter = register_filters() - def get_jinja_filters():
3d38848287b168cfbe3c9fe5297e7f322027634d
tests/test_parsePoaXml_test.py
tests/test_parsePoaXml_test.py
import unittest import os import re os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import parsePoaXml import generatePoaXml # Import test settings last in order to override the regular settings import poa_test_settings as settings def override_settings(): # For now need to override settings to use test data generatePoaXml.settings = settings def create_test_directories(): try: os.mkdir(settings.TEST_TEMP_DIR) except OSError: pass try: os.mkdir(settings.TARGET_OUTPUT_DIR) except OSError: pass class TestParsePoaXml(unittest.TestCase): def setUp(self): override_settings() create_test_directories() self.passes = [] self.passes.append('elife-02935-v2.xml') self.passes.append('elife-04637-v2.xml') self.passes.append('elife-15743-v1.xml') self.passes.append('elife-02043-v2.xml') def test_parse(self): for xml_file_name in self.passes: file_path = settings.XLS_PATH + xml_file_name articles = parsePoaXml.build_articles_from_article_xmls([file_path]) self.assertEqual(len(articles), 1) if __name__ == '__main__': unittest.main()
import unittest import os import re os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import parsePoaXml import generatePoaXml # Import test settings last in order to override the regular settings import poa_test_settings as settings class TestParsePoaXml(unittest.TestCase): def setUp(self): self.passes = [] self.passes.append('elife-02935-v2.xml') self.passes.append('elife-04637-v2.xml') self.passes.append('elife-15743-v1.xml') self.passes.append('elife-02043-v2.xml') def test_parse(self): for xml_file_name in self.passes: file_path = settings.XLS_PATH + xml_file_name articles = parsePoaXml.build_articles_from_article_xmls([file_path]) self.assertEqual(len(articles), 1) if __name__ == '__main__': unittest.main()
Delete excess code in the latest test scenario.
Delete excess code in the latest test scenario.
Python
mit
gnott/elife-poa-xml-generation,gnott/elife-poa-xml-generation
--- +++ @@ -10,29 +10,10 @@ # Import test settings last in order to override the regular settings import poa_test_settings as settings -def override_settings(): - # For now need to override settings to use test data - - generatePoaXml.settings = settings - -def create_test_directories(): - try: - os.mkdir(settings.TEST_TEMP_DIR) - except OSError: - pass - - try: - os.mkdir(settings.TARGET_OUTPUT_DIR) - except OSError: - pass - class TestParsePoaXml(unittest.TestCase): def setUp(self): - override_settings() - create_test_directories() - self.passes = [] self.passes.append('elife-02935-v2.xml') self.passes.append('elife-04637-v2.xml')
ddad1cf5c4b90ad7997fee72ecd4949dafa43315
custom/enikshay/model_migration_sets/private_nikshay_notifications.py
custom/enikshay/model_migration_sets/private_nikshay_notifications.py
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ( ENROLLED_IN_PRIVATE, REAL_DATASET_PROPERTY_VALUE, ) class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(self, domain, person, episode): self.domain = domain self.person = person self.episode = episode def update_json(self): if not self.should_update: return {} registered_datetime = get_datetime_case_property_changed( self.episode, 'private_nikshay_registered', 'true', ) if registered_datetime is not None: return { 'date_private_nikshay_notification': str(registered_datetime.date()) } else: return {} @property def should_update(self): if self.episode.get_case_property('date_private_nikshay_notification') is not None: return False if self.episode.get_case_property('private_nikshay_registered') != 'true': return False if self.episode.get_case_property(ENROLLED_IN_PRIVATE) != 'true': return False if self.person.get_case_property('dataset') != REAL_DATASET_PROPERTY_VALUE: return False return True
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ENROLLED_IN_PRIVATE class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(self, domain, person, episode): self.domain = domain self.person = person self.episode = episode def update_json(self): if not self.should_update: return {} registered_datetime = get_datetime_case_property_changed( self.episode, 'private_nikshay_registered', 'true', ) if registered_datetime is not None: return { 'date_private_nikshay_notification': str(registered_datetime.date()) } else: return {} @property def should_update(self): if self.episode.get_case_property('date_private_nikshay_notification') is not None: return False if self.episode.get_case_property('private_nikshay_registered') != 'true': return False if self.episode.get_case_property(ENROLLED_IN_PRIVATE) != 'true': return False return True
Remove redundant case property check
Remove redundant case property check
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -1,8 +1,5 @@ from casexml.apps.case.util import get_datetime_case_property_changed -from custom.enikshay.const import ( - ENROLLED_IN_PRIVATE, - REAL_DATASET_PROPERTY_VALUE, -) +from custom.enikshay.const import ENROLLED_IN_PRIVATE class PrivateNikshayNotifiedDateSetter(object): @@ -39,7 +36,4 @@ if self.episode.get_case_property(ENROLLED_IN_PRIVATE) != 'true': return False - if self.person.get_case_property('dataset') != REAL_DATASET_PROPERTY_VALUE: - return False - return True
b3224d83dd1fea7a4b50f93c775a824d82aec806
scan/commands/include.py
scan/commands/include.py
''' Created on Mar 8,2015 @author: qiuyx ''' from scan.commands.command import Command import xml.etree.ElementTree as ET class Include(Command): ''' classdocs ''' def __init__(self, scanFile=None, macros=None,errHandler=None): ''' @param scanFile: The included scan file path located at /scan/example Defaults as None. @param macros: Usage:: >>>icl=Include(scanFile='PrepMotor.scn',macros='macro=value') ''' self.__scanFile=scanFile self.__macros=macros self.__errHandler=errHandler def genXML(self): xml = ET.Element('include') ET.SubElement(xml, 'scan_file').text = self.__scanFile if self.__macros: ET.SubElement(xml, 'macros').text = self.__macros if self.__errHandler: ET.SubElement(xml,'error_handler').text = self.__errHandler return xml def __repr__(self): return self.toCmdString() def toCmdString(self): result = "Include('%s'" % self.__scanFile if self.__macros: result += ", macros='%s'" % self.__macros if self.__errHandler: result += ", errHandler='%s'" % self.__errHandler result += ")" return result
''' Created on Mar 8,2015 @author: qiuyx ''' from scan.commands.command import Command import xml.etree.ElementTree as ET class Include(Command): ''' classdocs ''' def __init__(self, scan, macros=None, errhandler=None): ''' @param scan: Name of included scan file, must be on the server's list of script_paths @param macros: "name=value, other=42" Usage:: >>>icl=Include(scanFile='PrepMotor.scn', macros='macro=value') ''' self.__scanFile = scan self.__macros = macros self.__errHandler = errhandler def genXML(self): xml = ET.Element('include') ET.SubElement(xml, 'scan_file').text = self.__scanFile if self.__macros: ET.SubElement(xml, 'macros').text = self.__macros if self.__errHandler: ET.SubElement(xml,'error_handler').text = self.__errHandler return xml def __repr__(self): return self.toCmdString() def toCmdString(self): result = "Include('%s'" % self.__scanFile if self.__macros: result += ", macros='%s'" % self.__macros if self.__errHandler: result += ", errHandler='%s'" % self.__errHandler result += ")" return result
Include command: All arguments lowercase. Require file, default to empty macros
Include command: All arguments lowercase. Require file, default to empty macros
Python
epl-1.0
PythonScanClient/PyScanClient,PythonScanClient/PyScanClient
--- +++ @@ -12,18 +12,17 @@ ''' - def __init__(self, scanFile=None, macros=None,errHandler=None): + def __init__(self, scan, macros=None, errhandler=None): ''' - @param scanFile: The included scan file path located at /scan/example - Defaults as None. - @param macros: + @param scan: Name of included scan file, must be on the server's list of script_paths + @param macros: "name=value, other=42" Usage:: - >>>icl=Include(scanFile='PrepMotor.scn',macros='macro=value') + >>>icl=Include(scanFile='PrepMotor.scn', macros='macro=value') ''' - self.__scanFile=scanFile - self.__macros=macros - self.__errHandler=errHandler + self.__scanFile = scan + self.__macros = macros + self.__errHandler = errhandler def genXML(self): xml = ET.Element('include')
c00bfab0c1bd00fcd1b075cfeaacb7a3b542017a
ynr/apps/candidates/search_indexes.py
ynr/apps/candidates/search_indexes.py
from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from popolo.models import Person class PersonIndex(CelerySearchIndex, indexes.Indexable): # FIXME: this doesn't seem to work for partial names despite what # docs say text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') family_name = indexes.CharField(model_attr='family_name') given_name = indexes.CharField(model_attr='given_name') additional_name = indexes.CharField(model_attr='additional_name') def get_updated_field(self): return 'updated_at' def get_model(self): return Person
from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from popolo.models import Person class PersonIndex(CelerySearchIndex, indexes.Indexable): # FIXME: this doesn't seem to work for partial names despite what # docs say text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') family_name = indexes.CharField(model_attr='family_name') given_name = indexes.CharField(model_attr='given_name') additional_name = indexes.CharField(model_attr='additional_name') last_updated = indexes.DateTimeField(model_attr='updated_at') def get_updated_field(self): return 'updated_at' def get_model(self): return Person
Add last modified to search index
Add last modified to search index
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
--- +++ @@ -12,6 +12,7 @@ family_name = indexes.CharField(model_attr='family_name') given_name = indexes.CharField(model_attr='given_name') additional_name = indexes.CharField(model_attr='additional_name') + last_updated = indexes.DateTimeField(model_attr='updated_at') def get_updated_field(self): return 'updated_at'
b47ecb3464585d762c17694190286388c25dbaf8
examples/convert_units.py
examples/convert_units.py
# -*- coding: utf-8 -*- from chatterbot import ChatBot bot = ChatBot( "Unit Converter", logic_adapters=[ "chatterbot.logic.UnitConversion", ], input_adapter="chatterbot.input.VariableInputTypeAdapter", output_adapter="chatterbot.output.OutputAdapter" ) questions = ['How many meters are in a kilometer?', 'How many meters are in one inch?', '0 celsius to fahrenheit', 'one hour is how many minutes ?'] # Prints the convertion given the specific question for q in questions: response = bot.get_response(q) print(q + " - Response: " + response.text)
# -*- coding: utf-8 -*- from chatterbot import ChatBot bot = ChatBot( "Unit Converter", logic_adapters=[ "chatterbot.logic.UnitConversion", ], input_adapter="chatterbot.input.VariableInputTypeAdapter", output_adapter="chatterbot.output.OutputAdapter" ) questions = ['How many meters are in a kilometer?', 'How many meters are in one inch?', '0 celsius to fahrenheit', 'one hour is how many minutes ?'] # Prints the convertion given the specific question for q in questions: response = bot.get_response(q) print(q + " - Response: " + response.text)
Break list declaration in multiple lines
Break list declaration in multiple lines
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
--- +++ @@ -11,7 +11,10 @@ output_adapter="chatterbot.output.OutputAdapter" ) -questions = ['How many meters are in a kilometer?', 'How many meters are in one inch?', '0 celsius to fahrenheit', 'one hour is how many minutes ?'] +questions = ['How many meters are in a kilometer?', + 'How many meters are in one inch?', + '0 celsius to fahrenheit', + 'one hour is how many minutes ?'] # Prints the convertion given the specific question for q in questions:
d38617dd6bf5c7b0f17245dd5a5e95a335ac6626
tracpro/orgs_ext/middleware.py
tracpro/orgs_ext/middleware.py
from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest from temba_client.base import TembaAPIError class HandleTembaAPIError(object): """ Catch all Temba exception errors """ def process_exception(self, request, exception): if isinstance(exception, TembaAPIError): return HttpResponseBadRequest( _("Org does not have a valid API Key. " + "Please edit the org through Site Manage or contact your administrator.")) pass
from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest from temba_client.base import TembaAPIError, TembaConnectionError class HandleTembaAPIError(object): """ Catch all Temba exception errors """ def process_exception(self, request, exception): rapidProConnectionErrorString = _( "RapidPro appears to be down right now or we cannot connect due to your internet connection. " "Please try again later.") if isinstance(exception, TembaAPIError): rapidpro_connection_error_codes = ["502", "503", "504"] if any(code in exception.caused_by.message for code in rapidpro_connection_error_codes): return HttpResponseBadRequest( rapidProConnectionErrorString) else: return HttpResponseBadRequest( _("Org does not have a valid API Key. " "Please edit the org through Site Manage or contact your administrator.")) elif isinstance(exception, TembaConnectionError): return HttpResponseBadRequest( rapidProConnectionErrorString) pass
Check forerror codes from temba connection issues
Check forerror codes from temba connection issues
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro
--- +++ @@ -1,16 +1,32 @@ from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest -from temba_client.base import TembaAPIError +from temba_client.base import TembaAPIError, TembaConnectionError class HandleTembaAPIError(object): """ Catch all Temba exception errors """ def process_exception(self, request, exception): + + rapidProConnectionErrorString = _( + "RapidPro appears to be down right now or we cannot connect due to your internet connection. " + "Please try again later.") + if isinstance(exception, TembaAPIError): + rapidpro_connection_error_codes = ["502", "503", "504"] + + if any(code in exception.caused_by.message for code in rapidpro_connection_error_codes): + return HttpResponseBadRequest( + rapidProConnectionErrorString) + + else: + return HttpResponseBadRequest( + _("Org does not have a valid API Key. " + "Please edit the org through Site Manage or contact your administrator.")) + + elif isinstance(exception, TembaConnectionError): return HttpResponseBadRequest( - _("Org does not have a valid API Key. " + - "Please edit the org through Site Manage or contact your administrator.")) + rapidProConnectionErrorString) pass
be19869d76bb655990464094ad17617b7b48ab3b
server/create_tiff.py
server/create_tiff.py
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', '--tile-height', '256', '--pyramid', '--bigtiff' ) proc = subprocess.Popen(convert_command) proc.wait() if proc.returncode: raise Exception('VIPS process failed (rc=%d).' % proc.returncode)
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', '--tile-height', '256', '--pyramid', '--bigtiff' ) proc = subprocess.Popen(convert_command) proc.wait() if proc.returncode: raise Exception('VIPS command failed (rc=%d): %s' % ( proc.returncode, ' '.join(convert_command)))
Print command in failure case
Print command in failure case
Python
apache-2.0
DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image
--- +++ @@ -22,4 +22,5 @@ proc.wait() if proc.returncode: - raise Exception('VIPS process failed (rc=%d).' % proc.returncode) + raise Exception('VIPS command failed (rc=%d): %s' % ( + proc.returncode, ' '.join(convert_command)))
e5acbfc176de3b531528c8b15f57e5d3feab3ad1
melody/constraints/abstract_constraint.py
melody/constraints/abstract_constraint.py
""" File: abstract_constraint.py Purpose: Define a constraint, in an abstract sense, related to a number of actors. """ from abc import ABCMeta, abstractmethod class AbstractConstraint(object): """ Class that represents a constraint, a set of actors that define a constraint amongst themselves. ParameterMap: A map from template note to contextual note.. """ __metaclass__ = ABCMeta def __init__(self, actors): self.__actors = list(actors) @property def actors(self): return list(self.__actors) @abstractmethod def clone(self, new_actors=None): """ Clone the constraint. :return: """ @abstractmethod def verify(self, solution_context): """ Verify that the actor map parameters are consistent with constraint. :params solution_context: aka pmap, map of actors to ContextualNotes. :return: Boolean if verification holds. May throw Exception dependent on implementation. """ @abstractmethod def values(self, solution_context, v_note): """ Method to generate all possible note values for actor v_note's target. The method returns a set of values for v_note. :param solution_context: includes parameter map. :param v_note: source actor, whose target values we are computing. :return: The set of all possible values for v_note's target. Note: The return value is a set! """
""" File: abstract_constraint.py Purpose: Define a constraint, in an abstract sense, related to a number of actors. """ from abc import ABCMeta, abstractmethod class AbstractConstraint(object): """ Class that represents a constraint, a set of actors that define a constraint amongst themselves. ParameterMap: A map from template note to contextual note.. """ __metaclass__ = ABCMeta def __init__(self, actors): self.__actors = list(actors) @property def actors(self): return list(self.__actors) @abstractmethod def clone(self, new_actors=None): """ Clone the constraint. :return: """ @abstractmethod def verify(self, solution_context): """ Verify that the actor map parameters are consistent with constraint. :params solution_context: aka pmap, map of actors to ContextualNotes. :return: Boolean if verification holds. May throw Exception dependent on implementation. """ @abstractmethod def values(self, solution_context, v_note): """ Method to generate all possible note values for actor v_note's target. The method returns a set of values for v_note. :param solution_context: includes parameter map. :param v_note: source actor, whose target values we are computing. :return: The set of all possible values for v_note's target. Note: The return value is a set! """ def __hash__(self): return hash(len(self.actors)) def __eq__(self, other): if not isinstance(other, AbstractConstraint): return NotImplemented return self is other
Add hash and eq methods
Add hash and eq methods
Python
mit
dpazel/music_rep
--- +++ @@ -50,3 +50,11 @@ :return: The set of all possible values for v_note's target. Note: The return value is a set! """ + + def __hash__(self): + return hash(len(self.actors)) + + def __eq__(self, other): + if not isinstance(other, AbstractConstraint): + return NotImplemented + return self is other
80025b77f42813a840533050331972d66febeb04
python/src/setup.py
python/src/setup.py
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.0.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="[email protected]", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=["GoogleAppEngineCloudStorageClient >= 1.9.0"] )
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.5.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="[email protected]", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=["GoogleAppEngineCloudStorageClient >= 1.9.5"] )
Create PyPI Release for 1.9.5.0.
Python: Create PyPI Release for 1.9.5.0. Revision created by MOE tool push_codebase. MOE_MIGRATION=7043
Python
apache-2.0
bmenasha/appengine-mapreduce,talele08/appengine-mapreduce,soundofjw/appengine-mapreduce,aozarov/appengine-mapreduce,ankit318/appengine-mapreduce,talele08/appengine-mapreduce,Candreas/mapreduce,aozarov/appengine-mapreduce,soundofjw/appengine-mapreduce,westerhofffl/appengine-mapreduce,soundofjw/appengine-mapreduce,vendasta/appengine-mapreduce,Candreas/mapreduce,VirusTotal/appengine-mapreduce,potatolondon/potato-mapreduce,westerhofffl/appengine-mapreduce,chargrizzle/appengine-mapreduce,vendasta/appengine-mapreduce,Candreas/mapreduce,lordzuko/appengine-mapreduce,aozarov/appengine-mapreduce,westerhofffl/appengine-mapreduce,vendasta/appengine-mapreduce,potatolondon/potato-mapreduce,westerhofffl/appengine-mapreduce,VirusTotal/appengine-mapreduce,rbruyere/appengine-mapreduce,vendasta/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,chargrizzle/appengine-mapreduce,mikelambert/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,rbruyere/appengine-mapreduce,lordzuko/appengine-mapreduce,Candreas/mapreduce,chargrizzle/appengine-mapreduce,ankit318/appengine-mapreduce,bmenasha/appengine-mapreduce,bmenasha/appengine-mapreduce,aozarov/appengine-mapreduce,vendasta/appengine-mapreduce,talele08/appengine-mapreduce,aozarov/appengine-mapreduce,rbruyere/appengine-mapreduce,lordzuko/appengine-mapreduce,talele08/appengine-mapreduce,Candreas/mapreduce,GoogleCloudPlatform/appengine-mapreduce,bmenasha/appengine-mapreduce,chargrizzle/appengine-mapreduce,soundofjw/appengine-mapreduce,mikelambert/appengine-mapreduce,rbruyere/appengine-mapreduce,mikelambert/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,talele08/appengine-mapreduce,soundofjw/appengine-mapreduce,potatolondon/potato-mapreduce,VirusTotal/appengine-mapreduce,bmenasha/appengine-mapreduce,ankit318/appengine-mapreduce,ankit318/appengine-mapreduce,mikelambert/appengine-mapreduce,westerhofffl/appengine-mapreduce,VirusTotal/appengine-mapreduce,chargrizzle/appengine-mapreduce,rbruyere/appengine-mapreduce,VirusTotal/appengine-mapreduce,lordzuko/appengine-mapreduce,lordzuko/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,mikelambert/appengine-mapreduce,ankit318/appengine-mapreduce
--- +++ @@ -14,7 +14,7 @@ # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", - version="1.9.0.0", + version="1.9.5.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="[email protected]", @@ -26,5 +26,5 @@ zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, - install_requires=["GoogleAppEngineCloudStorageClient >= 1.9.0"] + install_requires=["GoogleAppEngineCloudStorageClient >= 1.9.5"] )
7fde39b0d4a41e8119893254d38460cf6914f028
bashhub/view/status.py
bashhub/view/status.py
import dateutil.parser import datetime import humanize status_view = """\ === Bashhub Status https://bashhub.com/u/{0} Total Commands: {1} Total Sessions: {2} Total Systems: {3} === Session PID {4} Started {5} Commands In Session: {6} Commands Today: {7} """ def build_status_view(model): date = datetime.datetime.fromtimestamp(model.session_start_time / 1000.0) date_str = humanize.naturaltime(date) return status_view.format( model.username, model.total_commands, model.total_sessions, model.total_systems, model.session_name, date_str, model.session_total_commands, model.total_commands_today)
import dateutil.parser import datetime import humanize status_view = """\ === Bashhub Status https://bashhub.com/{0} Total Commands: {1} Total Sessions: {2} Total Systems: {3} === Session PID {4} Started {5} Commands In Session: {6} Commands Today: {7} """ def build_status_view(model): date = datetime.datetime.fromtimestamp(model.session_start_time / 1000.0) date_str = humanize.naturaltime(date) return status_view.format( model.username, model.total_commands, model.total_sessions, model.total_systems, model.session_name, date_str, model.session_total_commands, model.total_commands_today)
Remove /u/ from username path
Remove /u/ from username path
Python
apache-2.0
rcaloras/bashhub-client,rcaloras/bashhub-client
--- +++ @@ -4,7 +4,7 @@ status_view = """\ === Bashhub Status -https://bashhub.com/u/{0} +https://bashhub.com/{0} Total Commands: {1} Total Sessions: {2} Total Systems: {3}
8c2ad666266d4dbe8310007bd82dc907a288ee5a
databroker/__init__.py
databroker/__init__.py
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct) from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog # A catalog created from discovered entrypoints and v0 catalogs. catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog()]) # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions ### Legacy imports ### try: from .databroker import DataBroker except ImportError: pass else: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images
# Import intake to run driver discovery first and avoid circular import issues. import intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct) from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog # A catalog created from discovered entrypoints, v0, and intake YAML catalogs. catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog(), intake.cat]) # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions ### Legacy imports ### try: from .databroker import DataBroker except ImportError: pass else: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images
Include intake.cat. YAML is easier than entry_points.
Include intake.cat. YAML is easier than entry_points.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
--- +++ @@ -1,6 +1,5 @@ # Import intake to run driver discovery first and avoid circular import issues. import intake -del intake import warnings import logging @@ -15,8 +14,8 @@ from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog -# A catalog created from discovered entrypoints and v0 catalogs. -catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog()]) +# A catalog created from discovered entrypoints, v0, and intake YAML catalogs. +catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog(), intake.cat]) # set version string using versioneer from ._version import get_versions
0624417fbac1cf23316ee0a58ae41c0519a390c4
go/apps/surveys/definition.py
go/apps/surveys/definition.py
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) from go.apps.surveys.tasks import export_vxpolls_data class SendSurveyAction(ConversationAction): action_name = 'send_survey' action_display_name = 'Send Survey' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting_generic_sends(): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'send_survey', batch_id=self._conv.batch.key, msg_options={}, delivery_class=self._conv.delivery_class) class DownloadUserDataAction(ConversationAction): action_name = 'download_user_data' action_display_name = 'Download User Data' def perform_action(self, action_data): return export_vxpolls_data.delay(self._conv.user_account.key, self._conv.key) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'surveys' actions = ( SendSurveyAction, DownloadUserDataAction, )
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) from go.apps.surveys.tasks import export_vxpolls_data class SendSurveyAction(ConversationAction): action_name = 'send_survey' action_display_name = 'Send Survey' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting_generic_sends(): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'send_survey', batch_id=self._conv.batch.key, msg_options={}, delivery_class=self._conv.delivery_class) class DownloadUserDataAction(ConversationAction): action_name = 'download_user_data' action_display_name = 'Download User Data' action_display_verb = 'Send CSV via e-mail' def perform_action(self, action_data): return export_vxpolls_data.delay(self._conv.user_account.key, self._conv.key) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'surveys' actions = ( SendSurveyAction, DownloadUserDataAction, )
Change download survey data display verb to 'Send CSV via e-mail'.
Change download survey data display verb to 'Send CSV via e-mail'.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
--- +++ @@ -27,6 +27,7 @@ class DownloadUserDataAction(ConversationAction): action_name = 'download_user_data' action_display_name = 'Download User Data' + action_display_verb = 'Send CSV via e-mail' def perform_action(self, action_data): return export_vxpolls_data.delay(self._conv.user_account.key,
7a3c4eed8888c8c2befc94020bebbfc18e1d6156
src/redis_client.py
src/redis_client.py
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None @defer.inlineCallbacks def run_redis_client(on_started): pony = yield redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = True) global connection connection = pony on_started()
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None def run_redis_client(on_started): df = redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], poolsize = 8, reconnect = True, isLazy = False) def done(pony): global connection connection = pony on_started() df.addCallback(done)
Fix the Redis client connection to actually work
Fix the Redis client connection to actually work It previously lied.
Python
mit
prophile/compd,prophile/compd
--- +++ @@ -4,15 +4,16 @@ connection = None [email protected] def run_redis_client(on_started): - pony = yield redis.makeConnection(config.redis['host'], - config.redis['port'], - config.redis['db'], - poolsize = 8, - reconnect = True, - isLazy = True) - global connection - connection = pony - on_started() + df = redis.makeConnection(config.redis['host'], + config.redis['port'], + config.redis['db'], + poolsize = 8, + reconnect = True, + isLazy = False) + def done(pony): + global connection + connection = pony + on_started() + df.addCallback(done)
fdee90e6fd4669222c2da0530d9bc90131b5145e
djoser/social/views.py
djoser/social/views.py
from rest_framework import generics, permissions, status from rest_framework.response import Response from social_django.utils import load_backend, load_strategy from djoser.conf import settings from djoser.social.serializers import ProviderAuthSerializer class ProviderAuthView(generics.CreateAPIView): permission_classes = [permissions.AllowAny] serializer_class = ProviderAuthSerializer def get(self, request, *args, **kwargs): redirect_uri = request.GET.get("redirect_uri") if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS: return Response(status=status.HTTP_400_BAD_REQUEST) strategy = load_strategy(request) strategy.session_set("redirect_uri", redirect_uri) backend_name = self.kwargs["provider"] backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri) authorization_url = backend.auth_url() return Response(data={"authorization_url": authorization_url})
from rest_framework import generics, permissions, status from rest_framework.response import Response from social_django.utils import load_backend, load_strategy from djoser.conf import settings from djoser.social.serializers import ProviderAuthSerializer class ProviderAuthView(generics.CreateAPIView): permission_classes = [permissions.AllowAny] serializer_class = ProviderAuthSerializer def get(self, request, *args, **kwargs): redirect_uri = request.GET.get("redirect_uri") if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS: return Response("Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS", status=status.HTTP_400_BAD_REQUEST) strategy = load_strategy(request) strategy.session_set("redirect_uri", redirect_uri) backend_name = self.kwargs["provider"] backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri) authorization_url = backend.auth_url() return Response(data={"authorization_url": authorization_url})
Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS
Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS i forget add SOCIAL_AUTH_ALLOWED_REDIRECT_URIS to my config it return 400 error, i don't know why , i pay more time find the issues so i add Friendly tips -- sorry , my english is not well and thank you all
Python
mit
sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser
--- +++ @@ -13,7 +13,7 @@ def get(self, request, *args, **kwargs): redirect_uri = request.GET.get("redirect_uri") if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS: - return Response(status=status.HTTP_400_BAD_REQUEST) + return Response("Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS", status=status.HTTP_400_BAD_REQUEST) strategy = load_strategy(request) strategy.session_set("redirect_uri", redirect_uri)
db14ed2c23b3838796e648faade2c73b786d61ff
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sys import threading import time import traceback from .singleton import Singleton def _format_exception(exc_info): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)} class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.queue = queue.Queue() def schedule(self, event): """Schedule an event. The events have the form:: (event, error) where `event` is a thunk and `error` is called with an exception message (output of `_format_exception`) if there is an error when executing `event`. """ self.queue.put(event) def stop(self): """Stop the loop.""" pass def run_step(self, block=True): """Process one event.""" ev, error = self.queue.get(block=block) try: ev() except Exception as exc: error(_format_exception(sys.exc_info())) def run(self): """Process all events in the queue.""" try: while True: self.run_step(block=False) except queue.Empty: return
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sys import threading import time import traceback from .singleton import Singleton def exception_message(): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)} class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.queue = queue.Queue() def schedule(self, event): """Schedule an event. The events have the form:: (event, error) where `event` is a thunk and `error` is called with an exception message (output of `exception_message`) if there is an error when executing `event`. """ self.queue.put(event) def stop(self): """Stop the loop.""" pass def run_step(self, block=True): """Process one event.""" ev, error = self.queue.get(block=block) try: ev() except Exception as exc: error(exception_message()) def run(self): """Process all events in the queue.""" try: while True: self.run_step(block=False) except queue.Empty: return
Make exception message builder a nicer function
Make exception message builder a nicer function It is used by clients in other modules.
Python
mit
waltermoreira/tartpy
--- +++ @@ -21,9 +21,9 @@ from .singleton import Singleton -def _format_exception(exc_info): +def exception_message(): """Create a message with details on the exception.""" - exc_type, exc_value, exc_tb = exc_info + exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, @@ -44,7 +44,7 @@ (event, error) where `event` is a thunk and `error` is called with an - exception message (output of `_format_exception`) if there is + exception message (output of `exception_message`) if there is an error when executing `event`. """ @@ -60,7 +60,7 @@ try: ev() except Exception as exc: - error(_format_exception(sys.exc_info())) + error(exception_message()) def run(self): """Process all events in the queue."""
3976a5b38e1b5356b83d22d9113aa83c9f09fdec
admin/manage.py
admin/manage.py
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain(name=domain_name) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(domain) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
Allow admin creation after initial setup
Allow admin creation after initial setup
Python
mit
kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io
--- +++ @@ -21,14 +21,16 @@ def admin(localpart, domain_name, password): """ Create an admin user """ - domain = models.Domain(name=domain_name) + domain = models.Domain.query.get(domain_name) + if not domain: + domain = models.Domain(name=domain_name) + db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) - db.session.add(domain) db.session.add(user) db.session.commit()
2a7d28573d1e4f07250da1d30209304fdb6de90d
sqlobject/tests/test_blob.py
sqlobject/tests/test_blob.py
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', length=256) def test_BLOBCol(): if not supports('blobData'): pytest.skip("blobData isn't supported") setupClass(ImageData) if PY2: data = ''.join([chr(x) for x in range(256)]) else: data = bytes(range(256)) prof = ImageData() prof.image = data iid = prof.id ImageData._connection.cache.clear() prof2 = ImageData.get(iid) assert prof2.image == data ImageData(image='string') assert ImageData.selectBy(image='string').count() == 1
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', length=256) def test_BLOBCol(): if not supports('blobData'): pytest.skip("blobData isn't supported") setupClass(ImageData) if PY2: data = ''.join([chr(x) for x in range(256)]) else: data = bytes(range(256)) prof = ImageData(image=data) iid = prof.id ImageData._connection.cache.clear() prof2 = ImageData.get(iid) assert prof2.image == data ImageData(image=b'string') assert ImageData.selectBy(image=b'string').count() == 1
Use byte string for test
Tests(blob): Use byte string for test
Python
lgpl-2.1
sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject
--- +++ @@ -22,8 +22,7 @@ else: data = bytes(range(256)) - prof = ImageData() - prof.image = data + prof = ImageData(image=data) iid = prof.id ImageData._connection.cache.clear() @@ -31,5 +30,5 @@ prof2 = ImageData.get(iid) assert prof2.image == data - ImageData(image='string') - assert ImageData.selectBy(image='string').count() == 1 + ImageData(image=b'string') + assert ImageData.selectBy(image=b'string').count() == 1
95fa71c4439343764cac95a1667e08dc21cb6ebe
plugins.py
plugins.py
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) run("ln -sf %s %s" % (source_path, target_folder))
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) with settings(user=env.deploy_user): run("ln -sf %s %s" % (source_path, target_folder))
Fix plugin test by running scripts as user deploy
Fix plugin test by running scripts as user deploy
Python
bsd-3-clause
ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment
--- +++ @@ -18,4 +18,5 @@ source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) - run("ln -sf %s %s" % (source_path, target_folder)) + with settings(user=env.deploy_user): + run("ln -sf %s %s" % (source_path, target_folder))
9c35a41c6594d0ac482a558abf4772150c2a67e9
squash/dashboard/urls.py
squash/dashboard/urls.py
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'job', views.JobViewSet) router.register(r'metric', views.MetricViewSet) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(router.urls)), url(r'^api/token/', obtain_auth_token, name='api-token'), url(r'^(?P<pk>[0-9]+)/dashboard/', views.MetricDashboardView.as_view(), name='metric-detail'), url(r'^$', views.HomeView.as_view(), name='home'), ]
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views <<<<<<< HEAD router = DefaultRouter() router.register(r'job', views.JobViewSet) router.register(r'metric', views.MetricViewSet) ======= api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) api_router.register(r'packages', views.PackageViewSet) >>>>>>> b962845... Make all API resource collection endpoints plural urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(router.urls)), url(r'^api/token/', obtain_auth_token, name='api-token'), url(r'^(?P<pk>[0-9]+)/dashboard/', views.MetricDashboardView.as_view(), name='metric-detail'), url(r'^$', views.HomeView.as_view(), name='home'), ]
Make all API resource collection endpoints plural
Make all API resource collection endpoints plural /api/job/ -> /api/jobs/ /api/metric/ -> /api/metrics/ It's a standard convention in RESTful APIs to make endpoints for collections plural.
Python
mit
lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard
--- +++ @@ -4,9 +4,16 @@ from rest_framework.routers import DefaultRouter from . import views +<<<<<<< HEAD router = DefaultRouter() router.register(r'job', views.JobViewSet) router.register(r'metric', views.MetricViewSet) +======= +api_router = DefaultRouter() +api_router.register(r'jobs', views.JobViewSet) +api_router.register(r'metrics', views.MetricViewSet) +api_router.register(r'packages', views.PackageViewSet) +>>>>>>> b962845... Make all API resource collection endpoints plural urlpatterns = [ url(r'^admin/', include(admin.site.urls)),
32a61c6df871ad148a8c51b7b4cab3f392a2c61a
tsune/urls.py
tsune/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'tsune.views.home', name='home'), # url(r'^tsune/', include('tsune.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:go.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('authentication.urls')), url(r'^cardbox/', include('cardbox.deck_urls', namespace="deck")), url(r'^cardbox/cards/', include('cardbox.card_urls', namespace="card")), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.http import HttpResponseRedirect admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'tsune.views.home', name='home'), # url(r'^tsune/', include('tsune.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:go.contrib.admindocs.urls')), url(r'^$', lambda x: HttpResponseRedirect('/cardbox/')), # redirect to /cardbox/ url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('authentication.urls')), url(r'^cardbox/', include('cardbox.deck_urls', namespace="deck")), url(r'^cardbox/cards/', include('cardbox.card_urls', namespace="card")), )
Add redirect to cardbox if root url is accessed
Add redirect to cardbox if root url is accessed
Python
mit
DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune
--- +++ @@ -2,6 +2,8 @@ # Uncomment the next two lines to enable the admin: from django.contrib import admin +from django.http import HttpResponseRedirect + admin.autodiscover() urlpatterns = patterns('', @@ -13,6 +15,7 @@ # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:go.contrib.admindocs.urls')), + url(r'^$', lambda x: HttpResponseRedirect('/cardbox/')), # redirect to /cardbox/ url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('authentication.urls')), url(r'^cardbox/', include('cardbox.deck_urls', namespace="deck")),
171bbf488db643d01d6a58c9376ba85c200711d5
gtts/tokenizer/tests/test_pre_processors.py
gtts/tokenizer/tests/test_pre_processors.py
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) def test_end_of_line(self): _in = """test- ing""" _out = "testing" self.assertEqual(end_of_line(_in), _out) def test_abbreviations(self): _in = "jr. sr. dr." _out = "jr sr dr" self.assertEqual(abbreviations(_in), _out) def test_word_sub(self): _in = "M. Bacon" _out = "Monsieur Bacon" self.assertEqual(word_sub(_in), _out) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) def test_end_of_line(self): _in = """test- ing""" _out = "testing" self.assertEqual(end_of_line(_in), _out) def test_abbreviations(self): _in = "jr. sr. dr." _out = "jr sr dr" self.assertEqual(abbreviations(_in), _out) def test_word_sub(self): _in = "Esq. Bacon" _out = "Esquire Bacon" self.assertEqual(word_sub(_in), _out) if __name__ == '__main__': unittest.main()
Update unit test for ad8bcd8
Update unit test for ad8bcd8
Python
mit
pndurette/gTTS
--- +++ @@ -21,8 +21,8 @@ self.assertEqual(abbreviations(_in), _out) def test_word_sub(self): - _in = "M. Bacon" - _out = "Monsieur Bacon" + _in = "Esq. Bacon" + _out = "Esquire Bacon" self.assertEqual(word_sub(_in), _out)
46d64030c8724f016233703922cbc619eef2c179
examples/push_pull/architect.py
examples/push_pull/architect.py
from functions import print_message from osbrain.core import Proxy pusher = Proxy('Pusher') puller = Proxy('Puller') addr = pusher.bind('push') puller.connect(addr, print_message) puller.run() pusher.send(addr, 'Hello world!')
from functions import print_message from osbrain.core import Proxy pusher = Proxy('Pusher') puller = Proxy('Puller') addr = pusher.bind('PUSH', alias='push') puller.connect(addr, handler=print_message) puller.run() pusher.send('push', 'Hello, world!')
Update push_pull example to work with latest changes
Update push_pull example to work with latest changes
Python
apache-2.0
opensistemas-hub/osbrain
--- +++ @@ -5,8 +5,8 @@ pusher = Proxy('Pusher') puller = Proxy('Puller') -addr = pusher.bind('push') -puller.connect(addr, print_message) +addr = pusher.bind('PUSH', alias='push') +puller.connect(addr, handler=print_message) puller.run() -pusher.send(addr, 'Hello world!') +pusher.send('push', 'Hello, world!')
ae14d59b40d18d8a5399286d356bdf6cae58994e
yuicompressor/yuicompressor.py
yuicompressor/yuicompressor.py
# -*- coding: utf-8 -*- from pelican import signals from subprocess import call import logging import os logger = logging.getLogger(__name__) # Display command output on DEBUG and TRACE SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG """ Minify CSS and JS files in output path with Yuicompressor from Yahoo Required : pip install yuicompressor """ def minify(pelican): """ Minify CSS and JS with YUI Compressor :param pelican: The Pelican instance """ for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']): for name in filenames: if os.path.splitext(name)[1] in ('.css','.js'): filepath = os.path.join(dirpath, name) logger.info('minifiy %s', filepath) verbose = '-v' if SHOW_OUTPUT else '' call("yuicompressor {} --charset utf-8 {} -o {}".format( verbose, filepath, filepath), shell=True) def register(): signals.finalized.connect(minify)
# -*- coding: utf-8 -*- from pelican import signals from subprocess import call import logging import os logger = logging.getLogger(__name__) # Display command output on DEBUG and TRACE SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG """ Minify CSS and JS files in output path with Yuicompressor from Yahoo Required : pip install yuicompressor """ def minify(pelican): """ Minify CSS and JS with YUI Compressor :param pelican: The Pelican instance """ for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']): for name in filenames: if os.path.splitext(name)[1] in ('.css','.js'): filepath = os.path.join(dirpath, name) logger.info('minify %s', filepath) verbose = '-v' if SHOW_OUTPUT else '' call("yuicompressor {} --charset utf-8 {} -o {}".format( verbose, filepath, filepath), shell=True) def register(): signals.finalized.connect(minify)
Fix typo in log message
Fix typo in log message
Python
agpl-3.0
danmackinlay/pelican-plugins,MarkusH/pelican-plugins,mikitex70/pelican-plugins,howthebodyworks/pelican-plugins,howthebodyworks/pelican-plugins,talha131/pelican-plugins,mortada/pelican-plugins,MarkusH/pelican-plugins,xsteadfastx/pelican-plugins,howthebodyworks/pelican-plugins,danmackinlay/pelican-plugins,danmackinlay/pelican-plugins,UHBiocomputation/pelican-plugins,rlaboiss/pelican-plugins,rlaboiss/pelican-plugins,xsteadfastx/pelican-plugins,talha131/pelican-plugins,howthebodyworks/pelican-plugins,talha131/pelican-plugins,danmackinlay/pelican-plugins,MarkusH/pelican-plugins,xsteadfastx/pelican-plugins,UHBiocomputation/pelican-plugins,rlaboiss/pelican-plugins,mortada/pelican-plugins,UHBiocomputation/pelican-plugins,MarkusH/pelican-plugins,mortada/pelican-plugins,talha131/pelican-plugins,mikitex70/pelican-plugins,mortada/pelican-plugins,mikitex70/pelican-plugins,UHBiocomputation/pelican-plugins,MarkusH/pelican-plugins,rlaboiss/pelican-plugins,mortada/pelican-plugins,xsteadfastx/pelican-plugins,mikitex70/pelican-plugins,talha131/pelican-plugins
--- +++ @@ -25,7 +25,7 @@ for name in filenames: if os.path.splitext(name)[1] in ('.css','.js'): filepath = os.path.join(dirpath, name) - logger.info('minifiy %s', filepath) + logger.info('minify %s', filepath) verbose = '-v' if SHOW_OUTPUT else '' call("yuicompressor {} --charset utf-8 {} -o {}".format( verbose, filepath, filepath), shell=True)
b223107cbed5ea4c01b98c8e6abcebd1e380d04d
example_project/posts/urls.py
example_project/posts/urls.py
from django.conf.urls import patterns, url from .views import PostListView, PostDetailView urlpatterns = patterns('', url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'), url(r'$', PostListView.as_view(), name='list'), )
from django.conf.urls import patterns, url from .views import PostListView, PostDetailView urlpatterns = patterns('', url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'), url(r'/$', PostListView.as_view(), name='list'), )
Fix appending slash in example project
Fix appending slash in example project
Python
mit
jazzband/django-embed-video,mpachas/django-embed-video,yetty/django-embed-video,mpachas/django-embed-video,jazzband/django-embed-video,yetty/django-embed-video
--- +++ @@ -4,5 +4,5 @@ urlpatterns = patterns('', url(r'(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'), - url(r'$', PostListView.as_view(), name='list'), + url(r'/$', PostListView.as_view(), name='list'), )
904d0fe5c357390f90d7ec9dd9833288a01f7328
unnaturalcode/compile_error.py
unnaturalcode/compile_error.py
#!/usr/bin/python # Copyright 2017 Joshua Charles Campbell # # This file is part of UnnaturalCode. # # UnnaturalCode is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # UnnaturalCode 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from six import integer_types class CompileError(object): def __init__(self, filename=None, line=None, column=None, functionname=None, text=None, errorname=None): assert line is not None assert isintance(line, integer_types) self.filename = filename self.line = line self.functionname = functionname self.text = text self.errorname = errorname if column is not None: assert isintance(column, integer_types) self.column = column """ Compile result should be a list of CompileError objects, or if compile was successful, None (no list at all). """
#!/usr/bin/python # Copyright 2017 Joshua Charles Campbell # # This file is part of UnnaturalCode. # # UnnaturalCode is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # UnnaturalCode 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from six import integer_types class CompileError(object): def __init__(self, filename=None, line=None, column=None, functionname=None, text=None, errorname=None): assert line is not None assert isinstance(line, integer_types) self.filename = filename self.line = line self.functionname = functionname self.text = text self.errorname = errorname if column is not None: assert isintance(column, integer_types) self.column = column """ Compile result should be a list of CompileError objects, or if compile was successful, None (no list at all). """
Update compiler_error; fixed typo line 30
Update compiler_error; fixed typo line 30
Python
agpl-3.0
orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode
--- +++ @@ -27,7 +27,7 @@ text=None, errorname=None): assert line is not None - assert isintance(line, integer_types) + assert isinstance(line, integer_types) self.filename = filename self.line = line self.functionname = functionname
39da25f8d221605012c629b3d08478cfe858df36
poradnia/cases/migrations/0024_auto_20150809_2148.py
poradnia/cases/migrations/0024_auto_20150809_2148.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Count def delete_empty(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Case = apps.get_model("cases", "Case") pks = Case.objects.annotate(record_count=Count('record')).filter(record_count=0).values('id') Case.objects.filter(pk__in=pks).update(status='2') class Migration(migrations.Migration): dependencies = [ ('cases', '0023_auto_20150809_2131'), ('records', '0006_auto_20150503_1741'), ] operations = [ migrations.RunPython(delete_empty) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Count def delete_empty(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Case = apps.get_model("cases", "Case") pks = [x[0] for x in Case.objects.annotate(record_count=Count('record')).filter(record_count=0).values_list('id')] Case.objects.filter(pk__in=pks).update(status='2') class Migration(migrations.Migration): dependencies = [ ('cases', '0023_auto_20150809_2131'), ('records', '0006_auto_20150503_1741'), ] operations = [ migrations.RunPython(delete_empty) ]
Fix case migrations for MySQL
Fix case migrations for MySQL
Python
mit
watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl
--- +++ @@ -9,7 +9,7 @@ # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Case = apps.get_model("cases", "Case") - pks = Case.objects.annotate(record_count=Count('record')).filter(record_count=0).values('id') + pks = [x[0] for x in Case.objects.annotate(record_count=Count('record')).filter(record_count=0).values_list('id')] Case.objects.filter(pk__in=pks).update(status='2')
286cba2b3e7cf323835acd07f1e3bb510d74bcb2
biopsy/tests.py
biopsy/tests.py
# -*- coding: utf-8 -*- from django.test import TestCase from django.db import models from biopsy.models import Biopsy class BiopsyTest(TestCase): def biopy_test(self): biopsy = Biopsy( clinical_information= "clinica", macroscopic= "macroscopia", microscopic= "microscopia", conclusion= "conclusao", notes= "nota", footer= "legenda" ) biopsy.save() self.assertEquals("clinica",biopsy.clinical_information) self.assertEquals("macroscopia",biopsy.macroscopic) self.assertEquals("microscopia",biopsy.microscopic) self.assertEquals("conclusao",biopsy.conclusion) self.assertEquals("nota",biopsy.notes) self.assertEquals("legenda",biopsy.footer)
# -*- coding: utf-8 -*- from django.test import TestCase from django.db import models from biopsy.models import Biopsy class BiopsyTest(TestCase): def biopy_test(self): biopsy = Biopsy( clinical_information= "clinica", macroscopic= "macroscopia", microscopic= "microscopia", conclusion= "conclusao", notes= "nota", footer= "legenda", status = "status", exam = "exame" ) biopsy.save() self.assertEquals("clinica",biopsy.clinical_information) self.assertEquals("macroscopia",biopsy.macroscopic) self.assertEquals("microscopia",biopsy.microscopic) self.assertEquals("conclusao",biopsy.conclusion) self.assertEquals("nota",biopsy.notes) self.assertEquals("legenda",biopsy.footer) self.assertEquals("status",biopsy.status) self.assertEquals("exame",biopsy.exam)
Add status and exam in test Biopsy
Add status and exam in test Biopsy
Python
mit
msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub
--- +++ @@ -12,7 +12,9 @@ microscopic= "microscopia", conclusion= "conclusao", notes= "nota", - footer= "legenda" + footer= "legenda", + status = "status", + exam = "exame" ) biopsy.save() @@ -23,3 +25,5 @@ self.assertEquals("conclusao",biopsy.conclusion) self.assertEquals("nota",biopsy.notes) self.assertEquals("legenda",biopsy.footer) + self.assertEquals("status",biopsy.status) + self.assertEquals("exame",biopsy.exam)
d0ec3ee9b974fb6956c32e8dfdd6d20ea4da7cff
pwndbg/inthook.py
pwndbg/inthook.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This hook is necessary for compatibility with Python2.7 versions of GDB since they cannot directly cast to integer a gdb.Value object that is not already an integer type. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import gdb import pwndbg.typeinfo if sys.version_info < (3,0): import __builtin__ as builtins _int = builtins.int # We need this class to get isinstance(7, xint) to return True class IsAnInt(type): def __instancecheck__(self, other): return isinstance(other, _int) class xint(builtins.int): __metaclass__ = IsAnInt def __new__(cls, value, *a, **kw): if isinstance(value, gdb.Value): if pwndbg.typeinfo.is_pointer(value): value = value.cast(pwndbg.typeinfo.ulong) else: value = value.cast(pwndbg.typeinfo.long) return _int(_int(value, *a, **kw)) builtins.int = xint globals()['int'] = xint # Additionally, we need to compensate for Python2 else: import builtins builtins.long = int globals()['long'] = int
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This hook is necessary for compatibility with Python2.7 versions of GDB since they cannot directly cast to integer a gdb.Value object that is not already an integer type. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import gdb import pwndbg.typeinfo if sys.version_info < (3,0): import __builtin__ as builtins else: import builtins _int = builtins.int # We need this class to get isinstance(7, xint) to return True class IsAnInt(type): def __instancecheck__(self, other): return isinstance(other, _int) class xint(builtins.int): __metaclass__ = IsAnInt def __new__(cls, value, *a, **kw): if isinstance(value, gdb.Value): if pwndbg.typeinfo.is_pointer(value): value = value.cast(pwndbg.typeinfo.ulong) else: value = value.cast(pwndbg.typeinfo.long) return _int(_int(value, *a, **kw)) builtins.int = xint globals()['int'] = xint if sys.version_info >= (3,0): builtins.long = xint globals()['long'] = xint
Add int hook to Python3
Add int hook to Python3 Fixes #120
Python
mit
pwndbg/pwndbg,cebrusfs/217gdb,cebrusfs/217gdb,pwndbg/pwndbg,cebrusfs/217gdb,chubbymaggie/pwndbg,disconnect3d/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,0xddaa/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,zachriggle/pwndbg,anthraxx/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg
--- +++ @@ -18,28 +18,30 @@ if sys.version_info < (3,0): import __builtin__ as builtins - _int = builtins.int - - # We need this class to get isinstance(7, xint) to return True - class IsAnInt(type): - def __instancecheck__(self, other): - return isinstance(other, _int) - - class xint(builtins.int): - __metaclass__ = IsAnInt - def __new__(cls, value, *a, **kw): - if isinstance(value, gdb.Value): - if pwndbg.typeinfo.is_pointer(value): - value = value.cast(pwndbg.typeinfo.ulong) - else: - value = value.cast(pwndbg.typeinfo.long) - return _int(_int(value, *a, **kw)) - - builtins.int = xint - globals()['int'] = xint - - # Additionally, we need to compensate for Python2 else: import builtins - builtins.long = int - globals()['long'] = int + +_int = builtins.int + +# We need this class to get isinstance(7, xint) to return True +class IsAnInt(type): + def __instancecheck__(self, other): + return isinstance(other, _int) + +class xint(builtins.int): + __metaclass__ = IsAnInt + def __new__(cls, value, *a, **kw): + if isinstance(value, gdb.Value): + if pwndbg.typeinfo.is_pointer(value): + value = value.cast(pwndbg.typeinfo.ulong) + else: + value = value.cast(pwndbg.typeinfo.long) + return _int(_int(value, *a, **kw)) + +builtins.int = xint +globals()['int'] = xint + +if sys.version_info >= (3,0): + builtins.long = xint + globals()['long'] = xint +
caf2806124df489f28ceadf2db5d4abfdd27aae7
core/management/commands/send_tweets.py
core/management/commands/send_tweets.py
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Fix typo in field name
Fix typo in field name
Python
agpl-3.0
enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz
--- +++ @@ -8,7 +8,7 @@ help = "Send out tweets." def handle(self, *args, **options): - for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): + for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, @@ -21,7 +21,7 @@ status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e - tweet.failed_trails += 1 + tweet.failed_trials += 1 tweet.save() continue
92aa388d1b58c0e88979d299cc8deabab811f926
tests/test_webapps/filestotest/rest_routing.py
tests/test_webapps/filestotest/rest_routing.py
"""Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('error/:action/:id', controller='error') # CUSTOM ROUTES HERE map.resource('restsample', 'restsamples') map.connect('/:controller/index', action='index') map.connect('/:controller/:action/') map.connect('/:controller/:action/:id') return map
"""Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('error/:action/:id', controller='error') # CUSTOM ROUTES HERE map.resource('restsample', 'restsamples') map.connect('/:controller/:action') map.connect('/:controller/:action/:id') return map
Update to reflect not having trailing slashes
Update to reflect not having trailing slashes
Python
bsd-3-clause
obeattie/pylons,obeattie/pylons
--- +++ @@ -20,8 +20,7 @@ # CUSTOM ROUTES HERE map.resource('restsample', 'restsamples') - map.connect('/:controller/index', action='index') - map.connect('/:controller/:action/') + map.connect('/:controller/:action') map.connect('/:controller/:action/:id') return map
c8a0279d421c2837e4f7e4ef1eaf2cc9cb94210c
scripts/mkstdlibs.py
scripts/mkstdlibs.py
#!/usr/bin/env python3 from sphinx.ext.intersphinx import fetch_inventory URL = "https://docs.python.org/{}/objects.inv" PATH = "isort/stdlibs/py{}.py" VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")] DOCSTRING = """ File contains the standard library of Python {}. DO NOT EDIT. If the standard library changes, a new list should be created using the mkstdlibs.py script. """ class FakeConfig: intersphinx_timeout = None tls_verify = True class FakeApp: srcdir = "" config = FakeConfig() for version_info in VERSIONS: version = ".".join(version_info) url = URL.format(version) invdata = fetch_inventory(FakeApp(), "", url) modules = set() for module in invdata["py:module"]: root, *_ = module.split(".") if root not in ["__future__", "__main__"]: modules.add(root) path = PATH.format("".join(version_info)) with open(path, "w") as stdlib_file: docstring = DOCSTRING.format(version) stdlib_file.write(f'"""{docstring}"""\n\n') stdlib_file.write("stdlib = {\n") for module in sorted(modules): stdlib_file.write(f' "{module}",\n') stdlib_file.write("}\n")
#!/usr/bin/env python3 from sphinx.ext.intersphinx import fetch_inventory URL = "https://docs.python.org/{}/objects.inv" PATH = "isort/stdlibs/py{}.py" VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")] DOCSTRING = """ File contains the standard library of Python {}. DO NOT EDIT. If the standard library changes, a new list should be created using the mkstdlibs.py script. """ class FakeConfig: intersphinx_timeout = None tls_verify = True user_agent = "" class FakeApp: srcdir = "" config = FakeConfig() for version_info in VERSIONS: version = ".".join(version_info) url = URL.format(version) invdata = fetch_inventory(FakeApp(), "", url) modules = set() for module in invdata["py:module"]: root, *_ = module.split(".") if root not in ["__future__", "__main__"]: modules.add(root) path = PATH.format("".join(version_info)) with open(path, "w") as stdlib_file: docstring = DOCSTRING.format(version) stdlib_file.write(f'"""{docstring}"""\n\n') stdlib_file.write("stdlib = {\n") for module in sorted(modules): stdlib_file.write(f' "{module}",\n') stdlib_file.write("}\n")
Update script to include empty user agent
Update script to include empty user agent
Python
mit
PyCQA/isort,PyCQA/isort
--- +++ @@ -4,7 +4,7 @@ URL = "https://docs.python.org/{}/objects.inv" PATH = "isort/stdlibs/py{}.py" -VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")] +VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")] DOCSTRING = """ File contains the standard library of Python {}. @@ -17,6 +17,7 @@ class FakeConfig: intersphinx_timeout = None tls_verify = True + user_agent = "" class FakeApp:
4160fd07d428e26c4de6aee280d948f5044f2c9e
kimochi/scripts/initializedb.py
kimochi/scripts/initializedb.py
import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, Base, User, Site, SiteAPIKey, ) def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: DBSession.add(User(email='[email protected]', password='test', admin=True)) DBSession.add(Site(name='asd', key='80d621df066348e5938a469730ae0cab')) DBSession.add(SiteAPIKey(site_id=1, key='GIKfxIcIHPbM0uX9PrQ1To29Pb2on0pa'))
import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from pyramid.scripts.common import parse_vars from ..models import ( DBSession, Base, User, Site, SiteAPIKey, ) def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: user = User(email='[email protected]', password='test', admin=True) DBSession.add(user) site = Site(name='asd', key='80d621df066348e5938a469730ae0cab') DBSession.add(site) DBSession.add(SiteAPIKey(site_id=1, key='GIKfxIcIHPbM0uX9PrQ1To29Pb2on0pa')) site.users.append(user)
Make sure we add the user to the site as well
Make sure we add the user to the site as well
Python
mit
matslindh/kimochi,matslindh/kimochi
--- +++ @@ -39,6 +39,9 @@ Base.metadata.create_all(engine) with transaction.manager: - DBSession.add(User(email='[email protected]', password='test', admin=True)) - DBSession.add(Site(name='asd', key='80d621df066348e5938a469730ae0cab')) + user = User(email='[email protected]', password='test', admin=True) + DBSession.add(user) + site = Site(name='asd', key='80d621df066348e5938a469730ae0cab') + DBSession.add(site) DBSession.add(SiteAPIKey(site_id=1, key='GIKfxIcIHPbM0uX9PrQ1To29Pb2on0pa')) + site.users.append(user)
525bfce19f593cb598669cdf2eec46747a4b6952
goodreadsapi.py
goodreadsapi.py
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages'] book = {} for k in keys: book[k] = book_data[k] if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages', 'publication_year'] book = {} for k in keys: book[k] = book_data.get(k) if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
Add `publication_year` to return data
Add `publication_year` to return data
Python
mit
avinassh/Reddit-GoodReads-Bot
--- +++ @@ -24,10 +24,10 @@ except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', - 'num_pages'] + 'num_pages', 'publication_year'] book = {} for k in keys: - book[k] = book_data[k] + book[k] = book_data.get(k) if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors)
4c2dd9dd6dc0f9ff66a36a114c90897dab8da7e5
goodreadsapi.py
goodreadsapi.py
#!/usr/bin/env python import re import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages'] book = {} for k in keys: book[k] = book_data[k] if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_details_by_id(goodreads_id): api_url = 'http://goodreads.com/book/show/{0}?format=xml&key={1}' r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages'] book = {} for k in keys: book[k] = book_data[k] if type(book_data['authors']['author']) == list: authors = [author['name'] for author in book_data['authors']['author']] authors = ', '.join(authors) else: authors = book_data['authors']['author']['name'] book['authors'] = authors return book
Update GR API to handle Expat Error
Update GR API to handle Expat Error
Python
mit
avinassh/Reddit-GoodReads-Bot
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python import re +from xml.parsers.expat import ExpatError import requests import xmltodict @@ -20,7 +21,7 @@ r = requests.get(api_url.format(goodreads_id, goodreads_api_key)) try: book_data = xmltodict.parse(r.content)['GoodreadsResponse']['book'] - except (TypeError, KeyError): + except (TypeError, KeyError, ExpatError): return False keys = ['title', 'average_rating', 'ratings_count', 'description', 'num_pages']
7615bfa2a58db373c3e102e7d0205f265d9c4d57
dxtbx/tst_dxtbx.py
dxtbx/tst_dxtbx.py
from boost.python import streambuf from dxtbx import read_uint16 f = open('/Users/graeme/data/demo/insulin_1_001.img', 'rb') hdr = f.read(512) l = read_uint16(streambuf(f), 2304 * 2304) print sum(l)
from boost.python import streambuf from dxtbx import read_uint16 import sys from dxtbx.format.Registry import Registry format = Registry.find(sys.argv[1]) i = format(sys.argv[1]) size = i.get_detector().get_image_size() f = open(sys.argv[1], 'rb') hdr = f.read(512) l = read_uint16(streambuf(f), int(size[0] * size[1])) print sum(l)
Clean up test case: not finished yet though
Clean up test case: not finished yet though
Python
bsd-3-clause
dials/dials,dials/dials,dials/dials,dials/dials,dials/dials
--- +++ @@ -1,6 +1,13 @@ from boost.python import streambuf from dxtbx import read_uint16 -f = open('/Users/graeme/data/demo/insulin_1_001.img', 'rb') +import sys +from dxtbx.format.Registry import Registry + +format = Registry.find(sys.argv[1]) +i = format(sys.argv[1]) +size = i.get_detector().get_image_size() + +f = open(sys.argv[1], 'rb') hdr = f.read(512) -l = read_uint16(streambuf(f), 2304 * 2304) +l = read_uint16(streambuf(f), int(size[0] * size[1])) print sum(l)
675c05bd685d550e3c46137f2f52dcdb125cefa0
tests/test_speed.py
tests/test_speed.py
import os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import glob import fnmatch import traceback import logging import numpy import pytest import lasio test_dir = os.path.dirname(__file__) egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn) stegfn = lambda vers, fn: os.path.join(os.path.dirname(__file__), "examples", vers, fn) logger = logging.getLogger(__name__) def test_read_v12_sample_big(): l = lasio.read(stegfn("1.2", "sample_big.las"))
import os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import glob import fnmatch import traceback import logging import numpy import pytest import lasio test_dir = os.path.dirname(__file__) egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn) stegfn = lambda vers, fn: os.path.join(os.path.dirname(__file__), "examples", vers, fn) logger = logging.getLogger(__name__) def read_file(): las = lasio.read(stegfn("1.2", "sample_big.las")) def test_read_v12_sample_big(benchmark): benchmark(read_file)
Add benchmark test for the speed of reading a LAS file
Add benchmark test for the speed of reading a LAS file To run it you need to have `pytest-benchmark` installed, and run the tests using: ``` $ pytest lasio/tests/tests_speed.py ``` To compare two branches, you need to run and store the benchmark from the first branch e.g. master and then run and compare the benchmark from the second branch. e.g. ``` $ git checkout master $ mkdir ..\lasio-benchmarks $ pytest tests/\test_speed.py --benchmark-autosave --benchmark-storage ..\lasio-benchmarks --benchmark-compare
Python
mit
kwinkunks/lasio,kinverarity1/lasio,kinverarity1/las-reader
--- +++ @@ -19,5 +19,8 @@ logger = logging.getLogger(__name__) -def test_read_v12_sample_big(): - l = lasio.read(stegfn("1.2", "sample_big.las")) +def read_file(): + las = lasio.read(stegfn("1.2", "sample_big.las")) + +def test_read_v12_sample_big(benchmark): + benchmark(read_file)
f5477c30cb9fdbbb250800d379458e641ef97fd4
dwitter/serializers.py
dwitter/serializers.py
from rest_framework import serializers from dwitter.models import Dweet, Comment from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'username') class CommentSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') posted = serializers.ReadOnlyField() class Meta: model = Comment fields = ('text', 'posted', 'reply_to', 'author') class DweetSerializer(serializers.ModelSerializer): latest_comments = serializers.SerializerMethodField() reply_to = serializers.PrimaryKeyRelatedField(queryset=Dweet.objects.all()) class Meta: model = Dweet fields = ('pk', 'code', 'posted', 'author', 'likes','reply_to', 'latest_comments') def get_latest_comments(self, obj): cmnts = obj.comments.all().order_by('-posted') return CommentSerializer(cmnts[:3], many=True).data
from rest_framework import serializers from dwitter.models import Dweet, Comment from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'username') class CommentSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') posted = serializers.ReadOnlyField() class Meta: model = Comment fields = ('text', 'posted', 'reply_to', 'author') class DweetSerializer(serializers.ModelSerializer): latest_comments = serializers.SerializerMethodField() reply_to = serializers.PrimaryKeyRelatedField(queryset=Dweet.objects.all()) class Meta: model = Dweet fields = ('pk', 'code', 'posted', 'author', 'likes','reply_to', 'latest_comments') def get_latest_comments(self, obj): cmnts = obj.comments.all().order_by('-posted') return CommentSerializer(cmnts[:3], many=True).data
Remove whitespace at end of file
Remove whitespace at end of file
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
--- +++ @@ -25,8 +25,3 @@ def get_latest_comments(self, obj): cmnts = obj.comments.all().order_by('-posted') return CommentSerializer(cmnts[:3], many=True).data - - - - -
16bd36fe6fdcbd267413eabe1997337165775f28
taOonja/game/admin.py
taOonja/game/admin.py
from django.contrib import admin # Register your models here.
from django.contrib import admin from game.models import * class LocationAdmin(admin.ModelAdmin): model = Location admin.site.register(Location, LocationAdmin) class DetailAdmin(admin.ModelAdmin): model = Detail admin.site.register(Detail, DetailAdmin)
Add models to Admin Panel
Add models to Admin Panel
Python
mit
Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja
--- +++ @@ -1,3 +1,13 @@ from django.contrib import admin +from game.models import * -# Register your models here. +class LocationAdmin(admin.ModelAdmin): + model = Location + +admin.site.register(Location, LocationAdmin) + +class DetailAdmin(admin.ModelAdmin): + + model = Detail + +admin.site.register(Detail, DetailAdmin)
f620dde75d65e1175829b524eec00d54e20bb2be
tests/test_views.py
tests/test_views.py
from __future__ import unicode_literals from djet.testcases import ViewTestCase from pgallery.views import TaggedPhotoListView class TaggedPhotoListViewTestCase(ViewTestCase): view_class = TaggedPhotoListView def test_tag_in_response(self): request = self.factory.get() response = self.view(request, tag='example_tag') self.assertContains(response, 'example_tag')
from __future__ import unicode_literals from django.contrib.auth.models import AnonymousUser from djet.testcases import ViewTestCase from pgallery.views import GalleryListView, TaggedPhotoListView from .factories import GalleryFactory, UserFactory class GalleryListViewTestCase(ViewTestCase): view_class = GalleryListView def test_draft_invisible(self): gallery = GalleryFactory(status='draft', title="Draft gallery") request = self.factory.get(user=AnonymousUser()) response = self.view(request) self.assertNotContains(response, gallery.title) def test_draft_visible_for_staff(self): gallery = GalleryFactory(status='draft', title="Draft gallery") user = UserFactory(is_staff=True) request = self.factory.get(user=user) response = self.view(request) self.assertContains(response, gallery.title) class TaggedPhotoListViewTestCase(ViewTestCase): view_class = TaggedPhotoListView def test_tag_in_response(self): request = self.factory.get() response = self.view(request, tag='example_tag') self.assertContains(response, 'example_tag')
Test drafts visible for staff users only.
Test drafts visible for staff users only.
Python
mit
zsiciarz/django-pgallery,zsiciarz/django-pgallery
--- +++ @@ -1,8 +1,28 @@ from __future__ import unicode_literals + +from django.contrib.auth.models import AnonymousUser from djet.testcases import ViewTestCase -from pgallery.views import TaggedPhotoListView +from pgallery.views import GalleryListView, TaggedPhotoListView +from .factories import GalleryFactory, UserFactory + + +class GalleryListViewTestCase(ViewTestCase): + view_class = GalleryListView + + def test_draft_invisible(self): + gallery = GalleryFactory(status='draft', title="Draft gallery") + request = self.factory.get(user=AnonymousUser()) + response = self.view(request) + self.assertNotContains(response, gallery.title) + + def test_draft_visible_for_staff(self): + gallery = GalleryFactory(status='draft', title="Draft gallery") + user = UserFactory(is_staff=True) + request = self.factory.get(user=user) + response = self.view(request) + self.assertContains(response, gallery.title) class TaggedPhotoListViewTestCase(ViewTestCase):
7f1db4023f2310529822d721379b1019aaf320fc
tablib/formats/_df.py
tablib/formats/_df.py
""" Tablib - DataFrame Support. """ import sys if sys.version_info[0] > 2: from io import BytesIO else: from cStringIO import StringIO as BytesIO from pandas import DataFrame import tablib from tablib.compat import unicode title = 'df' extensions = ('df', ) def detect(stream): """Returns True if given stream is a DataFrame.""" try: DataFrame(stream) return True except ValueError: return False def export_set(dset, index=None): """Returns DataFrame representation of DataBook.""" dataframe = DataFrame(dset.dict, columns=dset.headers) return dataframe def import_set(dset, in_stream): """Returns dataset from DataFrame.""" dset.wipe() dset.dict = in_stream.to_dict(orient='records')
""" Tablib - DataFrame Support. """ import sys if sys.version_info[0] > 2: from io import BytesIO else: from cStringIO import StringIO as BytesIO try: from pandas import DataFrame except ImportError: DataFrame = None import tablib from tablib.compat import unicode title = 'df' extensions = ('df', ) def detect(stream): """Returns True if given stream is a DataFrame.""" if DataFrame is None: return False try: DataFrame(stream) return True except ValueError: return False def export_set(dset, index=None): """Returns DataFrame representation of DataBook.""" if DataFrame is None: raise NotImplementedError( 'DataFrame Format requires `pandas` to be installed.' ' Try `pip install tablib[pandas]`.') dataframe = DataFrame(dset.dict, columns=dset.headers) return dataframe def import_set(dset, in_stream): """Returns dataset from DataFrame.""" dset.wipe() dset.dict = in_stream.to_dict(orient='records')
Raise NotImplementedError if pandas is not installed
Raise NotImplementedError if pandas is not installed
Python
mit
kennethreitz/tablib
--- +++ @@ -10,7 +10,10 @@ else: from cStringIO import StringIO as BytesIO -from pandas import DataFrame +try: + from pandas import DataFrame +except ImportError: + DataFrame = None import tablib @@ -21,6 +24,8 @@ def detect(stream): """Returns True if given stream is a DataFrame.""" + if DataFrame is None: + return False try: DataFrame(stream) return True @@ -30,6 +35,10 @@ def export_set(dset, index=None): """Returns DataFrame representation of DataBook.""" + if DataFrame is None: + raise NotImplementedError( + 'DataFrame Format requires `pandas` to be installed.' + ' Try `pip install tablib[pandas]`.') dataframe = DataFrame(dset.dict, columns=dset.headers) return dataframe
5761364149b3171521cb4f72f591dc5f5cbd77d6
temp-sensor02/main.py
temp-sensor02/main.py
from machine import Pin from ds18x20 import DS18X20 import onewire import time import machine import ujson import urequests def posttocloud(temperature): keystext = open("sparkfun_keys.json").read() keys = ujson.loads(keystext) url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&temp=" + str(temperature) #data = {'temp':temperature} #data['private_key'] = keys['privateKey'] #print (keys['inputUrl']) #print(keys['privateKey']) #datajson = ujson.dumps(data) #print (datajson) resp = urequests.request("POST", url) print (resp.text) while True: p = Pin(2) # Data Line is on GPIO2 aka D4 ow = onewire.OneWire(p) ds = DS18X20(ow) lstrom = ds.scan() #Assuming we have only 1 device connected rom = lstrom[0] ds.convert_temp() time.sleep_ms(750) temperature = round(float(ds.read_temp(rom)),1) #print("Temperature: {:02.1f}".format(temperature)) posttocloud(temperature) time.sleep(10)
from machine import Pin from ds18x20 import DS18X20 import onewire import time import ujson import urequests def posttocloud(temperature): keystext = open("sparkfun_keys.json").read() keys = ujson.loads(keystext) params = {} params['temp'] = temperature params['private_key'] = keys['privateKey'] #data.sparkfun doesn't support putting data into the POST Body. #We had to add the data to the query string #Copied the Dirty hack from #https://github.com/matze/python-phant/blob/24edb12a449b87700a4f736e43a5415b1d021823/phant/__init__.py payload_str = "&".join("%s=%s" % (k, v) for k, v in params.items()) url = keys['inputUrl'] + "?" + payload_str resp = urequests.request("POST", url) print (resp.text) while True: p = Pin(2) # Data Line is on GPIO2 aka D4 ow = onewire.OneWire(p) ds = DS18X20(ow) lstrom = ds.scan() #Assuming we have only 1 device connected rom = lstrom[0] ds.convert_temp() time.sleep_ms(750) temperature = round(float(ds.read_temp(rom)),1) #print("Temperature: {:02.1f}".format(temperature)) posttocloud(temperature) time.sleep(10)
Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code
Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code
Python
mit
fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout
--- +++ @@ -2,20 +2,23 @@ from ds18x20 import DS18X20 import onewire import time -import machine import ujson import urequests def posttocloud(temperature): + keystext = open("sparkfun_keys.json").read() keys = ujson.loads(keystext) - url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&temp=" + str(temperature) - #data = {'temp':temperature} - #data['private_key'] = keys['privateKey'] - #print (keys['inputUrl']) - #print(keys['privateKey']) - #datajson = ujson.dumps(data) - #print (datajson) + params = {} + params['temp'] = temperature + params['private_key'] = keys['privateKey'] + + #data.sparkfun doesn't support putting data into the POST Body. + #We had to add the data to the query string + #Copied the Dirty hack from + #https://github.com/matze/python-phant/blob/24edb12a449b87700a4f736e43a5415b1d021823/phant/__init__.py + payload_str = "&".join("%s=%s" % (k, v) for k, v in params.items()) + url = keys['inputUrl'] + "?" + payload_str resp = urequests.request("POST", url) print (resp.text)
a427fab365ff3404748cdf8fb70b4ff542e81922
fabfile.py
fabfile.py
from armstrong.dev.tasks import * from d51.django.virtualenv.base import VirtualEnvironment from fabric.api import task settings = { 'DEBUG': True, 'INSTALLED_APPS': ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'armstrong.core.arm_sections', 'armstrong.core.arm_sections.tests.arm_sections_support', 'lettuce.django', 'south', 'mptt', ), 'ROOT_URLCONF': 'armstrong.core.arm_sections.tests.arm_sections_support.urls', 'SITE_ID': 1, } main_app = "arm_sections" tested_apps = (main_app, ) @task def lettuce(verbosity=4): defaults = settings defaults["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", }, } v = VirtualEnvironment() v.run(defaults) v.call_command("syncdb", interactive=False) v.call_command("harvest", apps='armstrong.core.arm_sections', verbosity=verbosity)
from armstrong.dev.tasks import * from fabric.api import task settings = { 'DEBUG': True, 'INSTALLED_APPS': ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'armstrong.core.arm_sections', 'armstrong.core.arm_sections.tests.arm_sections_support', 'lettuce.django', 'south', 'mptt', ), 'ROOT_URLCONF': 'armstrong.core.arm_sections.tests.arm_sections_support.urls', 'SITE_ID': 1, } full_name = "armstrong.core.arm_sections" main_app = "arm_sections" tested_apps = (main_app, )
Update to use the spec command in the latest armstrong.dev
Update to use the spec command in the latest armstrong.dev
Python
apache-2.0
texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,armstrong/armstrong.core.arm_sections
--- +++ @@ -1,5 +1,4 @@ from armstrong.dev.tasks import * -from d51.django.virtualenv.base import VirtualEnvironment from fabric.api import task @@ -21,20 +20,6 @@ 'SITE_ID': 1, } +full_name = "armstrong.core.arm_sections" main_app = "arm_sections" tested_apps = (main_app, ) - -@task -def lettuce(verbosity=4): - defaults = settings - defaults["DATABASES"] = { - "default": { - "ENGINE": "django.db.backends.sqlite3", - "NAME": ":memory:", - }, - } - v = VirtualEnvironment() - v.run(defaults) - v.call_command("syncdb", interactive=False) - v.call_command("harvest", apps='armstrong.core.arm_sections', - verbosity=verbosity)
327ba1797045235a420ce095d2cd2cac5257a1e9
tutorials/models.py
tutorials/models.py
from django.db import models # Create your models here. class Tutorial(models.Model): title = models.TextField() html = models.TextField() markdown = models.TextField()
from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField()
Add missing Fields according to mockup, Add markdownfield
Add missing Fields according to mockup, Add markdownfield
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
--- +++ @@ -1,8 +1,14 @@ from django.db import models +from markdownx.models import MarkdownxField # Create your models here. + class Tutorial(models.Model): + # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? + + # Category = models.TextField() title = models.TextField() html = models.TextField() - markdown = models.TextField() + markdown = MarkdownxField() + # Level = models.IntegerField()
c058bd887348340c91ae3633d341031569114131
smrt/__init__.py
smrt/__init__.py
# -*- coding: utf-8 -*- # # Author: Taylor Smith <[email protected]> # # The SMRT module import sys import os __version__ = '0.1' try: # this var is injected in the setup build to enable # the retrieval of the version number without actually # importing the un-built submodules. __SMRT_SETUP__ except NameError: __SMRT_SETUP__ = False if __SMRT_SETUP__: sys.stderr.write('Partial import of SMRT during the build process.' + os.linesep) else: __all__ = [ 'autoencode', 'balance' ] # top-level imports from .balance import smrt_balance, smote_balance from .autoencode import AutoEncoder
# -*- coding: utf-8 -*- # # Author: Taylor Smith <[email protected]> # # The SMRT module import sys import os __version__ = '0.2' try: # this var is injected in the setup build to enable # the retrieval of the version number without actually # importing the un-built submodules. __SMRT_SETUP__ except NameError: __SMRT_SETUP__ = False if __SMRT_SETUP__: sys.stderr.write('Partial import of SMRT during the build process.' + os.linesep) else: __all__ = [ 'autoencode', 'balance' ] # top-level imports from .balance import smrt_balance, smote_balance from .autoencode import AutoEncoder
Increment version to force build/coveralls
Increment version to force build/coveralls
Python
bsd-3-clause
tgsmith61591/smrt,tgsmith61591/smrt
--- +++ @@ -7,7 +7,7 @@ import sys import os -__version__ = '0.1' +__version__ = '0.2' try: # this var is injected in the setup build to enable
ea164b66cc93d5d7fb1f89a0297ea0a8da926b54
server/core/views.py
server/core/views.py
from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def app(request): return render(request, 'html.html')
from django.shortcuts import render def app(request): return render(request, 'html.html')
Stop inserting the CSRF token into the main app page
Stop inserting the CSRF token into the main app page
Python
mit
Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers
--- +++ @@ -1,7 +1,4 @@ from django.shortcuts import render -from django.views.decorators.csrf import ensure_csrf_cookie - -@ensure_csrf_cookie def app(request): return render(request, 'html.html')
6c314451e002db3213ff61d1e6935c091b605a8d
server/nurly/util.py
server/nurly/util.py
import traceback class NurlyResult(): def __init__(self, code='200 OK', head=None, body=''): self.head = {} if type(head) != dict else head self.body = body self.code = code class NurlyStatus(): ST_IDLE = 0 ST_BUSY = 1 ST_STOP = 2 ST_MAP = { ST_IDLE: 'IDLE', ST_BUSY: 'BUSY', ST_STOP: 'STOP', } def __init__(self, proc, pipe): self.proc = proc self.pipe = pipe self.fileno = self.pipe.fileno self.count = 0 self.state = NurlyStatus.ST_IDLE @staticmethod def label(code, short=False): return NurlyStatus.ST_MAP[code] if not short else NurlyStatus.ST_MAP[code][0] class NurlyAction(): def __init__(self, func, path='/', verb='GET'): self.func = func self.path = path self.verb = verb def __call__(self, env, res, parent): if env['REQUEST_METHOD'] == self.verb and env['PATH_INFO'].startswith(self.path): try: self.func(env, res, parent) except: res.code = '500 Server Error' res.body = traceback.format_exc() return True return False
import traceback import types class NurlyResult(): def __init__(self, code='200 OK', head=None, body=''): self.head = {} if type(head) != dict else head self.body = body self.code = code class NurlyStatus(): ST_IDLE = 0 ST_BUSY = 1 ST_STOP = 2 ST_MAP = { ST_IDLE: 'IDLE', ST_BUSY: 'BUSY', ST_STOP: 'STOP', } def __init__(self, proc, pipe): self.proc = proc self.pipe = pipe self.fileno = self.pipe.fileno self.count = 0 self.state = NurlyStatus.ST_IDLE @staticmethod def label(code, short=False): return NurlyStatus.ST_MAP[code] if not short else NurlyStatus.ST_MAP[code][0] class NurlyAction(): def __init__(self, func, path='/', verb='GET'): self.func = func if type(func) is not types.ModuleType else getattr(func, func.__name__.split('.')[-1]) self.path = path self.verb = verb def __call__(self, env, res, parent): if env['REQUEST_METHOD'] == self.verb and env['PATH_INFO'].startswith(self.path): try: self.func(env, res, parent) except: res.code = '500 Server Error' res.body = traceback.format_exc() return True return False
Support using a module as a call back if it has an function attribute by the same name.
Support using a module as a call back if it has an function attribute by the same name.
Python
mit
mk23/nurly,mk23/nurly,mk23/nurly,mk23/nurly
--- +++ @@ -1,4 +1,5 @@ import traceback +import types class NurlyResult(): def __init__(self, code='200 OK', head=None, body=''): @@ -34,7 +35,7 @@ class NurlyAction(): def __init__(self, func, path='/', verb='GET'): - self.func = func + self.func = func if type(func) is not types.ModuleType else getattr(func, func.__name__.split('.')[-1]) self.path = path self.verb = verb
293d50438fab81e74ab4559df7a4f7aa7cfd8f03
etcdocker/container.py
etcdocker/container.py
import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=False): # Ensure container is running with specified params containers = util.get_containers() found = False for pc in containers: if "/%s" % self.name in pc['Names']: found = True full_image = "%s:%s" % ( self.params.get('image'), self.params.get('tag')) if (pc['Status'].startswith('Up') and pc['Image'] == full_image and not force_restart): return break client = docker.Client() # Start our container if found: # Shut down old container first client.stop(self.name, 5) client.remove_container(self.name) # Create container with specified args client.create_container( image=self.params.get('image'), detach=True, volumes_from=self.params.get('volumes_from'), volumes=self.params.get('volumes'), name=self.name) # Start 'er up client.start( container=self.name, port_bindings=self.params.get('ports'), privileged=self.params.get('privileged'))
import ast import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=False): # Ensure container is running with specified params containers = util.get_containers() found = False for pc in containers: if "/%s" % self.name in pc['Names']: found = True full_image = "%s:%s" % ( self.params.get('image'), self.params.get('tag')) if (pc['Status'].startswith('Up') and pc['Image'] == full_image and not force_restart): return break client = docker.Client() # Start our container if found: # Shut down old container first client.stop(self.name, 5) client.remove_container(self.name) # Convert our ports into a dict if necessary ports = ast.literal_eval(self.params.get('ports')) # Create container with specified args client.create_container( image=self.params.get('image'), detach=True, volumes_from=self.params.get('volumes_from'), volumes=self.params.get('volumes'), ports=ports.keys(), name=self.name) # Start 'er up client.start( container=self.name, port_bindings=ports, privileged=self.params.get('privileged'))
Convert port list to dict
Convert port list to dict
Python
mit
CloudBrewery/docrane
--- +++ @@ -1,3 +1,4 @@ +import ast import docker from etcdocker import util @@ -34,16 +35,20 @@ client.stop(self.name, 5) client.remove_container(self.name) + # Convert our ports into a dict if necessary + ports = ast.literal_eval(self.params.get('ports')) + # Create container with specified args client.create_container( image=self.params.get('image'), detach=True, volumes_from=self.params.get('volumes_from'), volumes=self.params.get('volumes'), + ports=ports.keys(), name=self.name) # Start 'er up client.start( container=self.name, - port_bindings=self.params.get('ports'), + port_bindings=ports, privileged=self.params.get('privileged'))
c30181eed55cc1f2af6da4ee8608f4f2052ceb38
serverless_helpers/__init__.py
serverless_helpers/__init__.py
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <[email protected]> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): """Recursively load .env files starting from `path` Given the path "foo/bar/.env" and a directory structure like: foo \---.env \---bar \---.env Values from foo/bar/.env and foo/.env will both be loaded, but values in foo/bar/.env will take precedence over values from foo/.env """ import os path = os.path.abspath(path) path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <[email protected]> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): """Recursively load .env files starting from `path` Usage: from your Lambda function, call load_envs with the value __file__ to give it the current location as a place to start looking for .env files. import serverless_helpers serverless_helpers.load_envs(__file__) Given the path "foo/bar/myfile.py" and a directory structure like: foo \---.env \---bar \---.env \---myfile.py Values from foo/bar/.env and foo/.env will both be loaded, but values in foo/bar/.env will take precedence over values from foo/.env """ import os path = os.path.abspath(path) path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
Document calling with __file__ as starting env path
Document calling with __file__ as starting env path
Python
mit
serverless/serverless-helpers-py
--- +++ @@ -6,11 +6,18 @@ def load_envs(path): """Recursively load .env files starting from `path` - Given the path "foo/bar/.env" and a directory structure like: + Usage: from your Lambda function, call load_envs with the value __file__ to + give it the current location as a place to start looking for .env files. + + import serverless_helpers + serverless_helpers.load_envs(__file__) + + Given the path "foo/bar/myfile.py" and a directory structure like: foo \---.env \---bar \---.env + \---myfile.py Values from foo/bar/.env and foo/.env will both be loaded, but values in foo/bar/.env will take precedence over values from foo/.env
5b5ad0e4fc97f540fdbda459adaa1ccc68cf6712
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/urls.py
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/urls.py
from django.urls import path from . import views app_name = "users" urlpatterns = [ path("", view=views.UserListView.as_view(), name="list"), path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"), path("~update/", view=views.UserUpdateView.as_view(), name="update"), path( "<str:username>", view=views.UserDetailView.as_view(), name="detail", ), ]
from django.urls import path from . import views app_name = "users" urlpatterns = [ path("", view=views.UserListView.as_view(), name="list"), path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"), path("~update/", view=views.UserUpdateView.as_view(), name="update"), path( "<str:username>/", view=views.UserDetailView.as_view(), name="detail", ), ]
Fix Py.Test unittests fail on new cookie
Fix Py.Test unittests fail on new cookie Fixes #1674
Python
bsd-3-clause
topwebmaster/cookiecutter-django,trungdong/cookiecutter-django,mistalaba/cookiecutter-django,ad-m/cookiecutter-django,luzfcb/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,mistalaba/cookiecutter-django,Parbhat/cookiecutter-django-foundation,Parbhat/cookiecutter-django-foundation,mistalaba/cookiecutter-django,trungdong/cookiecutter-django,ad-m/cookiecutter-django,luzfcb/cookiecutter-django,ryankanno/cookiecutter-django,topwebmaster/cookiecutter-django,topwebmaster/cookiecutter-django,ad-m/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,topwebmaster/cookiecutter-django,trungdong/cookiecutter-django,luzfcb/cookiecutter-django,Parbhat/cookiecutter-django-foundation,pydanny/cookiecutter-django,ad-m/cookiecutter-django,mistalaba/cookiecutter-django,Parbhat/cookiecutter-django-foundation,pydanny/cookiecutter-django,pydanny/cookiecutter-django,luzfcb/cookiecutter-django,ryankanno/cookiecutter-django
--- +++ @@ -8,7 +8,7 @@ path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"), path("~update/", view=views.UserUpdateView.as_view(), name="update"), path( - "<str:username>", + "<str:username>/", view=views.UserDetailView.as_view(), name="detail", ),
922acafc793b3d32f625fe18cd52b2bfd59a5f96
ansible/wsgi.py
ansible/wsgi.py
from pecan.deploy import deploy app = deploy('/opt/web/draughtcraft/src/production.py') from paste.exceptions.errormiddleware import ErrorMiddleware app = ErrorMiddleware( app, error_email=app.conf.error_email, from_address=app.conf.error_email, smtp_server=app.conf.error_smtp_server, smtp_username=app.conf.error_email, smtp_password=app.conf.error_password, smtp_use_tls=True )
from pecan import conf from pecan.deploy import deploy app = deploy('/opt/web/draughtcraft/src/production.py') from paste.exceptions.errormiddleware import ErrorMiddleware app = ErrorMiddleware( app, error_email=conf.error_email, from_address=conf.error_email, smtp_server=conf.error_smtp_server, smtp_username=conf.error_email, smtp_password=conf.error_password, smtp_use_tls=True )
Fix a bug in the WSGI entrypoint.
Fix a bug in the WSGI entrypoint.
Python
bsd-3-clause
ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft
--- +++ @@ -1,13 +1,14 @@ +from pecan import conf from pecan.deploy import deploy app = deploy('/opt/web/draughtcraft/src/production.py') from paste.exceptions.errormiddleware import ErrorMiddleware app = ErrorMiddleware( app, - error_email=app.conf.error_email, - from_address=app.conf.error_email, - smtp_server=app.conf.error_smtp_server, - smtp_username=app.conf.error_email, - smtp_password=app.conf.error_password, + error_email=conf.error_email, + from_address=conf.error_email, + smtp_server=conf.error_smtp_server, + smtp_username=conf.error_email, + smtp_password=conf.error_password, smtp_use_tls=True )
b78b14214e317d1149b37bcdcf5ba0681212431b
rapidsms/contrib/httptester/models.py
rapidsms/contrib/httptester/models.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from django.db import models DIRECTION_CHOICES = ( ("I", "Incoming"), ("O", "Outgoing")) class HttpTesterMessage(models.Model): direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES) identity = models.CharField(max_length=100) text = models.TextField()
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from django.db import models DIRECTION_CHOICES = ( ("I", "Incoming"), ("O", "Outgoing")) class HttpTesterMessage(models.Model): direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES) identity = models.CharField(max_length=100) text = models.TextField() class Meta(object): # Ordering by id will order by when they were created, which is # typically what we want ordering = ['id']
Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added. Branch: feature/httptester-update
Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added. Branch: feature/httptester-update
Python
bsd-3-clause
eHealthAfrica/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,ehealthafrica-ci/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,caktus/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,peterayeni/rapidsms,caktus/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms,caktus/rapidsms
--- +++ @@ -13,3 +13,8 @@ direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES) identity = models.CharField(max_length=100) text = models.TextField() + + class Meta(object): + # Ordering by id will order by when they were created, which is + # typically what we want + ordering = ['id']
92eaa47b70d48874da032a21fbbd924936c0d518
code/csv2map.py
code/csv2map.py
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # [email protected] import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('csv', help='CSV file to convert') parser.add_argument('map', help='MAP file to create') args = parser.parse_args() # read the csv file and convert it into a MAP file with open(args.csv, 'r') as fdr: with open(args.map, 'w') as fdw: for line in fdr: line_split = line.split(',') fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])])) fdw.close() fdr.close() if __name__ == "__main__": main()
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # [email protected] import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles """) parser.add_argument('map', help='MAP file to create') args = parser.parse_args() # read the csv file and convert it into a MAP file with open(args.csv, 'r') as fdr: with open(args.map, 'w') as fdw: for line in fdr: line_split = line.split(',') fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])])) fdw.close() fdr.close() if __name__ == "__main__": main()
Add info about csv fields
Add info about csv fields
Python
mit
chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan
--- +++ @@ -8,9 +8,11 @@ def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') - parser.add_argument('csv', help='CSV file to convert') + parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles + """) parser.add_argument('map', help='MAP file to create') args = parser.parse_args() + # read the csv file and convert it into a MAP file with open(args.csv, 'r') as fdr: with open(args.map, 'w') as fdw: