commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
9aa17b90b8f3413f0621cc25a686774dd809dc84
frigg/projects/serializers.py
frigg/projects/serializers.py
from rest_framework import serializers from frigg.builds.serializers import BuildInlineSerializer from .models import Project class ProjectSerializer(serializers.ModelSerializer): builds = BuildInlineSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', 'should_clone_with_ssh', 'builds' )
from rest_framework import serializers from frigg.builds.serializers import BuildInlineSerializer from .models import Project class EnvironmentVariableSerializer(serializers.ModelSerializer): def to_representation(self, instance): representation = super().to_representation(instance) if instance.is_secret: representation.value = '[secret]' return representation class Meta: model = Project fields = ( 'id', 'key', 'is_secret', 'value', ) class ProjectSerializer(serializers.ModelSerializer): builds = BuildInlineSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', 'should_clone_with_ssh', 'builds' )
Add drf serializer for environment variables
feat: Add drf serializer for environment variables
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
4bcf35efcfc751a1c337fdcf50d23d9d06549717
demo/apps/catalogue/models.py
demo/apps/catalogue/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page class Category(Page): """ user oscars category as a wagtail Page. this works becuase they both use treebeard """ name = models.CharField( verbose_name=_('name'), max_length=255, help_text=_("Category name") ) from oscar.apps.catalogue.models import * # noqa
from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page class Category(Page): """ The Oscars Category as a Wagtail Page This works because they both use Treebeard """ name = models.CharField( verbose_name=_('name'), max_length=255, help_text=_("Category name") ) from oscar.apps.catalogue.models import * # noqa
Fix typo in doc string
Fix typo in doc string
Python
mit
pgovers/oscar-wagtail-demo,pgovers/oscar-wagtail-demo
0a69133e44810dd0469555f62ec49eba120e6ecc
apps/storybase/utils.py
apps/storybase/utils.py
"""Shared utility functions""" from django.template.defaultfilters import slugify as django_slugify def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, converts spaces to hyphens, and truncates to 50 characters. """ slug = django_slugify(value) slug = slug[:50] return slug.rstrip('-')
"""Shared utility functions""" from django.conf import settings from django.template.defaultfilters import slugify as django_slugify from django.utils.translation import ugettext as _ def get_language_name(language_code): """Convert a language code into its full (localized) name""" languages = dict(settings.LANGUAGES) return _(languages[language_code]) def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, converts spaces to hyphens, and truncates to 50 characters. """ slug = django_slugify(value) slug = slug[:50] return slug.rstrip('-')
Add utility function to convert a language code to a its full name
Add utility function to convert a language code to a its full name
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
62b1c49c67c72c36d4177c657df49a4700586c06
djangoTemplate/urls.py
djangoTemplate/urls.py
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', include('social.apps.django_app.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^tosp_auth/', include('tosp_auth.urls')) ]
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^tosp_auth/', include('tosp_auth.urls')) ]
Change the url patters from python_social_auth to social_django
Change the url patters from python_social_auth to social_django
Python
mit
tosp/djangoTemplate,tosp/djangoTemplate
62f4c6b7d24176284054b13c4e1e9b6d631c7b42
basicTest.py
basicTest.py
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither continueLoop = True while continueLoop: slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) # Handle quitting for event in pygame.event.get(): if event.type == pygame.QUIT: continueLoop = False time.sleep(0.01)
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither def run_a_frame(): snakey.changeXBy(1) SoExcited.changeDirectionBy(1) slither.runMainLoop(run_a_frame)
Update basic test Now uses the new format by @BookOwl.
Update basic test Now uses the new format by @BookOwl.
Python
mit
PySlither/Slither,PySlither/Slither
890190f40b9061f7bfa15bbd7e56abc0f1b7d44a
redmapper/__init__.py
redmapper/__init__.py
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
Make fitters available at main import level.
Make fitters available at main import level.
Python
apache-2.0
erykoff/redmapper,erykoff/redmapper
aa8234d1e6b4916e6945468a2bc5772df2d53e28
bot/admin.py
bot/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data')
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') @admin.register(models.DiscordChannel) class DiscordBotAdmin(admin.ModelAdmin): list_display = ('name', 'channel_id', 'server_id')
Add Discord Admin for debugging.
Add Discord Admin for debugging.
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
e9fbd541b3fcb84c6d2de9ba1de53886730a67fa
common.py
common.py
import os def get_project_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir
import os def get_project_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir def get_yourproject_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir
Add new changes to th branch
Add new changes to th branch
Python
mit
nvthanh1/Skypybot
53ad3866b8dfbd012748e4ad7d7ed7025d491bd0
src/alexa-main.py
src/alexa-main.py
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Application ID") if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
REVERT remove application id validation
REVERT remove application id validation
Python
mit
mauriceyap/ccm-assistant
5cd674ec764be72bb3e94c0b56fdf733a4a1c885
Discord/utilities/errors.py
Discord/utilities/errors.py
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class MissingPermissions(CommandError): '''Missing Permissions''' pass class MissingCapability(CommandError): '''Missing Capability''' def __init__(self, permissions): self.permissions = permissions class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass class AudioNotPlaying(AudioError): '''Audio Not Playing''' pass class AudioAlreadyDone(AudioError): '''Audio Already Done playing''' pass
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class MissingPermissions(CommandError): '''Missing Permissions''' pass class MissingCapability(CommandError): '''Missing Capability''' def __init__(self, permissions): self.permissions = permissions class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass class AudioNotPlaying(AudioError): '''Audio Not Playing''' pass
Remove Audio Already Done error
[Discord] Remove Audio Already Done error
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
c97e5cf11fc21e2ef4ee04779a424e4d6a2b96ae
tools/perf/metrics/__init__.py
tools/perf/metrics/__init__.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def CustomizeBrowserOptions(self, options): """Add browser options that are required by this metric. Some metrics do not have any special browser options that need to be added, and they do not need to override this method; by default, no browser options are added. To add options here, call options.AppendExtraBrowserArg(arg). """ pass def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
Add CustomizeBrowserOptions method to Metric base class
Add CustomizeBrowserOptions method to Metric base class BUG=271177 Review URL: https://chromiumcodereview.appspot.com/22938004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217198 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
mogoweb/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,jaruba/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,patrickm/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,Jonekee/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,mogoweb/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,ltilve/chromium,patrickm/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,patrickm/chromium.src,M4sse/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,jaruba/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,dushu1203/chromium.src,ltilve/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,dednal/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ltilve/chromium,patrickm/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src
f9c7a911411429972929bb4372b370192bd4cf8a
altair/examples/interactive_layered_crossfilter.py
altair/examples/interactive_layered_crossfilter.py
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # blue background with selection background = base.add_selection(brush) # yellow highlights on the transformed data highlight = base.encode( color=alt.value('goldenrod') ).transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # gray background with selection background = base.encode( color=alt.value('#ddd') ).add_selection(brush) # blue highlights on the transformed data highlight = base.transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
Update crossfilter to gray/blue scheme
Update crossfilter to gray/blue scheme Same as in https://vega.github.io/editor/#/examples/vega-lite/interactive_layered_crossfilter
Python
bsd-3-clause
altair-viz/altair,jakevdp/altair
6064db3000f2aeec66a775345d22b8a2b421497f
astropy/utils/tests/test_gzip.py
astropy/utils/tests/test_gzip.py
import io import os from ...tests.helper import pytest from .. import gzip def test_gzip(tmpdir): fd = gzip.GzipFile(str(tmpdir.join("test.gz")), 'wb') fd = io.TextIOWrapper(fd, encoding='utf8')
import io import os from ...tests.helper import pytest from .. import gzip pytestmark = pytest.mark.skipif("sys.version_info < (3,0)") def test_gzip(tmpdir): fd = gzip.GzipFile(str(tmpdir.join("test.gz")), 'wb') fd = io.TextIOWrapper(fd, encoding='utf8')
Fix gzip test for Python 2.6
Fix gzip test for Python 2.6
Python
bsd-3-clause
tbabej/astropy,bsipocz/astropy,lpsinger/astropy,MSeifert04/astropy,StuartLittlefair/astropy,larrybradley/astropy,DougBurke/astropy,stargaser/astropy,pllim/astropy,stargaser/astropy,MSeifert04/astropy,tbabej/astropy,lpsinger/astropy,joergdietrich/astropy,astropy/astropy,joergdietrich/astropy,dhomeier/astropy,kelle/astropy,kelle/astropy,saimn/astropy,MSeifert04/astropy,bsipocz/astropy,funbaker/astropy,kelle/astropy,pllim/astropy,dhomeier/astropy,StuartLittlefair/astropy,pllim/astropy,dhomeier/astropy,MSeifert04/astropy,larrybradley/astropy,mhvk/astropy,funbaker/astropy,StuartLittlefair/astropy,stargaser/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,astropy/astropy,AustereCuriosity/astropy,tbabej/astropy,DougBurke/astropy,AustereCuriosity/astropy,funbaker/astropy,pllim/astropy,lpsinger/astropy,larrybradley/astropy,funbaker/astropy,dhomeier/astropy,mhvk/astropy,joergdietrich/astropy,saimn/astropy,kelle/astropy,lpsinger/astropy,stargaser/astropy,mhvk/astropy,bsipocz/astropy,StuartLittlefair/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,joergdietrich/astropy,astropy/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,astropy/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,mhvk/astropy,aleksandr-bakanov/astropy,saimn/astropy,larrybradley/astropy,larrybradley/astropy,tbabej/astropy,pllim/astropy,bsipocz/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,astropy/astropy,kelle/astropy,lpsinger/astropy,AustereCuriosity/astropy,tbabej/astropy,saimn/astropy,DougBurke/astropy
853c727c472efc09df90cb016bd05f81d4cf5e8e
beetle_preview/__init__.py
beetle_preview/__init__.py
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config.get('port', 5000) self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config.get('port', 5000) self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: print('Preview available at http://0.0.0.0:{}/'.format(self.port)) httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
Print a line telling where the site is available at
Print a line telling where the site is available at
Python
mit
cknv/beetle-preview
b474c7368f3a8152296acf9cad7459510b71ada5
fs/opener/sshfs.py
fs/opener/sshfs.py
from ._base import Opener from ._registry import registry @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) return ssh_fs.opendir(dir_path) if dir_path else ssh_fs
from ._base import Opener from ._registry import registry from ..subfs import ClosingSubFS @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) if dir_path: return ssh_fs.opendir(dir_path, factory=ClosingSubFS) else: return ssh_fs
Fix SSHOpener to use the new ClosingSubFS
Fix SSHOpener to use the new ClosingSubFS
Python
lgpl-2.1
althonos/fs.sshfs
f70bbbdadc044a76f7b90b2cac0191353a6a5048
depfinder.py
depfinder.py
import ast def get_imported_libs(code): tree = ast.parse(code) # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second imports = [name.name.split('.')[0] for t in tree.body if type(t) == ast.Import for name in t.names] # ast.ImportFrom represents lines like 'from foo import bar' import_froms = [t.module.split('.')[0] for t in tree.body if type(t) == ast.ImportFrom if t.module] return imports + import_froms
import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second if type(t) == ast.Import: imports.extend([name.name.split('.')[0] for name in t.names]) # ast.ImportFrom represents lines like 'from foo import bar' # t.level == 0 is to get rid of 'from .foo import bar' and higher levels # of relative importing if type(t) == ast.ImportFrom: if t.level > 0: if conf['ignore_relative_imports'] or not t.module: continue else: imports.append(t.module.split('.')[0]) return list(imports) def iterate_over_library(path_to_source_code): libs = set() for parent, folders, files in os.walk(path_to_source_code): for file in files: if file.endswith('.py'): print('.', end='') full_file_path = os.path.join(parent, file) with open(full_file_path, 'r') as f: code = f.read() libs.update(set(get_imported_libs(code))) if conf['ignore_builtin_modules']: if not conf['pyver']: pyver = '%s.%s' % (sys.version_info.major, sys.version_info.minor) std_libs = stdlib_list("3.4") # print(std_libs) libs = [lib for lib in libs if lib not in std_libs] return libs
Rework the import finding logic
MNT: Rework the import finding logic
Python
bsd-3-clause
ericdill/depfinder
2a8c4790bd432fc4dc0fdda64c0cea4f76fac9ff
feincms/context_processors.py
feincms/context_processors.py
from feincms.module.page.models import Page def add_page_if_missing(request): # If this attribute exists, the a page object has been registered already # by some other part of the code. We let it decide, which page object it # wants to pass into the template if hasattr(request, '_feincms_page'): return {} return { 'feincms_page': Page.objects.best_match_for_request(request), }
from feincms.module.page.models import Page def add_page_if_missing(request): # If this attribute exists, the a page object has been registered already # by some other part of the code. We let it decide, which page object it # wants to pass into the template if hasattr(request, '_feincms_page'): return {} try: return { 'feincms_page': Page.objects.best_match_for_request(request), } except Page.DoesNotExist: return {}
Fix add_page_if_missing context processor when no pages exist yet
Fix add_page_if_missing context processor when no pages exist yet
Python
bsd-3-clause
matthiask/feincms2-content,hgrimelid/feincms,nickburlett/feincms,michaelkuty/feincms,michaelkuty/feincms,hgrimelid/feincms,feincms/feincms,pjdelport/feincms,joshuajonah/feincms,pjdelport/feincms,michaelkuty/feincms,joshuajonah/feincms,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,pjdelport/feincms,matthiask/django-content-editor,mjl/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,matthiask/feincms2-content,mjl/feincms,joshuajonah/feincms,hgrimelid/feincms,nickburlett/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,feincms/feincms,matthiask/django-content-editor
efa36e1013e44fa75f6a77a74bd8bf21f3120976
django_facebook/models.py
django_facebook/models.py
from django.db import models from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images') date_of_birth = models.DateField(blank=True, null=True) raw_data = models.TextField(blank=True, null=True) def __unicode__(self): return self.user.__unicode__() class Meta: abstract = True def post_facebook_registration(self): ''' Behaviour after registering with facebook ''' url = reverse('facebook_connect') response = HttpResponseRedirect(url) response.set_cookie('fresh_registration', self.user.id) return response
from django.db import models from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images', max_length=255) date_of_birth = models.DateField(blank=True, null=True) raw_data = models.TextField(blank=True, null=True) def __unicode__(self): return self.user.__unicode__() class Meta: abstract = True def post_facebook_registration(self): ''' Behaviour after registering with facebook ''' url = reverse('facebook_connect') response = HttpResponseRedirect(url) response.set_cookie('fresh_registration', self.user.id) return response
Allow for a longer image path
Allow for a longer image path My profile image for example does not fit in the default VARCHAR(100)
Python
bsd-3-clause
fivejjs/Django-facebook,troygrosfield/Django-facebook,danosaure/Django-facebook,rafaelgontijo/Django-facebook-fork,abendleiter/Django-facebook,pjdelport/Django-facebook,fivejjs/Django-facebook,abendleiter/Django-facebook,abendleiter/Django-facebook,andriisoldatenko/Django-facebook,ganescoo/Django-facebook,VishvajitP/Django-facebook,javipalanca/Django-facebook,fyndsi/Django-facebook,christer155/Django-facebook,cyrixhero/Django-facebook,Fiedzia/Django-facebook,tuxos/Django-facebook,troygrosfield/Django-facebook,QLGu/Django-facebook,PeterWangPo/Django-facebook,PeterWangPo/Django-facebook,troygrosfield/Django-facebook,pjdelport/Django-facebook,andriisoldatenko/Django-facebook,tuxos/Django-facebook,danosaure/Django-facebook,abhijo89/Django-facebook,cyrixhero/Django-facebook,andriisoldatenko/Django-facebook,cyrixhero/Django-facebook,abhijo89/Django-facebook,VishvajitP/Django-facebook,sitsbeyou/Django-facebook,ganescoo/Django-facebook,sitsbeyou/Django-facebook,takeshineshiro/Django-facebook,christer155/Django-facebook,javipalanca/Django-facebook,takeshineshiro/Django-facebook,fyndsi/Django-facebook,fyndsi/Django-facebook,QLGu/Django-facebook,jcpyun/Django-facebook,takeshineshiro/Django-facebook,selwin/Django-facebook,christer155/Django-facebook,javipalanca/Django-facebook,rafaelgontijo/Django-facebook-fork,PeterWangPo/Django-facebook,selwin/Django-facebook,jcpyun/Django-facebook,Shekharrajak/Django-facebook,Shekharrajak/Django-facebook,ganescoo/Django-facebook,VishvajitP/Django-facebook,rafaelgontijo/Django-facebook-fork,jcpyun/Django-facebook,danosaure/Django-facebook,abhijo89/Django-facebook,QLGu/Django-facebook,Fiedzia/Django-facebook,Shekharrajak/Django-facebook,tuxos/Django-facebook,andriisoldatenko/Django-facebook,Fiedzia/Django-facebook,selwin/Django-facebook,fivejjs/Django-facebook,pjdelport/Django-facebook,sitsbeyou/Django-facebook
78a03f0b0cbc948a6c9fb215e9051d099c528a82
src/app.py
src/app.py
from flask import Flask from flask import render_template, url_for import parse_data app = Flask(__name__) @app.route("/dashboard") def dashboard(): data = parse_data.load_and_format_data() title = 'Grand Bargain Monitoring' return render_template('dashboard.html', data=data, heading=title, page_title=title) if __name__ == "__main__": app.run()
from flask import Flask from flask import render_template, url_for import parse_data app = Flask(__name__) @app.route("/dashboard") def dashboard(): data = parse_data.load_and_format_data() title = 'Grand Bargain Transparency Dashboard' return render_template('dashboard.html', data=data, heading=title, page_title=title) if __name__ == "__main__": app.run()
Change page title and heading
Change page title and heading
Python
mit
devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring
6b7e32c98fa8a11dcd7bbbadaa2a057e4ff0ce90
f5_os_test/__init__.py
f5_os_test/__init__.py
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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. # __version__ = '0.2.0'
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 random import string __version__ = '0.2.0' def random_name(prefix, N): """Creates a name with random characters. Returns a new string created from an input prefix appended with a set of random characters. The number of random characters appended to the prefix string is defined by the N parameter. For example, random_name('test_', 6) might return "test_FR3N5Y" :param string prefix: String to append randoms characters. :param int N: Number of random characters to append. """ return prefix + ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(N))
Add function to create name strings with random characters
Add function to create name strings with random characters Issues: Fixes #48 Problem: Need a function that will generate names with random chars. Analysis: Added new function, random_name(). Tests: test_solution.py
Python
apache-2.0
F5Networks/f5-openstack-test,pjbreaux/f5-openstack-test
1a98b29293ccfab6534a48402414e89726d8e5bb
Python/pomodoro.py
Python/pomodoro.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() spr.call(['notify-send', 'Started new pomodoro']) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start.strftime("%H:%M:%S")) ] ) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() start_str = start.strftime("%H:%M:%S") spr.call(['notify-send', '--app-name', 'POMODORO', '--icon', 'dialog-information', 'New pomodoro', 'From: {}'.format(start_str)]) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start_str ) ] ) if __name__ == "__main__": main()
Set icon, summary for notification
Set icon, summary for notification
Python
bsd-2-clause
familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG
d9a6071674857ceae566d29c7c77a31a5ed5214d
byceps/blueprints/api/decorators.py
byceps/blueprints/api/decorators.py
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): abort(401, www_authenticate='Bearer') return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from werkzeug.datastructures import WWWAuthenticate from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): www_authenticate = WWWAuthenticate('Bearer') abort(401, www_authenticate=www_authenticate) return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
Return proper WWW-Authenticate header if API authentication fails
Return proper WWW-Authenticate header if API authentication fails
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
ab4ae040895c50da6cb0827f6461d1733c7fe30a
tests/test_plugin_states.py
tests/test_plugin_states.py
from contextlib import contextmanager from os import path from unittest import TestCase from canaryd_packages import six from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd.plugin import get_plugin_by_name @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError( 'Broken tests: {0} not in commands'.format(command), ) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name class TestPluginRealStates(TestCase): def run_plugin(self, plugin_name): plugin = get_plugin_by_name(plugin_name) plugin.get_state({}) def test_meta_plugin(self): self.run_plugin('meta') def test_services_plugin(self): self.run_plugin('services') def test_containers_plugin(self): self.run_plugin('containers') @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
Add real plugin state tests for plugins that always work (meta, containers, services).
Add real plugin state tests for plugins that always work (meta, containers, services).
Python
mit
Oxygem/canaryd,Oxygem/canaryd
26dcd1ce43864de77c1cd26065c09cc2b4c4788e
tests/fuzzer/test_random_content.py
tests/fuzzer/test_random_content.py
# Copyright (c) 2016 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert out_len >= exp_min_len and out_len <= exp_max_len
# Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert exp_min_len <= out_len <= exp_max_len
Make use of chained comparisons
Make use of chained comparisons
Python
bsd-3-clause
akosthekiss/fuzzinator,akosthekiss/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator,renatahodovan/fuzzinator,renatahodovan/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator
c79cedf826a3b6ee89e6186954185ef3217dd901
tomviz/python/InvertData.py
tomviz/python/InvertData.py
import tomviz.operators NUMBER_OF_CHUNKS = 10 class InvertOperator(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): from tomviz import utils import numpy as np self.progress.maximum = NUMBER_OF_CHUNKS scalars = utils.get_scalars(dataset) if scalars is None: raise RuntimeError("No scalars found!") result = np.float32(scalars) max = np.amax(scalars) step = 0 for chunk in np.array_split(result, NUMBER_OF_CHUNKS): if self.canceled: return chunk[:] = max - chunk step += 1 self.progress.value = step utils.set_scalars(dataset, result)
import tomviz.operators NUMBER_OF_CHUNKS = 10 class InvertOperator(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): from tomviz import utils import numpy as np self.progress.maximum = NUMBER_OF_CHUNKS scalars = utils.get_scalars(dataset) if scalars is None: raise RuntimeError("No scalars found!") result = np.float32(scalars) min = np.amin(scalars) max = np.amax(scalars) step = 0 for chunk in np.array_split(result, NUMBER_OF_CHUNKS): if self.canceled: return chunk[:] = max - chunk + min step += 1 self.progress.value = step utils.set_scalars(dataset, result)
Add the minimum scalar value to the result of the InvertOperator
Add the minimum scalar value to the result of the InvertOperator Without it, all results would be shifted so the minimum was 0.
Python
bsd-3-clause
OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
47053a42b9053755aad052159dac845b34195297
config/test/__init__.py
config/test/__init__.py
from SCons.Script import * def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \ '--view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
from SCons.Script import * import inspect def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') path = inspect.getfile(inspect.currentframe()) home = os.path.dirname(os.path.abspath(path)) + '/../..' cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \ '--view-failed --view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
Use common testHarness in derived projects
Use common testHarness in derived projects
Python
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
37831f549eddc014ab89cc7dba3616a133c774a2
api/BucketListAPI.py
api/BucketListAPI.py
from flask import Flask, jsonify from modals.modals import User, Bucket, Item from api.__init__ import app, db @app.errorhandler(404) def page_not_found(e): response = jsonify({'error': 'The request can not be completed'}) response.status_code = 404 return response if __name__ == '__main__': app.run()
from flask import Flask, jsonify from modals.modals import User, Bucket, Item from api.__init__ import create_app, db app = create_app('DevelopmentEnv') @app.errorhandler(404) def page_not_found(e): response = jsonify({'error': 'The request can not be completed'}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Add create_app method to __init__.py
Add create_app method to __init__.py
Python
mit
patlub/BucketListAPI,patlub/BucketListAPI
4b5dd61607c9692bb330f89545d5f76d7a1ed221
puzzle/feeds.py
puzzle/feeds.py
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', args=[item.number]) def item_pubdate(self, item): return item.pub_date
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', kwargs={'author': item.user.username, 'number': item.number}) def item_pubdate(self, item): return item.pub_date
Fix linkage in the RSS feed
Fix linkage in the RSS feed
Python
mit
jomoore/threepins,jomoore/threepins,jomoore/threepins
a0ceb84519d1bf735979b3afdfdb8b17621d308b
froide/problem/admin.py
froide/problem/admin.py
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user, resolution=obj.resolution) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
Fix overwriting resolution with empty text
Fix overwriting resolution with empty text
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
1171ade137c54c778a284ef32fdbdcd9e5c1d828
runcommands/runners/result.py
runcommands/runners/result.py
from ..util import cached_property class Result: def __init__(self, return_code, stdout_data, stderr_data, encoding): self.return_code = return_code self.stdout_data = stdout_data self.stderr_data = stderr_data self.encoding = encoding self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout(self): if self.stdout_data: stdout = b''.join(self.stdout_data) stdout = stdout.decode(self.encoding) else: stdout = '' return stdout @cached_property def stderr(self): if self.stderr_data: stderr = b''.join(self.stderr_data) stderr = stderr.decode(self.encoding) else: stderr = '' return stderr @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else [] def __bool__(self): return self.succeeded
from ..util import cached_property class Result: def __init__(self, return_code, stdout_data, stderr_data, encoding): self.return_code = return_code self.stdout_data = stdout_data self.stderr_data = stderr_data self.encoding = encoding self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout(self): if self.stdout_data: stdout = b''.join(self.stdout_data) stdout = stdout.decode(self.encoding) else: stdout = '' return stdout @cached_property def stderr(self): if self.stderr_data: stderr = b''.join(self.stderr_data) stderr = stderr.decode(self.encoding) else: stderr = '' return stderr @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else [] def __bool__(self): return self.succeeded def __str__(self): return self.stdout def __repr__(self): return repr(self.stdout)
Add __repr__() and __str__() to Result
Add __repr__() and __str__() to Result
Python
mit
wylee/runcommands,wylee/runcommands
ed45c8201977aecde226b2e9b060820a8fd677c3
test/functional/rpc_deprecated.py
test/functional/rpc_deprecated.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
Remove test for deprecated createmultsig option
[tests] Remove test for deprecated createmultsig option
Python
mit
guncoin/guncoin,AkioNak/bitcoin,tjps/bitcoin,myriadteam/myriadcoin,tjps/bitcoin,tecnovert/particl-core,vmp32k/litecoin,jamesob/bitcoin,achow101/bitcoin,jtimon/bitcoin,particl/particl-core,DigitalPandacoin/pandacoin,MarcoFalke/bitcoin,kazcw/bitcoin,cdecker/bitcoin,andreaskern/bitcoin,paveljanik/bitcoin,Kogser/bitcoin,andreaskern/bitcoin,Flowdalic/bitcoin,ericshawlinux/bitcoin,guncoin/guncoin,ElementsProject/elements,jambolo/bitcoin,MeshCollider/bitcoin,DigitalPandacoin/pandacoin,dscotese/bitcoin,yenliangl/bitcoin,BTCGPU/BTCGPU,EthanHeilman/bitcoin,qtumproject/qtum,Kogser/bitcoin,guncoin/guncoin,Xekyo/bitcoin,sstone/bitcoin,nikkitan/bitcoin,domob1812/namecore,pataquets/namecoin-core,fujicoin/fujicoin,thrasher-/litecoin,domob1812/namecore,yenliangl/bitcoin,n1bor/bitcoin,CryptArc/bitcoin,jtimon/bitcoin,midnightmagic/bitcoin,jtimon/bitcoin,kallewoof/bitcoin,r8921039/bitcoin,sstone/bitcoin,DigitalPandacoin/pandacoin,GlobalBoost/GlobalBoost,afk11/bitcoin,joshrabinowitz/bitcoin,ahmedbodi/vertcoin,h4x3rotab/BTCGPU,OmniLayer/omnicore,Kogser/bitcoin,midnightmagic/bitcoin,Christewart/bitcoin,Sjors/bitcoin,lateminer/bitcoin,bitcoin/bitcoin,fujicoin/fujicoin,midnightmagic/bitcoin,prusnak/bitcoin,anditto/bitcoin,Xekyo/bitcoin,jnewbery/bitcoin,litecoin-project/litecoin,RHavar/bitcoin,digibyte/digibyte,cdecker/bitcoin,fanquake/bitcoin,jtimon/bitcoin,TheBlueMatt/bitcoin,untrustbank/litecoin,ElementsProject/elements,domob1812/bitcoin,fanquake/bitcoin,AkioNak/bitcoin,domob1812/bitcoin,JeremyRubin/bitcoin,GlobalBoost/GlobalBoost,fujicoin/fujicoin,mm-s/bitcoin,bitcoinsSG/bitcoin,namecoin/namecore,mitchellcash/bitcoin,rnicoll/bitcoin,nikkitan/bitcoin,EthanHeilman/bitcoin,vertcoin/vertcoin,gjhiggins/vcoincore,lateminer/bitcoin,tjps/bitcoin,GroestlCoin/bitcoin,litecoin-project/litecoin,bitcoinknots/bitcoin,jonasschnelli/bitcoin,untrustbank/litecoin,kallewoof/bitcoin,mitchellcash/bitcoin,afk11/bitcoin,jtimon/bitcoin,thrasher-/litecoin,jonasschnelli/bitcoin,Flowdalic/bitcoin,JeremyRubin/bitcoin,h4x3rotab/BTCGPU,prusnak/bitcoin,cdecker/bitcoin,achow101/bitcoin,CryptArc/bitcoin,paveljanik/bitcoin,jnewbery/bitcoin,namecoin/namecoin-core,jlopp/statoshi,jmcorgan/bitcoin,apoelstra/bitcoin,bitcoinknots/bitcoin,MarcoFalke/bitcoin,tecnovert/particl-core,bitcoinsSG/bitcoin,rawodb/bitcoin,bitcoin/bitcoin,peercoin/peercoin,jlopp/statoshi,kallewoof/bitcoin,domob1812/huntercore,ahmedbodi/vertcoin,r8921039/bitcoin,jlopp/statoshi,Bushstar/UFO-Project,DigitalPandacoin/pandacoin,domob1812/huntercore,thrasher-/litecoin,bespike/litecoin,jmcorgan/bitcoin,myriadcoin/myriadcoin,MarcoFalke/bitcoin,Christewart/bitcoin,jnewbery/bitcoin,vmp32k/litecoin,jonasschnelli/bitcoin,kazcw/bitcoin,guncoin/guncoin,paveljanik/bitcoin,midnightmagic/bitcoin,droark/bitcoin,globaltoken/globaltoken,bitcoinsSG/bitcoin,practicalswift/bitcoin,Christewart/bitcoin,jambolo/bitcoin,n1bor/bitcoin,guncoin/guncoin,paveljanik/bitcoin,bitcoin/bitcoin,sstone/bitcoin,GroestlCoin/GroestlCoin,fanquake/bitcoin,mruddy/bitcoin,stamhe/bitcoin,jtimon/bitcoin,RHavar/bitcoin,domob1812/huntercore,h4x3rotab/BTCGPU,kazcw/bitcoin,vmp32k/litecoin,rnicoll/dogecoin,joshrabinowitz/bitcoin,AkioNak/bitcoin,lbryio/lbrycrd,achow101/bitcoin,practicalswift/bitcoin,instagibbs/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,sebrandon1/bitcoin,rnicoll/dogecoin,domob1812/bitcoin,nikkitan/bitcoin,CryptArc/bitcoin,OmniLayer/omnicore,bespike/litecoin,mm-s/bitcoin,wellenreiter01/Feathercoin,TheBlueMatt/bitcoin,ahmedbodi/vertcoin,monacoinproject/monacoin,Sjors/bitcoin,OmniLayer/omnicore,FeatherCoin/Feathercoin,Kogser/bitcoin,JeremyRubin/bitcoin,jambolo/bitcoin,domob1812/namecore,domob1812/namecore,monacoinproject/monacoin,donaloconnor/bitcoin,h4x3rotab/BTCGPU,namecoin/namecoin-core,wellenreiter01/Feathercoin,n1bor/bitcoin,lbryio/lbrycrd,pstratem/bitcoin,fujicoin/fujicoin,peercoin/peercoin,BTCGPU/BTCGPU,myriadteam/myriadcoin,n1bor/bitcoin,sipsorcery/bitcoin,afk11/bitcoin,TheBlueMatt/bitcoin,myriadcoin/myriadcoin,lateminer/bitcoin,ericshawlinux/bitcoin,bespike/litecoin,gjhiggins/vcoincore,domob1812/bitcoin,qtumproject/qtum,tecnovert/particl-core,namecoin/namecoin-core,vertcoin/vertcoin,bespike/litecoin,lateminer/bitcoin,qtumproject/qtum,myriadteam/myriadcoin,afk11/bitcoin,GroestlCoin/bitcoin,peercoin/peercoin,randy-waterhouse/bitcoin,GlobalBoost/GlobalBoost,pstratem/bitcoin,donaloconnor/bitcoin,paveljanik/bitcoin,mm-s/bitcoin,stamhe/bitcoin,FeatherCoin/Feathercoin,pstratem/bitcoin,ajtowns/bitcoin,EthanHeilman/bitcoin,tjps/bitcoin,digibyte/digibyte,GlobalBoost/GlobalBoost,RHavar/bitcoin,jamesob/bitcoin,midnightmagic/bitcoin,joshrabinowitz/bitcoin,rawodb/bitcoin,mitchellcash/bitcoin,CryptArc/bitcoin,JeremyRubin/bitcoin,OmniLayer/omnicore,lbryio/lbrycrd,yenliangl/bitcoin,jmcorgan/bitcoin,untrustbank/litecoin,dscotese/bitcoin,bitcoinsSG/bitcoin,fujicoin/fujicoin,namecoin/namecore,litecoin-project/litecoin,myriadcoin/myriadcoin,alecalve/bitcoin,untrustbank/litecoin,prusnak/bitcoin,TheBlueMatt/bitcoin,mruddy/bitcoin,myriadteam/myriadcoin,alecalve/bitcoin,dscotese/bitcoin,practicalswift/bitcoin,ryanofsky/bitcoin,FeatherCoin/Feathercoin,lbryio/lbrycrd,OmniLayer/omnicore,GlobalBoost/GlobalBoost,vertcoin/vertcoin,Flowdalic/bitcoin,kallewoof/bitcoin,digibyte/digibyte,MarcoFalke/bitcoin,andreaskern/bitcoin,domob1812/huntercore,tjps/bitcoin,n1bor/bitcoin,sstone/bitcoin,fanquake/bitcoin,bitcoinknots/bitcoin,afk11/bitcoin,digibyte/digibyte,Kogser/bitcoin,pstratem/bitcoin,sebrandon1/bitcoin,domob1812/bitcoin,gjhiggins/vcoincore,thrasher-/litecoin,Bushstar/UFO-Project,ahmedbodi/vertcoin,MarcoFalke/bitcoin,ahmedbodi/vertcoin,ajtowns/bitcoin,rnicoll/bitcoin,Bushstar/UFO-Project,litecoin-project/litecoin,yenliangl/bitcoin,lbryio/lbrycrd,achow101/bitcoin,ajtowns/bitcoin,MeshCollider/bitcoin,Flowdalic/bitcoin,MeshCollider/bitcoin,pataquets/namecoin-core,mitchellcash/bitcoin,nikkitan/bitcoin,qtumproject/qtum,particl/particl-core,tjps/bitcoin,vertcoin/vertcoin,Christewart/bitcoin,untrustbank/litecoin,CryptArc/bitcoin,monacoinproject/monacoin,AkioNak/bitcoin,jlopp/statoshi,Sjors/bitcoin,namecoin/namecore,kazcw/bitcoin,droark/bitcoin,bitcoin/bitcoin,Kogser/bitcoin,vmp32k/litecoin,Kogser/bitcoin,thrasher-/litecoin,EthanHeilman/bitcoin,droark/bitcoin,sipsorcery/bitcoin,cdecker/bitcoin,randy-waterhouse/bitcoin,jnewbery/bitcoin,andreaskern/bitcoin,jamesob/bitcoin,andreaskern/bitcoin,ajtowns/bitcoin,randy-waterhouse/bitcoin,rnicoll/bitcoin,GroestlCoin/GroestlCoin,lateminer/bitcoin,jambolo/bitcoin,h4x3rotab/BTCGPU,myriadcoin/myriadcoin,jmcorgan/bitcoin,TheBlueMatt/bitcoin,sipsorcery/bitcoin,particl/particl-core,bespike/litecoin,ryanofsky/bitcoin,achow101/bitcoin,Christewart/bitcoin,EthanHeilman/bitcoin,Kogser/bitcoin,namecoin/namecore,mitchellcash/bitcoin,monacoinproject/monacoin,peercoin/peercoin,globaltoken/globaltoken,particl/particl-core,donaloconnor/bitcoin,namecoin/namecore,GroestlCoin/GroestlCoin,instagibbs/bitcoin,fujicoin/fujicoin,namecoin/namecoin-core,apoelstra/bitcoin,pataquets/namecoin-core,GroestlCoin/bitcoin,namecoin/namecore,donaloconnor/bitcoin,practicalswift/bitcoin,jambolo/bitcoin,sipsorcery/bitcoin,instagibbs/bitcoin,gjhiggins/vcoincore,Christewart/bitcoin,nikkitan/bitcoin,vertcoin/vertcoin,r8921039/bitcoin,globaltoken/globaltoken,apoelstra/bitcoin,myriadcoin/myriadcoin,EthanHeilman/bitcoin,myriadteam/myriadcoin,particl/particl-core,vmp32k/litecoin,stamhe/bitcoin,GroestlCoin/bitcoin,cdecker/bitcoin,jnewbery/bitcoin,ericshawlinux/bitcoin,r8921039/bitcoin,practicalswift/bitcoin,MeshCollider/bitcoin,qtumproject/qtum,ElementsProject/elements,bitcoin/bitcoin,jmcorgan/bitcoin,jamesob/bitcoin,mruddy/bitcoin,DigitalPandacoin/pandacoin,joshrabinowitz/bitcoin,rawodb/bitcoin,OmniLayer/omnicore,vmp32k/litecoin,particl/particl-core,monacoinproject/monacoin,DigitalPandacoin/pandacoin,gjhiggins/vcoincore,randy-waterhouse/bitcoin,RHavar/bitcoin,rawodb/bitcoin,wellenreiter01/Feathercoin,peercoin/peercoin,wellenreiter01/Feathercoin,globaltoken/globaltoken,Xekyo/bitcoin,ryanofsky/bitcoin,andreaskern/bitcoin,peercoin/peercoin,fanquake/bitcoin,rnicoll/dogecoin,bespike/litecoin,namecoin/namecoin-core,r8921039/bitcoin,myriadcoin/myriadcoin,droark/bitcoin,donaloconnor/bitcoin,kazcw/bitcoin,instagibbs/bitcoin,paveljanik/bitcoin,globaltoken/globaltoken,midnightmagic/bitcoin,mitchellcash/bitcoin,Kogser/bitcoin,bitcoin/bitcoin,ahmedbodi/vertcoin,sstone/bitcoin,achow101/bitcoin,randy-waterhouse/bitcoin,TheBlueMatt/bitcoin,rawodb/bitcoin,rnicoll/bitcoin,anditto/bitcoin,Sjors/bitcoin,apoelstra/bitcoin,jonasschnelli/bitcoin,pataquets/namecoin-core,pataquets/namecoin-core,mruddy/bitcoin,untrustbank/litecoin,droark/bitcoin,nikkitan/bitcoin,h4x3rotab/BTCGPU,namecoin/namecoin-core,tecnovert/particl-core,globaltoken/globaltoken,dscotese/bitcoin,ElementsProject/elements,RHavar/bitcoin,lbryio/lbrycrd,Xekyo/bitcoin,Bushstar/UFO-Project,GlobalBoost/GlobalBoost,Bushstar/UFO-Project,practicalswift/bitcoin,kallewoof/bitcoin,prusnak/bitcoin,AkioNak/bitcoin,sebrandon1/bitcoin,gjhiggins/vcoincore,jamesob/bitcoin,jlopp/statoshi,Kogser/bitcoin,rnicoll/dogecoin,GroestlCoin/GroestlCoin,jamesob/bitcoin,rawodb/bitcoin,Kogser/bitcoin,Xekyo/bitcoin,domob1812/namecore,mruddy/bitcoin,joshrabinowitz/bitcoin,domob1812/bitcoin,CryptArc/bitcoin,BTCGPU/BTCGPU,prusnak/bitcoin,ericshawlinux/bitcoin,GroestlCoin/GroestlCoin,anditto/bitcoin,JeremyRubin/bitcoin,BTCGPU/BTCGPU,afk11/bitcoin,pstratem/bitcoin,Flowdalic/bitcoin,wellenreiter01/Feathercoin,yenliangl/bitcoin,alecalve/bitcoin,lateminer/bitcoin,tecnovert/particl-core,dscotese/bitcoin,stamhe/bitcoin,Flowdalic/bitcoin,fanquake/bitcoin,jmcorgan/bitcoin,apoelstra/bitcoin,MarcoFalke/bitcoin,jlopp/statoshi,thrasher-/litecoin,r8921039/bitcoin,pataquets/namecoin-core,wellenreiter01/Feathercoin,monacoinproject/monacoin,qtumproject/qtum,instagibbs/bitcoin,mm-s/bitcoin,sstone/bitcoin,pstratem/bitcoin,GroestlCoin/GroestlCoin,mruddy/bitcoin,stamhe/bitcoin,n1bor/bitcoin,rnicoll/bitcoin,kazcw/bitcoin,domob1812/namecore,bitcoinknots/bitcoin,JeremyRubin/bitcoin,rnicoll/bitcoin,guncoin/guncoin,litecoin-project/litecoin,FeatherCoin/Feathercoin,Bushstar/UFO-Project,rnicoll/dogecoin,prusnak/bitcoin,Kogser/bitcoin,donaloconnor/bitcoin,domob1812/huntercore,sipsorcery/bitcoin,mm-s/bitcoin,BTCGPU/BTCGPU,digibyte/digibyte,joshrabinowitz/bitcoin,bitcoinknots/bitcoin,FeatherCoin/Feathercoin,myriadteam/myriadcoin,sebrandon1/bitcoin,ElementsProject/elements,sebrandon1/bitcoin,yenliangl/bitcoin,vertcoin/vertcoin,instagibbs/bitcoin,jambolo/bitcoin,GroestlCoin/bitcoin,RHavar/bitcoin,ryanofsky/bitcoin,jonasschnelli/bitcoin,Sjors/bitcoin,alecalve/bitcoin,dscotese/bitcoin,anditto/bitcoin,GlobalBoost/GlobalBoost,AkioNak/bitcoin,ryanofsky/bitcoin,sebrandon1/bitcoin,sipsorcery/bitcoin,alecalve/bitcoin,BTCGPU/BTCGPU,ajtowns/bitcoin,FeatherCoin/Feathercoin,anditto/bitcoin,ericshawlinux/bitcoin,ericshawlinux/bitcoin,litecoin-project/litecoin,Xekyo/bitcoin,digibyte/digibyte,bitcoinsSG/bitcoin,mm-s/bitcoin,ryanofsky/bitcoin,apoelstra/bitcoin,cdecker/bitcoin,anditto/bitcoin,kallewoof/bitcoin,bitcoinsSG/bitcoin,ElementsProject/elements,domob1812/huntercore,droark/bitcoin,MeshCollider/bitcoin,alecalve/bitcoin,qtumproject/qtum,stamhe/bitcoin,ajtowns/bitcoin,lbryio/lbrycrd,randy-waterhouse/bitcoin,MeshCollider/bitcoin
09c3b752154478b15a45d11f08d46a5003f174ec
giveaminute/keywords.py
giveaminute/keywords.py
""" :copyright: (c) 2011 Local Projects, all rights reserved :license: Affero GNU GPL v3, see LICENSE for more details. """ from framework.controller import log # find keywords in a string def getKeywords(db, s): """Get all matches for passed in string in keyword tables :param db: database handle :param s: string to look for :returns list of matching keywords """ words = [] if isinstance(s, str): s = [s] if not isinstance(s, list): log.error("getKeywords requested for a non-string, non-list value: %s. Cannot process!" % s) else: words = list(db.query("select keyword from keyword where keyword in $lookfor", vars=dict(lookfor=s))) return words
""" :copyright: (c) 2011 Local Projects, all rights reserved :license: Affero GNU GPL v3, see LICENSE for more details. """ # find keywords in a string def getKeywords(db, s): sql = "select keyword from keyword" data = list(db.query(sql)) words = [] for d in data: if (d.keyword in s): words.append(d.keyword) return words
Revert keyword optimization for current release
Revert keyword optimization for current release
Python
agpl-3.0
codeforeurope/Change-By-Us,watchcat/cbu-rotterdam,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,watchcat/cbu-rotterdam,localprojects/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,localprojects/Change-By-Us,localprojects/Change-By-Us
d7001ccab0879e17308bf2dc945b5fd3b726be27
statblock/dice.py
statblock/dice.py
from random import random class Die: """ Abstracts the random dice throw. Roll will produce the result. The die can be further parametrized by a multiplicator and/or a modifier, like 2 * Die(8) +4. """ def __init__(self, number, multiplicator=1, modifier=0): self.number = number self.multiplicator = multiplicator self.modifier = modifier def roll(self): return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier def __rmul__(self, other): return Die(self.number, multiplicator=other, modifier=self.modifier) def __add__(self, other): return Die(self.number, multiplicator=self.multiplicator, modifier=other) def __call__(self): return self.roll() def __eq__(self, other): return (other.number == self.number and other.multiplicator == self.multiplicator and other.modifier == self.modifier) @classmethod def parse(cls, text): return cls.__new__() def __repr__(self): return "%sd%s+%s" % (self.multiplicator, self.number, self.modifier) d4 = Die(4) d6 = Die(6) d8 = Die(8) d10 = Die(10) d12 = Die(12) d20 = Die(20) d100 = Die(100)
from random import random class Die: """ Abstracts the random dice throw. Roll will produce the result. The die can be further parametrized by a multiplicator and/or a modifier, like 2 * Die(8) +4. """ def __init__(self, number, multiplicator=1, modifier=0): self.number = number self.multiplicator = multiplicator self.modifier = modifier def roll(self): return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier def __rmul__(self, other): return Die(self.number, multiplicator=other, modifier=self.modifier) def __add__(self, other): return Die(self.number, multiplicator=self.multiplicator, modifier=other) def __call__(self): return self.roll() def __eq__(self, other): return (other.number == self.number and other.multiplicator == self.multiplicator and other.modifier == self.modifier) @classmethod def parse(cls, text): return cls.__new__() def __repr__(self): base = "%sd%s" % (self.multiplicator, self.number) if self.modifier > 0: return base + ("+%s" % self.modifier) return base d4 = Die(4) d6 = Die(6) d8 = Die(8) d10 = Die(10) d12 = Die(12) d20 = Die(20) d100 = Die(100)
Write the critical multiplier or the range when the damage gets converted into a String
Write the critical multiplier or the range when the damage gets converted into a String
Python
mit
bkittelmann/statblock
95f7c6cba7c4077053899e3ca01c8ffd3172873c
grouprise/core/views.py
grouprise/core/views.py
import json import django from rules.contrib.views import PermissionRequiredMixin class PermissionMixin(PermissionRequiredMixin): @property def raise_exception(self): return self.request.user.is_authenticated class AppConfig: def __init__(self): self._settings = {} self._defaults = {} def add_setting(self, name, value): self._settings[name] = value return self def add_default(self, name, value): self._defaults[name] = value return self def serialize(self): conf = {} conf.update(self._defaults) conf.update(self._settings) return json.dumps(conf) app_config = AppConfig() class Markdown(django.views.generic.TemplateView): template_name = 'core/markdown.html'
import json import django from django_filters.views import FilterMixin from rules.contrib.views import PermissionRequiredMixin class PermissionMixin(PermissionRequiredMixin): @property def raise_exception(self): return self.request.user.is_authenticated class TemplateFilterMixin(FilterMixin): def get_context_data(self, **kwargs): filterset_class = self.get_filterset_class() self.filterset = self.get_filterset(filterset_class) if not self.filterset.is_bound or self.filterset.is_valid() or not self.get_strict(): self.object_list = self.filterset.qs else: self.object_list = self.filterset.queryset.none() return super().get_context_data(filter=self.filterset, object_list=self.object_list) class AppConfig: def __init__(self): self._settings = {} self._defaults = {} def add_setting(self, name, value): self._settings[name] = value return self def add_default(self, name, value): self._defaults[name] = value return self def serialize(self): conf = {} conf.update(self._defaults) conf.update(self._settings) return json.dumps(conf) app_config = AppConfig() class Markdown(django.views.generic.TemplateView): template_name = 'core/markdown.html'
Add view mixin for working with filters in templates
Add view mixin for working with filters in templates
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
a789e8bf574973259c0461b99fb9a486abed6e23
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
Fix a bug that would add updated control ip address instead of replace
Fix a bug that would add updated control ip address instead of replace
Python
apache-2.0
jcshen007/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack
67ebe8da58384529c49673e2314d4fc228aebe9e
python/testData/inspections/PyPackageRequirementsInspection/ImportsNotInRequirementsTxt/test1.py
python/testData/inspections/PyPackageRequirementsInspection/ImportsNotInRequirementsTxt/test1.py
import pip import <weak_warning descr="Package 'opster' is not listed in project requirements">opster</weak_warning> from <weak_warning descr="Package 'clevercss' is not listed in project requirements">clevercss</weak_warning> import convert import <weak_warning descr="Package 'django' is not listed in project requirements">django</weak_warning>.conf import httplib import <weak_warning descr="Package 'test3' is not listed in project requirements">test3</weak_warning> print('Hello, World!')
import pip import <weak_warning descr="Package containing module 'opster' is not listed in project requirements">opster</weak_warning> from <weak_warning descr="Package containing module 'clevercss' is not listed in project requirements">clevercss</weak_warning> import convert import <weak_warning descr="Package containing module 'django' is not listed in project requirements">django</weak_warning>.conf import httplib import <weak_warning descr="Package containing module 'test3' is not listed in project requirements">test3</weak_warning> print('Hello, World!')
Fix test data for PyPackageRequirementsInspectionTest.testImportsNotInRequirementsTxt.
Fix test data for PyPackageRequirementsInspectionTest.testImportsNotInRequirementsTxt.
Python
apache-2.0
apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community
ed91a6832d459dffa18d1b2d7b827b6aa6da2627
src/sentry/api/endpoints/team_project_index.py
src/sentry/api/endpoints/team_project_index.py
from __future__ import absolute_import from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.bases.team import TeamEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.constants import MEMBER_ADMIN from sentry.models import Project from sentry.permissions import can_create_projects class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('name', 'slug') class TeamProjectIndexEndpoint(TeamEndpoint): def get(self, request, team): assert_perm(team, request.user, request.auth) results = list(Project.objects.get_for_user(team=team, user=request.user)) return Response(serialize(results, request.user)) def post(self, request, team): assert_perm(team, request.user, request.auth, access=MEMBER_ADMIN) if not can_create_projects(user=request.user, team=team): return Response(status=403) serializer = ProjectSerializer(data=request.DATA) if serializer.is_valid(): project = serializer.object project.team = team project.organization = team.organization project.save() return Response(serialize(project, request.user), status=201) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
from __future__ import absolute_import from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.team import TeamEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.constants import MEMBER_ADMIN from sentry.models import Project from sentry.permissions import can_create_projects class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('name', 'slug') class TeamProjectIndexEndpoint(TeamEndpoint): doc_section = DocSection.TEAMS def get(self, request, team): """ List a team's projects Return a list of projects bound to a team. {method} {path} """ assert_perm(team, request.user, request.auth) results = list(Project.objects.get_for_user(team=team, user=request.user)) return Response(serialize(results, request.user)) def post(self, request, team): """ Create a new project Create a new project bound to a team. {method} {path} {{ "name": "My project" }} """ assert_perm(team, request.user, request.auth, access=MEMBER_ADMIN) if not can_create_projects(user=request.user, team=team): return Response(status=403) serializer = ProjectSerializer(data=request.DATA) if serializer.is_valid(): project = serializer.object project.team = team project.organization = team.organization project.save() return Response(serialize(project, request.user), status=201) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Add team project list to docs
Add team project list to docs
Python
bsd-3-clause
BuildingLink/sentry,JamesMura/sentry,mvaled/sentry,beeftornado/sentry,JamesMura/sentry,ngonzalvez/sentry,Kryz/sentry,fuziontech/sentry,nicholasserra/sentry,TedaLIEz/sentry,JackDanger/sentry,songyi199111/sentry,BayanGroup/sentry,songyi199111/sentry,1tush/sentry,kevinlondon/sentry,gg7/sentry,jokey2k/sentry,Natim/sentry,vperron/sentry,daevaorn/sentry,wong2/sentry,JTCunning/sentry,Natim/sentry,nicholasserra/sentry,daevaorn/sentry,fuziontech/sentry,gg7/sentry,boneyao/sentry,kevinastone/sentry,gencer/sentry,mvaled/sentry,pauloschilling/sentry,kevinastone/sentry,BuildingLink/sentry,TedaLIEz/sentry,fotinakis/sentry,gg7/sentry,drcapulet/sentry,drcapulet/sentry,JTCunning/sentry,BayanGroup/sentry,argonemyth/sentry,fuziontech/sentry,looker/sentry,gencer/sentry,jokey2k/sentry,wujuguang/sentry,boneyao/sentry,JamesMura/sentry,vperron/sentry,felixbuenemann/sentry,ewdurbin/sentry,daevaorn/sentry,ifduyue/sentry,1tush/sentry,zenefits/sentry,korealerts1/sentry,zenefits/sentry,alexm92/sentry,JackDanger/sentry,mitsuhiko/sentry,wujuguang/sentry,llonchj/sentry,ngonzalvez/sentry,JamesMura/sentry,mvaled/sentry,fotinakis/sentry,hongliang5623/sentry,pauloschilling/sentry,looker/sentry,Kryz/sentry,gencer/sentry,jean/sentry,boneyao/sentry,Kryz/sentry,looker/sentry,wong2/sentry,BuildingLink/sentry,korealerts1/sentry,ewdurbin/sentry,JTCunning/sentry,ifduyue/sentry,ewdurbin/sentry,beeftornado/sentry,JackDanger/sentry,gencer/sentry,hongliang5623/sentry,jokey2k/sentry,ifduyue/sentry,1tush/sentry,BuildingLink/sentry,imankulov/sentry,fotinakis/sentry,daevaorn/sentry,felixbuenemann/sentry,songyi199111/sentry,imankulov/sentry,beeftornado/sentry,jean/sentry,vperron/sentry,Natim/sentry,zenefits/sentry,felixbuenemann/sentry,imankulov/sentry,looker/sentry,alexm92/sentry,mvaled/sentry,gencer/sentry,ifduyue/sentry,kevinlondon/sentry,kevinlondon/sentry,pauloschilling/sentry,JamesMura/sentry,BayanGroup/sentry,ngonzalvez/sentry,jean/sentry,zenefits/sentry,drcapulet/sentry,korealerts1/sentry,mvaled/sentry,wong2/sentry,ifduyue/sentry,fotinakis/sentry,argonemyth/sentry,alexm92/sentry,jean/sentry,hongliang5623/sentry,argonemyth/sentry,llonchj/sentry,looker/sentry,llonchj/sentry,jean/sentry,kevinastone/sentry,nicholasserra/sentry,BuildingLink/sentry,zenefits/sentry,mvaled/sentry,mitsuhiko/sentry,TedaLIEz/sentry,wujuguang/sentry
a8a0dd55a5289825aae34aa45765ea328811523e
spotpy/unittests/test_fast.py
spotpy/unittests/test_fast.py
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(203,len(results)) if __name__ == '__main__': unittest.main()
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup # Test only untder Python 3 as Python >2.7.10 results in a strange fft error if sys.version_info >= (3, 5): class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(203,len(results)) if __name__ == '__main__': unittest.main()
Exclude Fast test for Python 2
Exclude Fast test for Python 2
Python
mit
bees4ever/spotpy,bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy
5ab0c1c1323b2b12a19ef58de4c03236db84644d
cellcounter/accounts/urls.py
cellcounter/accounts/urls.py
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/done/$', views.password_reset_done, name='password-reset-done'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', 'django.contrib.auth.views.password_reset_confirm', { 'template_name': 'accounts/reset_confirm.html', 'post_reset_redirect': 'password-reset-done', }, name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
from django.conf.urls import patterns, url from cellcounter.accounts import views urlpatterns = patterns('', url('^new/$', views.RegistrationView.as_view(), name='register'), url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'), url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'), url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'), url('^password/reset/$', views.PasswordResetView.as_view(), name='password-reset'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', views.PasswordResetConfirmView.as_view(), name='password-reset-confirm'), url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'), )
Remove old views and replace with new PasswordResetConfirmView
Remove old views and replace with new PasswordResetConfirmView
Python
mit
haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter
f0acf5023db56e8011a6872f230514a69ec9f311
extractor.py
extractor.py
import extractor.ui.mainapplication as ui import Tkinter as tk def main(): root = tk.Tk() root.title('SNES Wolfenstein 3D Extractor') root.minsize(400, 100) ui.MainApplication(root).pack(side="top", fill="both", expand=True) root.mainloop() main()
import extractor.ui.mainapplication as ui import Tkinter as tk def main(): ## root = tk.Tk() ## root.title('SNES Wolfenstein 3D Extractor') ## root.minsize(400, 100) ## ui.MainApplication(root).pack(side="top", fill="both", expand=True) ## root.mainloop() ui.MainApplication().mainloop() main()
Use new MainApplication Tk class.
Use new MainApplication Tk class.
Python
mit
adambiser/snes-wolf3d-extractor
ce9da309294f2520f297980d80773160f050e8bf
yubico/yubico_exceptions.py
yubico/yubico_exceptions.py
class YubicoError(Exception): """ Base class for Yubico related exceptions. """ pass class StatusCodeError(YubicoError): def __init__(self, status_code): self.status_code = status_code def __str__(self): return ('Yubico server returned the following status code: %s' % (self.status_code)) class InvalidClientIdError(YubicoError): def __init__(self, client_id): self.client_id = client_id def __str__(self): return 'The client with ID %s does not exist' % (self.client_id) class SignatureVerificationError(YubicoError): def __init__(self, generated_signature, response_signature): self.generated_signature = generated_signature self.response_signature = response_signature def __str__(self): return repr('Server response message signature verification failed' + '(expected %s, got %s)' % (self.generated_signature, self.response_signature))
__all___ = [ 'YubicoError', 'StatusCodeError', 'InvalidClientIdError', 'SignatureVerificationError' ] class YubicoError(Exception): """ Base class for Yubico related exceptions. """ pass class StatusCodeError(YubicoError): def __init__(self, status_code): self.status_code = status_code def __str__(self): return ('Yubico server returned the following status code: %s' % (self.status_code)) class InvalidClientIdError(YubicoError): def __init__(self, client_id): self.client_id = client_id def __str__(self): return 'The client with ID %s does not exist' % (self.client_id) class SignatureVerificationError(YubicoError): def __init__(self, generated_signature, response_signature): self.generated_signature = generated_signature self.response_signature = response_signature def __str__(self): return repr('Server response message signature verification failed' + '(expected %s, got %s)' % (self.generated_signature, self.response_signature))
Add __all__ in exceptions module.
Add __all__ in exceptions module.
Python
bsd-3-clause
Kami/python-yubico-client
682f45ffd222dc582ee770a0326c962540657c68
django_twilio/models.py
django_twilio/models.py
# -*- coding: utf-8 -*- from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Caller(models.Model): """A caller is defined uniquely by their phone number. :param bool blacklisted: Designates whether the caller can use our services. :param char phone_number: Unique phone number in `E.164 <http://en.wikipedia.org/wiki/E.164>`_ format. """ blacklisted = models.BooleanField() phone_number = PhoneNumberField(unique=True) def __unicode__(self): return str(self.phone_number) + ' (blacklisted)' if self.blacklisted else ''
# -*- coding: utf-8 -*- from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Caller(models.Model): """A caller is defined uniquely by their phone number. :param bool blacklisted: Designates whether the caller can use our services. :param char phone_number: Unique phone number in `E.164 <http://en.wikipedia.org/wiki/E.164>`_ format. """ blacklisted = models.BooleanField() phone_number = PhoneNumberField(unique=True) def __unicode__(self): name = str(self.phone_number) if self.blacklisted: name += ' (blacklisted)' return name
Fix an error in __unicode__
Fix an error in __unicode__ __unicode__ name displaying incorrectly - FIXED
Python
unlicense
rdegges/django-twilio,aditweb/django-twilio
69a8528801ae5c3fdde57b9766917fcf8690c54e
telephus/translate.py
telephus/translate.py
class APIMismatch(Exception): pass def translateArgs(request, api_version): args = request.args if request.method == 'system_add_keyspace' \ or request.method == 'system_update_keyspace': args = adapt_ksdef_rf(args[0]) + args[1:] return args def postProcess(results, method): if method == 'describe_keyspace': results = adapt_ksdef_rf(results) elif method == 'describe_keyspaces': results = map(adapt_ksdef_rf, results) return results def adapt_ksdef_rf(ksdef): """ try to always have both KsDef.strategy_options['replication_factor'] and KsDef.replication_factor available, and let the thrift api code and client code work out what they want to use. """ if getattr(ksdef, 'strategy_options', None) is None: ksdef.strategy_options = {} if 'replication_factor' in ksdef.strategy_options: if ksdef.replication_factor is None: ksdef.replication_factor = int(ksdef.strategy_options['replication_factor']) elif ksdef.replication_factor is not None: ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor) return ksdef
class APIMismatch(Exception): pass def translateArgs(request, api_version): args = request.args if request.method == 'system_add_keyspace' \ or request.method == 'system_update_keyspace': adapted_ksdef = adapt_ksdef_rf(args[0]) args = (adapted_ksdef,) + args[1:] return args def postProcess(results, method): if method == 'describe_keyspace': results = adapt_ksdef_rf(results) elif method == 'describe_keyspaces': results = map(adapt_ksdef_rf, results) return results def adapt_ksdef_rf(ksdef): """ try to always have both KsDef.strategy_options['replication_factor'] and KsDef.replication_factor available, and let the thrift api code and client code work out what they want to use. """ if getattr(ksdef, 'strategy_options', None) is None: ksdef.strategy_options = {} if 'replication_factor' in ksdef.strategy_options: if ksdef.replication_factor is None: ksdef.replication_factor = int(ksdef.strategy_options['replication_factor']) elif ksdef.replication_factor is not None: ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor) return ksdef
Fix args manipulation in when translating ksdefs
Fix args manipulation in when translating ksdefs
Python
mit
Metaswitch/Telephus,driftx/Telephus,ClearwaterCore/Telephus,driftx/Telephus,Metaswitch/Telephus,ClearwaterCore/Telephus
172768dacc224f3c14e85f8e732209efe9ce075a
app/soc/models/project_survey.py
app/soc/models/project_survey.py
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) # TODO: prefix has to be set to gsoc_program once data has been transferred self.prefix = 'program' self.taking_access = 'student'
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) self.prefix = 'gsoc_program' self.taking_access = 'student'
Set the default prefix for ProjectSurveys to gsoc_program.
Set the default prefix for ProjectSurveys to gsoc_program.
Python
apache-2.0
SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange
48e15b8f99bb0714b7ec465a0131e452c67004e5
Chapter4_TheGreatestTheoremNeverTold/top_pic_comments.py
Chapter4_TheGreatestTheoremNeverTold/top_pic_comments.py
import sys import numpy as np from IPython.core.display import Image import praw reddit = praw.Reddit("BayesianMethodsForHackers") subreddit = reddit.get_subreddit( "pics" ) top_submissions = subreddit.get_top() n_pic = int( sys.argv[1] ) if sys.argv[1] else 1 i = 0 while i < n_pic: top_submission = top_submissions.next() while "i.imgur.com" not in top_submission.url: #make sure it is linking to an image, not a webpage. top_submission = top_submissions.next() i+=1 print "Title of submission: \n", top_submission.title top_post_url = top_submission.url #top_submission.replace_more_comments(limit=5, threshold=0) print top_post_url upvotes = [] downvotes = [] contents = [] _all_comments = top_submission.comments all_comments=[] for comment in _all_comments: try: upvotes.append( comment.ups ) downvotes.append( comment.downs ) contents.append( comment.body ) except Exception as e: continue votes = np.array( [ upvotes, downvotes] ).T
import sys import numpy as np from IPython.core.display import Image import praw reddit = praw.Reddit("BayesianMethodsForHackers") subreddit = reddit.get_subreddit( "pics" ) top_submissions = subreddit.get_top() n_pic = int( sys.argv[1] ) if len(sys.argv) > 1 else 1 i = 0 while i < n_pic: top_submission = top_submissions.next() while "i.imgur.com" not in top_submission.url: #make sure it is linking to an image, not a webpage. top_submission = top_submissions.next() i+=1 print "Title of submission: \n", top_submission.title top_post_url = top_submission.url #top_submission.replace_more_comments(limit=5, threshold=0) print top_post_url upvotes = [] downvotes = [] contents = [] _all_comments = top_submission.comments all_comments=[] for comment in _all_comments: try: upvotes.append( comment.ups ) downvotes.append( comment.downs ) contents.append( comment.body ) except Exception as e: continue votes = np.array( [ upvotes, downvotes] ).T
Fix index to list when there is no 2nd element
Fix index to list when there is no 2nd element
Python
mit
chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
afd27c62049e87eaefbfb5f38c6b61b461656384
formulae/token.py
formulae/token.py
class Token: """Representation of a single Token""" def __init__(self, _type, lexeme, literal=None): self.type = _type self.lexeme = lexeme self.literal = literal def __repr__(self): string_list = [ "'type': " + str(self.type), "'lexeme': " + str(self.lexeme), "'literal': " + str(self.literal), ] return "{" + ", ".join(string_list) + "}" def __str__(self): string_list = [ "type= " + str(self.type), "lexeme= " + str(self.lexeme), "literal= " + str(self.literal), ] return "Token(" + ", ".join(string_list) + ")"
class Token: """Representation of a single Token""" def __init__(self, _type, lexeme, literal=None): self.type = _type self.lexeme = lexeme self.literal = literal def __hash__(self): return hash((self.type, self.lexeme, self.literal)) def __eq__(self, other): if not isinstance(other, type(self)): return False return ( self.type == other.type and self.lexeme == other.lexeme and self.literal == other.literal ) def __repr__(self): string_list = [ "'type': " + str(self.type), "'lexeme': " + str(self.lexeme), "'literal': " + str(self.literal), ] return "{" + ", ".join(string_list) + "}" def __str__(self): string_list = [ "type= " + str(self.type), "lexeme= " + str(self.lexeme), "literal= " + str(self.literal), ] return "Token(" + ", ".join(string_list) + ")"
Add hash and eq methods to Token
Add hash and eq methods to Token
Python
mit
bambinos/formulae
d012763c57450555d45385ed9b254f500388618e
automata/render.py
automata/render.py
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.animation as animation class AnimatedGif: """ Setup various rendering things """ def __init__(self, dpi=100, colors="Purples"): self.frames = [] self.fig = plt.figure(dpi=dpi) plt.axis("off") self.colors = colors self.dimensions = None def append(self, universe): if not self.dimensions: if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]): raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values") self.dimensions = universe.shape if self.dimensions != universe.shape: raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape)) self.frames.append((plt.imshow(universe, cmap=self.colors),)) def render(self, filename, interval=300): im_ani = animation.ArtistAnimation( self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True ) im_ani.save(filename, writer="imagemagick")
import matplotlib matplotlib.use('Agg') import matplotlib.colors import matplotlib.pyplot as plt import matplotlib.animation as animation class AnimatedGif: """ Setup various rendering things """ def __init__(self, dpi=100, colors="Purples"): self.frames = [] self.fig = plt.figure(dpi=dpi) plt.axis("off") self.colors = colors self.normalize = matplotlib.colors.Normalize() self.dimensions = None def append(self, universe): if not self.dimensions: if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]): raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values") self.dimensions = universe.shape if self.dimensions != universe.shape: raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape)) self.frames.append((plt.imshow(universe, norm=self.normalize, cmap=self.colors),)) def render(self, filename, interval=300): im_ani = animation.ArtistAnimation( self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True ) im_ani.save(filename, writer="imagemagick")
Use the same normlization for whole gif
Use the same normlization for whole gif
Python
apache-2.0
stevearm/automata
ce7c31f3dd97716051b72951c7c745dd2c63efcd
plugins/audit_logs/server/__init__.py
plugins/audit_logs/server/__init__.py
import cherrypy import logging from girder import auditLogger from girder.models.model_base import Model from girder.api.rest import getCurrentUser class Record(Model): def initialize(self): self.name = 'audit_log_record' def validate(self, doc): return doc class AuditLogHandler(logging.Handler): def handle(self, record): user = getCurrentUser() Record().save({ 'type': record.msg, 'details': record.details, 'ip': cherrypy.request.remote.ip, 'userId': user and user['_id'] }) def load(info): auditLogger.addHandler(AuditLogHandler())
import cherrypy import datetime import logging from girder import auditLogger from girder.models.model_base import Model from girder.api.rest import getCurrentUser class Record(Model): def initialize(self): self.name = 'audit_log_record' def validate(self, doc): return doc class AuditLogHandler(logging.Handler): def handle(self, record): user = getCurrentUser() Record().save({ 'type': record.msg, 'details': record.details, 'ip': cherrypy.request.remote.ip, 'userId': user and user['_id'], 'when': datetime.datetime.utcnow() }) def load(info): auditLogger.addHandler(AuditLogHandler())
Include timestamp in audit logs
Include timestamp in audit logs
Python
apache-2.0
RafaelPalomar/girder,data-exp-lab/girder,RafaelPalomar/girder,data-exp-lab/girder,girder/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,manthey/girder,jbeezley/girder,manthey/girder,girder/girder,data-exp-lab/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,Kitware/girder,data-exp-lab/girder,kotfic/girder,girder/girder,manthey/girder,jbeezley/girder,data-exp-lab/girder,manthey/girder,girder/girder,Kitware/girder,RafaelPalomar/girder,kotfic/girder,kotfic/girder,jbeezley/girder,jbeezley/girder
b2069b2b4a07d82cc6831dde0e396d7dae79d23e
autopidact/view.py
autopidact/view.py
from gi.repository import Gtk, GdkPixbuf, GLib import cv2 class View(Gtk.Window): def __init__(self, title, camera, interval=200): Gtk.Window.__init__(self) self.set_title(title) self.cam = camera self.img = Gtk.Image() self.add(self.img) GLib.timeout_add(interval, self.update) def update(self): if self.cam.isReady(): frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB) self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None)) else: print('not ready')
from gi.repository import Gtk, GdkPixbuf, GLib import cv2 class View(Gtk.Window): def __init__(self, title, camera, interval=200): Gtk.Window.__init__(self) self.set_title(title) self.set_size_request(640, 480) self.set_resizable(False) self.cam = camera self.img = Gtk.Image() self.add(self.img) GLib.timeout_add(interval, self.update) def update(self): if self.cam.isReady(): frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB) self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None)) else: print('not ready')
Set an initial size and disallow resizing
Set an initial size and disallow resizing
Python
mit
fkmclane/AutoPidact
fb01aa54032b7ab73dcd5a3e73d4ece5f36517e2
locations/tasks.py
locations/tasks.py
from future.standard_library import install_aliases install_aliases() # noqa from urllib.parse import urlparse from celery.task import Task from django.conf import settings from seed_services_client import IdentityStoreApiClient from .models import Parish class SyncLocations(Task): """ Has a look at all the identity store identities, and ensures that all of the locations assigned to identities appear in the list of locations. """ def get_identities(self, client): """ Returns an iterator over all the identities in the identity store specified by 'client'. """ identities = client.get_identities() while True: for identity in identities.get('results', []): yield identity if identities.get('next') is not None: qs = urlparse(identities['next']).query identities = client.get_identities(params=qs) else: break def run(self, **kwargs): l = self.get_logger(**kwargs) l.info('Starting location import') imported_count = 0 client = IdentityStoreApiClient( settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL) for identity in self.get_identities(client): parish = identity.get('details', {}).get('parish') if parish is not None: _, created = Parish.objects.get_or_create(name=parish.title()) if created: imported_count += 1 l.info('Imported {} locations'.format(imported_count)) return imported_count sync_locations = SyncLocations()
from future.standard_library import install_aliases install_aliases() # noqa from urllib.parse import urlparse from celery.task import Task from django.conf import settings from seed_services_client import IdentityStoreApiClient from .models import Parish class SyncLocations(Task): """ Has a look at all the identity store identities, and ensures that all of the locations assigned to identities appear in the list of locations. """ def get_identities(self, client): """ Returns an iterator over all the identities in the identity store specified by 'client'. """ identities = client.get_identities() while True: for identity in identities.get('results', []): yield identity # If there is a next page, extract the querystring and get it if identities.get('next') is not None: qs = urlparse(identities['next']).query identities = client.get_identities(params=qs) else: break def run(self, **kwargs): l = self.get_logger(**kwargs) l.info('Starting location import') imported_count = 0 client = IdentityStoreApiClient( settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL) for identity in self.get_identities(client): parish = identity.get('details', {}).get('parish') if parish is not None: _, created = Parish.objects.get_or_create(name=parish.title()) if created: imported_count += 1 l.info('Imported {} locations'.format(imported_count)) return imported_count sync_locations = SyncLocations()
Add comment to explain pagination handling
Add comment to explain pagination handling
Python
bsd-3-clause
praekelt/familyconnect-registration,praekelt/familyconnect-registration
e9fc291faca8af35398b958d046e951aa8471cbf
apps/core/tests/test_factories.py
apps/core/tests/test_factories.py
from .. import factories from . import CoreFixturesTestCase class AnalysisFactoryTestCase(CoreFixturesTestCase): def test_new_factory_with_Experiments(self): experiments = factories.ExperimentFactory.create_batch(3) # build analysis = factories.AnalysisFactory.build(experiments=experiments) self.assertEqual(analysis.experiments.count(), 0) # create analysis = factories.AnalysisFactory(experiments=experiments) experiments_ids = list( analysis.experiments.values_list('id', flat=True) ) expected_experiments_ids = [e.id for e in experiments] self.assertEqual(experiments_ids, expected_experiments_ids)
from .. import factories, models from . import CoreFixturesTestCase class AnalysisFactoryTestCase(CoreFixturesTestCase): def test_new_factory_with_Experiments(self): experiments = factories.ExperimentFactory.create_batch(3) # build analysis = factories.AnalysisFactory.build(experiments=experiments) self.assertEqual(analysis.experiments.count(), 0) # create analysis = factories.AnalysisFactory(experiments=experiments) experiments_ids = analysis.experiments.values_list( 'id', flat=True ) expected_experiments_ids = models.Experiment.objects.values_list( 'id', flat=True ) self.assertEqual( list(experiments_ids), list(expected_experiments_ids) )
Fix broken test since models new default ordering
Fix broken test since models new default ordering
Python
bsd-3-clause
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
f4e36132448a4a55bff5660b3f5a669e0095ecc5
awx/main/models/activity_stream.py
awx/main/models/activity_stream.py
# Copyright (c) 2013 AnsibleWorks, Inc. # All Rights Reserved. from django.db import models class ActivityStream(models.Model): ''' Model used to describe activity stream (audit) events ''' OPERATION_CHOICES = [ ('create', _('Entity Created')), ('update', _("Entity Updated")), ('delete', _("Entity Deleted")), ('associate', _("Entity Associated with another Entity")), ('disaassociate', _("Entity was Disassociated with another Entity")) ] user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL) operation = models.CharField(max_length=9, choices=OPERATION_CHOICES) timestamp = models.DateTimeField(auto_now_add=True) changes = models.TextField(blank=True) object1_id = models.PositiveIntegerField(db_index=True) object1_type = models.TextField() object2_id = models.PositiveIntegerField(db_index=True) object2_type = models.TextField() object_relationship_type = models.TextField()
# Copyright (c) 2013 AnsibleWorks, Inc. # All Rights Reserved. from django.db import models from django.utils.translation import ugettext_lazy as _ class ActivityStream(models.Model): ''' Model used to describe activity stream (audit) events ''' class Meta: app_label = 'main' OPERATION_CHOICES = [ ('create', _('Entity Created')), ('update', _("Entity Updated")), ('delete', _("Entity Deleted")), ('associate', _("Entity Associated with another Entity")), ('disaassociate', _("Entity was Disassociated with another Entity")) ] user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL, related_name='activity_stream') operation = models.CharField(max_length=9, choices=OPERATION_CHOICES) timestamp = models.DateTimeField(auto_now_add=True) changes = models.TextField(blank=True) object1_id = models.PositiveIntegerField(db_index=True) object1_type = models.TextField() object2_id = models.PositiveIntegerField(db_index=True, null=True) object2_type = models.TextField(null=True, blank=True) object_relationship_type = models.TextField(blank=True)
Fix up some issues with supporting schema migration
Fix up some issues with supporting schema migration
Python
apache-2.0
wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx
941ab0315d71fbea552b0ab12d75e4d8968adfce
cube2sphere/blender_init.py
cube2sphere/blender_init.py
__author__ = 'Xyene' import bpy import sys import math bpy.context.scene.cycles.resolution_x = int(sys.argv[-5]) bpy.context.scene.cycles.resolution_y = int(sys.argv[-4]) for i, name in enumerate(['bottom', 'top', 'left', 'right', 'back', 'front']): bpy.data.images[name].filepath = "%s" % sys.argv[-6 - i] camera = bpy.data.objects["Camera"] camera.rotation_mode = 'XYZ' camera.rotation_euler = (math.pi / 2 + float(sys.argv[-3]), float(sys.argv[-2]), float(sys.argv[-1])) bpy.ops.render.render(animation=True)
__author__ = 'Xyene' import bpy import sys import math for scene in bpy.data.scenes: scene.render.resolution_x = int(sys.argv[-5]) scene.render.resolution_y = int(sys.argv[-4]) scene.render.resolution_percentage = 100 scene.render.use_border = False for i, name in enumerate(['bottom', 'top', 'left', 'right', 'back', 'front']): bpy.data.images[name].filepath = "%s" % sys.argv[-6 - i] camera = bpy.data.objects["Camera"] camera.rotation_mode = 'XYZ' camera.rotation_euler = (math.pi / 2 + float(sys.argv[-3]), float(sys.argv[-2]), float(sys.argv[-1])) bpy.ops.render.render(animation=True)
Change the way we pass resolution to blender
Change the way we pass resolution to blender
Python
agpl-3.0
Xyene/cube2sphere
8ddbd0b39687f46637041848ab7190bcefd57b68
pyramid_mongodb/__init__.py
pyramid_mongodb/__init__.py
""" simplified mongodb integration 1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db ) import python_mongodb def main(global_config, **settings): ## ... # Initialize mongodb , which is a subscriber python_mongodb.initialize_mongo_db( config , settings ) ## ... return config.make_wsgi_app() 2. in each of your envinronment.ini files, have: mongodb.use = true mongodb.uri = mongodb://localhost mongodb.name = myapp if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to ) """ import pymongo from gridfs import GridFS def initialize_mongo_db( config, settings ): if ( 'mongodb.use' in settings ) and ( settings['mongodb.use'] == 'true' ): conn = pymongo.Connection( settings['mongodb.uri'] ) config.registry.settings['!mongodb.conn'] = conn config.add_subscriber(add_mongo_db, 'pyramid.events.NewRequest') def add_mongo_db(event): settings = event.request.registry.settings db = settings['!mongodb.conn'][settings['mongodb.name']] event.request.mongodb = db event.request.gridfs = GridFS(db)
""" simplified mongodb integration 1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db ) import python_mongodb def main(global_config, **settings): ## ... # Initialize mongodb , which is a subscriber python_mongodb.initialize_mongo_db( config , settings ) ## ... return config.make_wsgi_app() 2. in each of your envinronment.ini files, have: mongodb.use = true mongodb.uri = mongodb://localhost mongodb.name = myapp if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to ) """ import pymongo from gridfs import GridFS def initialize_mongo_db(config, settings): if ('mongodb.use' in settings) and (settings['mongodb.use'] == 'true'): conn = pymongo.Connection(settings['mongodb.uri']) config.registry.settings['!mongodb.conn'] = conn config.set_request_property(add_mongo_db, 'mongodb', reify=True) def add_mongo_db(request): settings = request.registry.settings db = settings['!mongodb.conn'][settings['mongodb.name']] request.mongodb = db request.gridfs = GridFS(db)
Use set_request_property instead of subscriber to improve performance
Use set_request_property instead of subscriber to improve performance
Python
mit
niallo/pyramid_mongodb
92c024c2112573e4c4b2d1288b1ec3c7a40bc670
test/test_uploader.py
test/test_uploader.py
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) # fetch the contents back out, be sure we truly uploaded the dummyfile retrieved_bucket = conn.Object( mock_bucket, conf.s3_package_name() ).get()['Body'] found_contents = str(retrieved_bucket.read()).rstrip() assert found_contents == 'dummy data'
Add additional assertion that the file we uploaded is correct
Add additional assertion that the file we uploaded is correct We should pull back down the S3 bucket file and be sure it's the same, proving we used the boto3 API correctly. We should probably, at some point, also upload a _real_ zip file and not just a plaintext file.
Python
apache-2.0
rackerlabs/lambda-uploader,dsouzajude/lambda-uploader
cc4b68c7eccf05ca32802022b2abfd31b51bce32
chef/exceptions.py
chef/exceptions.py
# Exception hierarchy for chef # Copyright (c) 2010 Noah Kantrowitz <noah@coderanger.net> class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): ChefError.__init__(self, message) self.code = code
# Exception hierarchy for chef # Copyright (c) 2010 Noah Kantrowitz <noah@coderanger.net> class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): super(ChefError, self).__init__(message) self.code = code
Use super() for great justice.
Use super() for great justice.
Python
apache-2.0
Scalr/pychef,Scalr/pychef,cread/pychef,dipakvwarade/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,coderanger/pychef,jarosser06/pychef,jarosser06/pychef
f11d7232486a92bf5e9dba28432ee2ed97e02da4
print_web_django/api/views.py
print_web_django/api/views.py
from rest_framework import viewsets from . import serializers, models class PrintJobViewSet(viewsets.ModelViewSet): serializer_class = serializers.PrintJobSerializer def get_queryset(self): return self.request.user.printjobs.all() def perform_create(self, serializer): # need to also pass the requests user on a create serializer.save(user=self.request.user)
from rest_framework import viewsets from . import serializers, models class PrintJobViewSet(viewsets.ModelViewSet): serializer_class = serializers.PrintJobSerializer def get_queryset(self): return self.request.user.printjobs.all().order_by('-created') def perform_create(self, serializer): # need to also pass the requests user on a create serializer.save(user=self.request.user)
Sort by descending date created (new first)
Sort by descending date created (new first)
Python
mit
aabmass/print-web,aabmass/print-web,aabmass/print-web
97d6f5e7b346944ac6757fd4570bfbc7dcf52425
survey/admin.py
survey/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from survey.models import Answer, Category, Question, Response, Survey from .actions import make_published class QuestionInline(admin.TabularInline): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(admin.TabularInline): model = Category extra = 0 class SurveyAdmin(admin.ModelAdmin): list_display = ("name", "is_published", "need_logged_user", "template") list_filter = ("is_published", "need_logged_user") inlines = [CategoryInline, QuestionInline] actions = [make_published] class AnswerBaseInline(admin.StackedInline): fields = ("question", "body") readonly_fields = ("question",) extra = 0 model = Answer class ResponseAdmin(admin.ModelAdmin): list_display = ("interview_uuid", "survey", "created", "user") list_filter = ("survey", "created") date_hierarchy = "created" inlines = [AnswerBaseInline] # specifies the order as well as which fields to act on readonly_fields = ("survey", "created", "updated", "interview_uuid", "user") # admin.site.register(Question, QuestionInline) # admin.site.register(Category, CategoryInline) admin.site.register(Survey, SurveyAdmin) admin.site.register(Response, ResponseAdmin)
# -*- coding: utf-8 -*- from django.contrib import admin from survey.actions import make_published from survey.models import Answer, Category, Question, Response, Survey class QuestionInline(admin.TabularInline): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(admin.TabularInline): model = Category extra = 0 class SurveyAdmin(admin.ModelAdmin): list_display = ("name", "is_published", "need_logged_user", "template") list_filter = ("is_published", "need_logged_user") inlines = [CategoryInline, QuestionInline] actions = [make_published] class AnswerBaseInline(admin.StackedInline): fields = ("question", "body") readonly_fields = ("question",) extra = 0 model = Answer class ResponseAdmin(admin.ModelAdmin): list_display = ("interview_uuid", "survey", "created", "user") list_filter = ("survey", "created") date_hierarchy = "created" inlines = [AnswerBaseInline] # specifies the order as well as which fields to act on readonly_fields = ("survey", "created", "updated", "interview_uuid", "user") # admin.site.register(Question, QuestionInline) # admin.site.register(Category, CategoryInline) admin.site.register(Survey, SurveyAdmin) admin.site.register(Response, ResponseAdmin)
Fix Attempted relative import beyond top-level package
Fix Attempted relative import beyond top-level package
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
a03eb91088943a4b3ed0ae5fc87b104562a4a645
location_field/urls.py
location_field/urls.py
try: from django.conf.urls import patterns # Django>=1.6 except ImportError: from django.conf.urls.defaults import patterns # Django<1.6 import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
from django.conf.urls import patterns import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
Drop support for Django 1.6
Drop support for Django 1.6
Python
mit
Mixser/django-location-field,recklessromeo/django-location-field,Mixser/django-location-field,voodmania/django-location-field,recklessromeo/django-location-field,undernewmanagement/django-location-field,voodmania/django-location-field,caioariede/django-location-field,caioariede/django-location-field,undernewmanagement/django-location-field,Mixser/django-location-field,undernewmanagement/django-location-field,caioariede/django-location-field,recklessromeo/django-location-field,voodmania/django-location-field
f292cfa783bcc30c2625b340ad763db2723ce056
test/test_db.py
test/test_db.py
from piper.db import DbCLI import mock class DbCLIBase(object): def setup_method(self, method): self.cli = DbCLI(mock.Mock()) self.ns = mock.Mock() self.config = mock.Mock() class TestDbCLIRun(DbCLIBase): def test_plain_run(self): self.cli.cls.init = mock.Mock() ret = self.cli.run(self.ns, self.config) assert ret == 0 self.cli.cls.init.assert_called_once_with(self.ns, self.config)
from piper.db import DbCLI from piper.db import DatabaseBase import mock import pytest class DbCLIBase(object): def setup_method(self, method): self.cli = DbCLI(mock.Mock()) self.ns = mock.Mock() self.config = mock.Mock() class TestDbCLIRun(DbCLIBase): def test_plain_run(self): self.cli.cls.init = mock.Mock() ret = self.cli.run(self.ns, self.config) assert ret == 0 self.cli.cls.init.assert_called_once_with(self.ns, self.config) class TestDatabaseBaseInit(object): def setup_method(self, method): self.db = DatabaseBase() self.ns = mock.Mock() self.config = mock.Mock() def test_raises_not_implemented_error(self): with pytest.raises(NotImplementedError): self.db.init(self.ns, self.config)
Add tests for DatabaseBase abstraction
Add tests for DatabaseBase abstraction
Python
mit
thiderman/piper
63c2cc935d3c97ecb8b297ae387bfdf719cf1350
apps/admin/forms.py
apps/admin/forms.py
from django.contrib.auth.models import User from django import forms from apps.categories.models import * from apps.books.models import * class LoginForm(forms.ModelForm): """docstring for LoginForm""" class Meta: model = User fields = ['username', 'password'] class CategoryForm(forms.ModelForm): """docstring for CategoryForm""" class Meta: model = Category fields = '__all__' class BookForm(forms.ModelForm): """docstring for BookForm""" class Meta: model = Book fields = ('title', 'description', 'slug', 'categories', 'pages', 'author', 'publish_date', 'cover', 'price') widgets = { 'categories': forms.widgets.SelectMultiple( attrs={'class': 'form-control select2', 'style': 'width: 100%;', 'multiple': "multiple"}), }
from django.contrib.auth.models import User from django import forms from apps.categories.models import * from apps.books.models import * class CategoryForm(forms.ModelForm): """docstring for CategoryForm""" class Meta: model = Category fields = '__all__' class BookForm(forms.ModelForm): """docstring for BookForm""" class Meta: model = Book fields = ('title', 'description', 'slug', 'categories', 'pages', 'author', 'publish_date', 'cover', 'price') widgets = { 'categories': forms.widgets.SelectMultiple( attrs={'class': 'form-control select2', 'style': 'width: 100%;', 'multiple': "multiple"}), }
Remove unused FormLogin in admin app
[REMOVE] Remove unused FormLogin in admin app
Python
mit
vuonghv/brs,vuonghv/brs,vuonghv/brs,vuonghv/brs
6f464e422befe22e56bb759a7ac7ff52a353c6d9
accountant/functional_tests/test_layout_and_styling.py
accountant/functional_tests/test_layout_and_styling.py
# -*- coding: utf-8 -*- import unittest from .base import FunctionalTestCase from .pages import game class StylesheetTests(FunctionalTestCase): def test_color_css_loaded(self): self.story('Create a game') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) page.start_button.click() self.assertTrue(any('css/color.css' in s.get_attribute('href') for s in page.stylesheets)) def test_main_stylesheet_loaded(self): self.story('Load the start page') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) self.assertTrue(any('css/main.css' in s.get_attribute('href') for s in page.stylesheets))
# -*- coding: utf-8 -*- import unittest from .base import FunctionalTestCase from .pages import game class StylesheetTests(FunctionalTestCase): def test_color_css_loaded(self): self.story('Create a game') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) page.start_button.click() self.assertTrue(any('css/color.css' in s.get_attribute('href') for s in page.stylesheets)) def test_main_stylesheet_loaded(self): self.story('Load the start page') self.browser.get(self.live_server_url) page = game.Homepage(self.browser) self.assertTrue(any('css/main.css' in s.get_attribute('href') for s in page.stylesheets)) # Test constant to see if css actually gets loaded self.assertEqual('rgb(55, 71, 79)', page.bank_cash.value_of_css_property('border-color'))
Test is loaded CSS is applied
Test is loaded CSS is applied
Python
mit
XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant
517f53dc91164f4249de9dbaf31be65df02ffde7
numpy/fft/setup.py
numpy/fft/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('fft', parent_package, top_path) config.add_data_dir('tests') # Configure pocketfft_internal config.add_extension('_pocketfft_internal', sources=['_pocketfft.c'] ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
import sys def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('fft', parent_package, top_path) config.add_data_dir('tests') # AIX needs to be told to use large file support - at all times defs = [('_LARGE_FILES', None)] if sys.platform[:3] == "aix" else [] # Configure pocketfft_internal config.add_extension('_pocketfft_internal', sources=['_pocketfft.c'], define_macros=defs, ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
Add _LARGE_FILES to def_macros[] when platform is AIX (gh-15938)
BUG: Add _LARGE_FILES to def_macros[] when platform is AIX (gh-15938) AIX needs to be told to use large file support at all times. Fixes parts of gh-15801.
Python
bsd-3-clause
mhvk/numpy,pbrod/numpy,mattip/numpy,anntzer/numpy,numpy/numpy,numpy/numpy,pbrod/numpy,rgommers/numpy,numpy/numpy,endolith/numpy,abalkin/numpy,pdebuyl/numpy,grlee77/numpy,mattip/numpy,grlee77/numpy,pdebuyl/numpy,charris/numpy,charris/numpy,seberg/numpy,pbrod/numpy,grlee77/numpy,anntzer/numpy,jakirkham/numpy,seberg/numpy,rgommers/numpy,simongibbons/numpy,pdebuyl/numpy,madphysicist/numpy,endolith/numpy,abalkin/numpy,anntzer/numpy,mhvk/numpy,mhvk/numpy,jakirkham/numpy,simongibbons/numpy,mattip/numpy,simongibbons/numpy,grlee77/numpy,numpy/numpy,madphysicist/numpy,seberg/numpy,pbrod/numpy,charris/numpy,charris/numpy,endolith/numpy,madphysicist/numpy,mhvk/numpy,endolith/numpy,jakirkham/numpy,simongibbons/numpy,abalkin/numpy,madphysicist/numpy,mhvk/numpy,simongibbons/numpy,rgommers/numpy,seberg/numpy,mattip/numpy,grlee77/numpy,anntzer/numpy,jakirkham/numpy,madphysicist/numpy,pbrod/numpy,pdebuyl/numpy,rgommers/numpy,jakirkham/numpy
8a522bc92bbf5bee8bc32a0cc332dc77fa86fcd6
drcontroller/http_server.py
drcontroller/http_server.py
import eventlet import os import commands from eventlet import wsgi from paste.deploy import loadapp def main(): conf = "conf/api-paste.ini" appname = "main" commands.getoutput('mkdir -p ../logs') app = loadapp("config:%s" % os.path.abspath(conf), appname) wsgi.server(eventlet.listen(('', 80)), app) if __name__ == '__main__': main()
import eventlet import os import commands from eventlet import wsgi from paste.deploy import loadapp # Monkey patch socket, time, select, threads eventlet.patcher.monkey_patch(all=False, socket=True, time=True, select=True, thread=True, os=True) def main(): conf = "conf/api-paste.ini" appname = "main" commands.getoutput('mkdir -p ../logs') app = loadapp("config:%s" % os.path.abspath(conf), appname) wsgi.server(eventlet.listen(('', 80)), app) if __name__ == '__main__': main()
Update http server to un-blocking
Update http server to un-blocking
Python
apache-2.0
fs714/drcontroller
620bf504292583b2547cf7489eeeaaa582ddad77
indra/tests/test_ctd.py
indra/tests/test_ctd.py
import os from indra.statements import * from indra.sources import ctd from indra.sources.ctd.processor import CTDChemicalGeneProcessor HERE = os.path.dirname(os.path.abspath(__file__)) def test_statement_type_mapping(): st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^phosphorylation', 'X', 'X decreases the phosphorylation of Y') assert set(st.values()) == {Dephosphorylation}, st st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^reaction|increases^phosphorylation', 'X', 'X decreases the reaction [Z increases the phosphorylation of Y]') assert set(st.values()) == {Dephosphorylation}, st def test_chemical_gene(): fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv') cp = ctd.process_tsv(fname, 'chemical_gene') assert len(cp.statements) == 4, cp.statements
import os from indra.statements import * from indra.sources import ctd from indra.sources.ctd.processor import CTDChemicalGeneProcessor HERE = os.path.dirname(os.path.abspath(__file__)) def test_statement_type_mapping(): st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^phosphorylation', 'X', 'X decreases the phosphorylation of Y') assert set(st.values()) == {Dephosphorylation}, st st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^reaction|increases^phosphorylation', 'X', 'X decreases the reaction [Z increases the phosphorylation of Y]') assert set(st.values()) == {Dephosphorylation}, st def test_chemical_gene(): fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv') cp = ctd.process_tsv(fname, 'chemical_gene') assert len(cp.statements) == 3, cp.statements assert isinstance(cp.statements[0], Dephosphorylation) assert cp.statements[0].enz.name == 'wortmannin' assert isinstance(cp.statements[1], Dephosphorylation) assert cp.statements[1].enz.name == 'YM-254890' assert isinstance(cp.statements[2], Phosphorylation) assert cp.statements[2].enz.name == 'zinc atom'
Fix and extend test conditions
Fix and extend test conditions
Python
bsd-2-clause
sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,sorgerlab/belpy
0e2270415b287cb643cff5023dcaacbcb2d5e3fc
translators/google.py
translators/google.py
#!/usr/bin/python # -*- coding: utf-8 -*- import time import requests def save_google_translation(queue, source_text, client_id, client_secret, translate_from='et', translate_to='en'): translation = '' try: begin = time.time() translation = google_translation(source_text, translate_from=translate_from, translate_to=translate_to) end = time.time() print("Google", end - begin) except Exception as e: print("Google failed!", e) queue.put({'translation_google': translation}) return None def google_translation(text, translate_from='et', translate_to='en'): response = requests.get(url) translation = response['data']['translations'][0]['translatedText'] print("Test", translation) return translation
#!/usr/bin/python # -*- coding: utf-8 -*- import time import requests import json def save_google_translation(queue, source_text, translate_from='et', translate_to='en'): translation = '' try: begin = time.time() translation = google_translation(source_text, translate_from=translate_from, translate_to=translate_to) end = time.time() print("Google", end - begin) except Exception as e: print("Google failed!", e) queue.put({'translation_google': translation}) return None def google_translation(text, translate_from='et', translate_to='en'): response = requests.get(url) json_response = json.loads(response.text) translation = json_response['data']['translations'][0]['translatedText'] return translation
Fix Google Translator request & processing
Fix Google Translator request & processing
Python
mit
ChameleonTartu/neurotolge,ChameleonTartu/neurotolge,ChameleonTartu/neurotolge
0f018ec9bfd0c93d980b232af325be453c065632
qsimcirq/_version.py
qsimcirq/_version.py
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.14.0"
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.14.1.dev20220804"
Update to dev version 0.14.1+dev20220804
Update to dev version 0.14.1+dev20220804
Python
apache-2.0
quantumlib/qsim,quantumlib/qsim,quantumlib/qsim,quantumlib/qsim
4e8dc0ca41ee1e21a75a3e803c3b2b223d9f14cb
users/managers.py
users/managers.py
from django.utils import timezone from django.contrib.auth.models import BaseUserManager from model_utils.managers import InheritanceQuerySet from .conf import settings class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): users_auto_activate = not settings.USERS_VERIFY_EMAIL now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) is_active = extra_fields.pop('is_active', users_auto_activate) user = self.model(email=email, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): is_staff = extra_fields.pop('is_staff', False) return self._create_user(email, password, is_staff, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class UserInheritanceManager(UserManager): def get_queryset(self): return InheritanceQuerySet(self.model).select_subclasses()
from django.utils import timezone from django.contrib.auth.models import BaseUserManager from model_utils.managers import InheritanceQuerySet from .conf import settings class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): users_auto_activate = not settings.USERS_VERIFY_EMAIL now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) is_active = extra_fields.pop('is_active', users_auto_activate) user = self.model(email=email, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): is_staff = extra_fields.pop('is_staff', False) return self._create_user(email, password, is_staff, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, is_active=True, **extra_fields) class UserInheritanceManager(UserManager): def get_queryset(self): return InheritanceQuerySet(self.model).select_subclasses()
Fix issue with create_superuser method on UserManager
Fix issue with create_superuser method on UserManager
Python
bsd-3-clause
mishbahr/django-users2,mishbahr/django-users2
818e15028c4dd158fa93fe4bcd351255585c2f4f
src/model/predict_rf_model.py
src/model/predict_rf_model.py
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year]) cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl') test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl') X_test = test.ix[:,1:] print "predict RandomForest Classifier..." probs = cforest.predict_proba(X_test) sorted_index = np.argsort(-np.array(probs))[:,:5] result = pd.DataFrame(columns = {'hotel_cluster'}) result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])]) result.hotel_cluster.to_csv(utils.model_path + 'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year]) cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl') test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl') #X_test = test.ix[:,1:] X_test = test.ix[:9,1:] X_test.fillna(-1, inplace=True) print "predict RandomForest Classifier..." probs = cforest.predict_proba(X_test) sorted_index = np.argsort(-np.array(probs))[:,:5] result = pd.DataFrame(columns = {'hotel_cluster'}) result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])]) result.hotel_cluster.to_csv(utils.model_path + 'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
Handle missing value in predit rf
Handle missing value in predit rf
Python
bsd-3-clause
parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia
8cc8f9a1535a2361c27e9411f9163ecd2a9958d5
utils/__init__.py
utils/__init__.py
import pymongo connection = pymongo.MongoClient("mongodb://localhost") db = connection.vcf_explorer import database import parse_vcf import filter_vcf import query
import pymongo import config #config.py connection = pymongo.MongoClient(host=config.MONGODB_HOST, port=config.MONGODB_PORT) db = connection[config.MONGODB_NAME] import database import parse_vcf import filter_vcf import query
Set mongodb settings using config.py
Set mongodb settings using config.py
Python
mit
CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer
2206681a89346970b71ca8d0ed1ff60a861b2ff9
doc/examples/plot_pyramid.py
doc/examples/plot_pyramid.py
""" ==================== Build image pyramids ==================== This example shows how to build image pyramids. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage import img_as_float from skimage.transform import build_gaussian_pyramid image = data.lena() rows, cols, dim = image.shape pyramid = tuple(build_gaussian_pyramid(image, downscale=2)) display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) display[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] display[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(display) plt.show()
""" ==================== Build image pyramids ==================== The `build_gauassian_pyramid` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage import img_as_float from skimage.transform import build_gaussian_pyramid image = data.lena() rows, cols, dim = image.shape pyramid = tuple(build_gaussian_pyramid(image, downscale=2)) display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) display[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] display[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(display) plt.show()
Update pyramid example with longer description
Update pyramid example with longer description
Python
bsd-3-clause
chintak/scikit-image,paalge/scikit-image,keflavich/scikit-image,SamHames/scikit-image,jwiggins/scikit-image,bsipocz/scikit-image,keflavich/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,youprofit/scikit-image,chintak/scikit-image,dpshelio/scikit-image,Midafi/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,bennlich/scikit-image,ajaybhat/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,ClinicalGraphics/scikit-image,almarklein/scikit-image,emon10005/scikit-image,oew1v07/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,almarklein/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,newville/scikit-image,pratapvardhan/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,ClinicalGraphics/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,dpshelio/scikit-image,blink1073/scikit-image,vighneshbirodkar/scikit-image,michaelpacer/scikit-image,rjeli/scikit-image,emon10005/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,Britefury/scikit-image,paalge/scikit-image,ajaybhat/scikit-image,oew1v07/scikit-image,robintw/scikit-image,michaelaye/scikit-image,robintw/scikit-image
1454b42049e94db896aab99e2dd1b286ca2d04e3
convert-bookmarks.py
convert-bookmarks.py
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup from datetime import datetime, timezone import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='*') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tags to bookmarks') args = parser.parse_args() bookmarks = [] for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() secs = link.get('add_date') date = datetime.fromtimestamp(int(secs), tz=timezone.utc) bookmark['add_date'] = { '$date': date.isoformat() } bookmark['tags'] = link.get('tags').split(',') sibling = link.parent.next_sibling if sibling and sibling.name == 'dd': bookmark['comment'] = sibling.string.strip() print(json.dumps(bookmark, sort_keys=False, indent=4))
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup from datetime import datetime, timezone import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='*') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') parser.add_argument('-m', '--mongodb', action='store_true', dest='mongo', help='output in mongodb import format') args = parser.parse_args() for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() secs = link.get('add_date') date = datetime.fromtimestamp(int(secs), tz=timezone.utc) bookmark['add_date'] = {'$date': date.isoformat()} if args.mongo \ else date.isoformat() bookmark['tags'] = link.get('tags').split(',') if args.tags: bookmark['tags'] += args.tags sibling = link.parent.next_sibling if sibling and sibling.name == 'dd': bookmark['comment'] = sibling.string.strip() print(json.dumps(bookmark, sort_keys=False, indent=4))
Add options for add date and tags.
Add options for add date and tags.
Python
mit
jhh/netscape-bookmark-converter
6cd7e79fc32ebf75776ab0bcf367854d76dd5e03
src/redditsubscraper/items.py
src/redditsubscraper/items.py
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import scrapy class Post(scrapy.Item): """ A model representing a single Reddit post. """ id = scrapy.Field() class Comment(scrapy.Item): """ A model representing a single Reddit comment """ id = scrapy.Field() parent_id = scrapy.Field() class RedditItemPipeline(object): pass
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import scrapy class Post(scrapy.Item): """ A model representing a single Reddit post. """ """An id encoded in base-36 without any prefixes.""" id = scrapy.Field() class Comment(scrapy.Item): """ A model representing a single Reddit comment """ """An id encoded in base-36 without any prefixes.""" id = scrapy.Field() parent_id = scrapy.Field() class RedditItemPipeline(object): pass
Add comments to item fields.
Add comments to item fields.
Python
mit
rfkrocktk/subreddit-scraper
b590ddd735131faa3fd1bdc91b1866e1bd7b0738
us_ignite/snippets/management/commands/snippets_load_fixtures.py
us_ignite/snippets/management/commands/snippets_load_fixtures.py
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'Up next:', 'body': '', 'url_text': 'Get involved', 'url': '', }, ] class Command(BaseCommand): def handle(self, *args, **options): for data in FIXTURES: try: # Ignore existing snippets: Snippet.objects.get(slug=data['slug']) continue except Snippet.DoesNotExist: pass data.update({ 'status': Snippet.PUBLISHED, }) Snippet.objects.create(**data) print u'Importing %s' % data['slug'] print "Done!"
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'UP NEXT: LOREM IPSUM', 'body': '', 'url_text': 'GET INVOLVED', 'url': '', }, { 'slug': 'featured', 'name': 'FEATURED CONTENT', 'body': '', 'url_text': 'FEATURED', 'url': '', }, ] class Command(BaseCommand): def handle(self, *args, **options): for data in FIXTURES: try: # Ignore existing snippets: Snippet.objects.get(slug=data['slug']) continue except Snippet.DoesNotExist: pass data.update({ 'status': Snippet.PUBLISHED, }) Snippet.objects.create(**data) print u'Importing %s' % data['slug'] print "Done!"
Add featured homepage initial fixture.
Add featured homepage initial fixture.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
d37f91f50dd6c0c3202258daca95ee6ee111688f
pyjswidgets/pyjamas/ui/Focus.oldmoz.py
pyjswidgets/pyjamas/ui/Focus.oldmoz.py
def ensureFocusHandler(): JS(""" return (focusHandler !== null) ? focusHandler : (focusHandler = @{{createFocusHandler}}()); """) def createFocusHandler(): JS(""" return function(evt) { // This function is called directly as an event handler, so 'this' is // set up by the browser to be the input on which the event is fired. We // call focus() in a timeout or the element may be blurred when this event // ends. var div = this['parentNode']; if (div['onfocus']) { $wnd['setTimeout'](function() { div['focus'](); }, 0); } }; """) def createFocusable0(focusHandler): JS(""" var div = $doc['createElement']('div'); div['tabIndex'] = 0; var input = $doc['createElement']('input'); input['type'] = 'text'; input['style']['opacity'] = 0; input['tabIndex'] = -1; input['style']['zIndex'] = -1; input['style']['width'] = '1px'; input['style']['height'] = '1px'; input['style']['overflow'] = 'hidden'; input['style']['position'] = 'absolute'; input['addEventListener']( 'focus', focusHandler, false); div['appendChild'](input); return div; """) def createFocusable(): ensureFocusHandler() return createFocusable0()
def ensureFocusHandler(): JS(""" return (focusHandler !== null) ? focusHandler : (focusHandler = @{{createFocusHandler}}()); """) def createFocusHandler(): JS(""" return function(evt) { // This function is called directly as an event handler, so 'this' is // set up by the browser to be the input on which the event is fired. We // call focus() in a timeout or the element may be blurred when this event // ends. var div = this['parentNode']; if (div['onfocus']) { $wnd['setTimeout'](function() { div['focus'](); }, 0); } }; """) def createFocusable0(focusHandler): JS(""" var div = $doc['createElement']('div'); div['tabIndex'] = 0; var input = $doc['createElement']('input'); input['type'] = 'text'; input['style']['opacity'] = 0; input['tabIndex'] = -1; input['style']['zIndex'] = -1; input['style']['width'] = '1px'; input['style']['height'] = '1px'; input['style']['overflow'] = 'hidden'; input['style']['position'] = 'absolute'; input['addEventListener']( 'focus', focusHandler, false); div['appendChild'](input); return div; """) def createFocusable(): return createFocusable0(ensureFocusHandler())
Fix for IE 11 (Focus)
Fix for IE 11 (Focus) IE presents itself as mozilla, so it trips on the bug.
Python
apache-2.0
gpitel/pyjs,spaceone/pyjs,lancezlin/pyjs,spaceone/pyjs,lancezlin/pyjs,pombredanne/pyjs,pyjs/pyjs,Hasimir/pyjs,gpitel/pyjs,pyjs/pyjs,spaceone/pyjs,pyjs/pyjs,Hasimir/pyjs,lancezlin/pyjs,pyjs/pyjs,pombredanne/pyjs,gpitel/pyjs,Hasimir/pyjs,gpitel/pyjs,spaceone/pyjs,pombredanne/pyjs,lancezlin/pyjs,pombredanne/pyjs,Hasimir/pyjs
3d5fd3233ecaf2bae5fbd5a1ae349c55d2f4cdc7
scistack/scistack.py
scistack/scistack.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SciStack: the web app to build docker containers for reproducable science """ import os import flask app = flask.Flask(__name__) @app.route("/") def hello(): return "Choose a domain!" if __name__ == "__main__": app.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SciStack: the web app to build docker containers for reproducable science """ import os import flask import inspect app = flask.Flask(__name__, static_url_path='') # Home of any pre-build docker files docker_file_path = os.path.join(os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))), "..", "dockerfiles") @app.route("/") def hello(): return "Choose a domain!" @app.route("/dfview/<path:fname>") def send_dockerfile(fname): with open(os.path.join(docker_file_path, fname)) as dfile: return_value = dfile.read() return return_value if __name__ == "__main__": app.run()
Return pre-built dockerfile to user
Return pre-built dockerfile to user
Python
mit
callaghanmt/research-stacks,callaghanmt/research-stacks,callaghanmt/research-stacks
834d02d65b0d71bd044b18b0be031751a8c1a7de
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '607907aed2c1dcdd3b5968a756a990ba3f47bca7'
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '276722e68bb643e3ae3b468b701c276aeb884838'
Upgrade libchromiumcontent: Add support for acceptsFirstMouse.
Upgrade libchromiumcontent: Add support for acceptsFirstMouse.
Python
mit
bbondy/electron,greyhwndz/electron,Neron-X5/electron,jacksondc/electron,baiwyc119/electron,brave/electron,tinydew4/electron,trigrass2/electron,pirafrank/electron,arturts/electron,RobertJGabriel/electron,takashi/electron,wan-qy/electron,hokein/atom-shell,digideskio/electron,tincan24/electron,jonatasfreitasv/electron,beni55/electron,tinydew4/electron,mhkeller/electron,aaron-goshine/electron,michaelchiche/electron,systembugtj/electron,leolujuyi/electron,bwiggs/electron,chrisswk/electron,twolfson/electron,tylergibson/electron,yan-foto/electron,MaxWhere/electron,vipulroxx/electron,matiasinsaurralde/electron,roadev/electron,Faiz7412/electron,arturts/electron,IonicaBizauKitchen/electron,felixrieseberg/electron,fomojola/electron,aichingm/electron,MaxWhere/electron,Andrey-Pavlov/electron,timruffles/electron,tinydew4/electron,John-Lin/electron,adamjgray/electron,aichingm/electron,IonicaBizauKitchen/electron,bruce/electron,preco21/electron,etiktin/electron,howmuchcomputer/electron,voidbridge/electron,DivyaKMenon/electron,leethomas/electron,edulan/electron,eric-seekas/electron,medixdev/electron,vHanda/electron,thomsonreuters/electron,leethomas/electron,michaelchiche/electron,rprichard/electron,evgenyzinoviev/electron,robinvandernoord/electron,tincan24/electron,rhencke/electron,greyhwndz/electron,jtburke/electron,carsonmcdonald/electron,beni55/electron,ankitaggarwal011/electron,jlord/electron,howmuchcomputer/electron,brave/electron,aecca/electron,digideskio/electron,posix4e/electron,fffej/electron,iftekeriba/electron,pombredanne/electron,shennushi/electron,meowlab/electron,bruce/electron,Jacobichou/electron,d-salas/electron,fomojola/electron,gabrielPeart/electron,davazp/electron,etiktin/electron,takashi/electron,christian-bromann/electron,digideskio/electron,kenmozi/electron,farmisen/electron,wan-qy/electron,gamedevsam/electron,RIAEvangelist/electron,stevemao/electron,setzer777/electron,aliib/electron,davazp/electron,chriskdon/electron,cqqccqc/electron,maxogden/atom-shell,vipulroxx/electron,gamedevsam/electron,bpasero/electron,jaanus/electron,oiledCode/electron,Rokt33r/electron,meowlab/electron,aichingm/electron,fireball-x/atom-shell,xiruibing/electron,trigrass2/electron,evgenyzinoviev/electron,aichingm/electron,shaundunne/electron,rajatsingla28/electron,thingsinjars/electron,jaanus/electron,rhencke/electron,thompsonemerson/electron,chriskdon/electron,stevemao/electron,destan/electron,rajatsingla28/electron,GoooIce/electron,dongjoon-hyun/electron,arusakov/electron,timruffles/electron,vaginessa/electron,trigrass2/electron,sircharleswatson/electron,neutrous/electron,pombredanne/electron,vipulroxx/electron,coderhaoxin/electron,brave/muon,sky7sea/electron,jlord/electron,anko/electron,JesselJohn/electron,sircharleswatson/electron,baiwyc119/electron,rreimann/electron,zhakui/electron,shiftkey/electron,egoist/electron,tomashanacek/electron,gstack/infinium-shell,GoooIce/electron,kazupon/electron,ervinb/electron,nekuz0r/electron,egoist/electron,xfstudio/electron,adcentury/electron,tincan24/electron,systembugtj/electron,mhkeller/electron,gerhardberger/electron,BionicClick/electron,vaginessa/electron,jsutcodes/electron,felixrieseberg/electron,gamedevsam/electron,iftekeriba/electron,BionicClick/electron,wolfflow/electron,aecca/electron,chrisswk/electron,anko/electron,jsutcodes/electron,nicobot/electron,ankitaggarwal011/electron,arusakov/electron,stevekinney/electron,aaron-goshine/electron,jacksondc/electron,lrlna/electron,zhakui/electron,wan-qy/electron,trigrass2/electron,shennushi/electron,natgolov/electron,kokdemo/electron,neutrous/electron,miniak/electron,mattdesl/electron,iftekeriba/electron,nicholasess/electron,thompsonemerson/electron,Rokt33r/electron,RobertJGabriel/electron,setzer777/electron,jlord/electron,saronwei/electron,Gerhut/electron,thingsinjars/electron,Gerhut/electron,DivyaKMenon/electron,zhakui/electron,lzpfmh/electron,gbn972/electron,lzpfmh/electron,matiasinsaurralde/electron,noikiy/electron,the-ress/electron,fabien-d/electron,gabriel/electron,davazp/electron,astoilkov/electron,jiaz/electron,JussMee15/electron,nekuz0r/electron,jjz/electron,leftstick/electron,rsvip/electron,jiaz/electron,DivyaKMenon/electron,gabrielPeart/electron,stevemao/electron,Evercoder/electron,Rokt33r/electron,maxogden/atom-shell,bbondy/electron,Zagorakiss/electron,aliib/electron,mjaniszew/electron,twolfson/electron,biblerule/UMCTelnetHub,bobwol/electron,rsvip/electron,dongjoon-hyun/electron,abhishekgahlot/electron,nicholasess/electron,subblue/electron,zhakui/electron,felixrieseberg/electron,eriser/electron,carsonmcdonald/electron,digideskio/electron,dahal/electron,tonyganch/electron,RIAEvangelist/electron,yan-foto/electron,anko/electron,arusakov/electron,d-salas/electron,minggo/electron,evgenyzinoviev/electron,rhencke/electron,digideskio/electron,xiruibing/electron,jcblw/electron,electron/electron,posix4e/electron,mrwizard82d1/electron,Jacobichou/electron,adcentury/electron,bright-sparks/electron,timruffles/electron,smczk/electron,aaron-goshine/electron,micalan/electron,arturts/electron,gamedevsam/electron,Evercoder/electron,beni55/electron,sircharleswatson/electron,aaron-goshine/electron,darwin/electron,Neron-X5/electron,medixdev/electron,gabrielPeart/electron,hokein/atom-shell,tinydew4/electron,egoist/electron,twolfson/electron,shennushi/electron,nicobot/electron,jacksondc/electron,SufianHassan/electron,GoooIce/electron,stevekinney/electron,thingsinjars/electron,shaundunne/electron,kostia/electron,adcentury/electron,seanchas116/electron,Floato/electron,jhen0409/electron,minggo/electron,seanchas116/electron,howmuchcomputer/electron,the-ress/electron,rhencke/electron,jaanus/electron,lrlna/electron,bitemyapp/electron,takashi/electron,Ivshti/electron,eriser/electron,natgolov/electron,smczk/electron,maxogden/atom-shell,mubassirhayat/electron,dongjoon-hyun/electron,renaesop/electron,faizalpribadi/electron,farmisen/electron,Jacobichou/electron,leftstick/electron,joneit/electron,stevekinney/electron,mattotodd/electron,vHanda/electron,egoist/electron,matiasinsaurralde/electron,carsonmcdonald/electron,brenca/electron,gabriel/electron,xiruibing/electron,cos2004/electron,jlhbaseball15/electron,seanchas116/electron,JesselJohn/electron,minggo/electron,joaomoreno/atom-shell,micalan/electron,systembugtj/electron,egoist/electron,benweissmann/electron,pirafrank/electron,howmuchcomputer/electron,eriser/electron,felixrieseberg/electron,abhishekgahlot/electron,MaxGraey/electron,nagyistoce/electron-atom-shell,miniak/electron,dongjoon-hyun/electron,leolujuyi/electron,lzpfmh/electron,wolfflow/electron,RobertJGabriel/electron,soulteary/electron,takashi/electron,jcblw/electron,SufianHassan/electron,edulan/electron,bobwol/electron,gabriel/electron,shaundunne/electron,jjz/electron,pandoraui/electron,Andrey-Pavlov/electron,greyhwndz/electron,thingsinjars/electron,jhen0409/electron,shockone/electron,vHanda/electron,jjz/electron,jcblw/electron,micalan/electron,Rokt33r/electron,soulteary/electron,gabriel/electron,davazp/electron,nicholasess/electron,bpasero/electron,Jacobichou/electron,BionicClick/electron,deed02392/electron,thompsonemerson/electron,renaesop/electron,astoilkov/electron,egoist/electron,kokdemo/electron,nekuz0r/electron,shiftkey/electron,icattlecoder/electron,micalan/electron,jonatasfreitasv/electron,kikong/electron,mattdesl/electron,joneit/electron,mrwizard82d1/electron,fritx/electron,brave/electron,jiaz/electron,Jonekee/electron,tylergibson/electron,leethomas/electron,renaesop/electron,chriskdon/electron,eric-seekas/electron,farmisen/electron,yan-foto/electron,leftstick/electron,voidbridge/electron,RIAEvangelist/electron,chrisswk/electron,ianscrivener/electron,IonicaBizauKitchen/electron,RIAEvangelist/electron,smczk/electron,matiasinsaurralde/electron,jhen0409/electron,kenmozi/electron,soulteary/electron,sshiting/electron,JesselJohn/electron,d-salas/electron,rsvip/electron,kostia/electron,twolfson/electron,RobertJGabriel/electron,setzer777/electron,sircharleswatson/electron,stevemao/electron,ianscrivener/electron,joneit/electron,eriser/electron,robinvandernoord/electron,icattlecoder/electron,trankmichael/electron,renaesop/electron,gstack/infinium-shell,kenmozi/electron,noikiy/electron,twolfson/electron,fireball-x/atom-shell,soulteary/electron,shockone/electron,Gerhut/electron,carsonmcdonald/electron,jiaz/electron,aichingm/electron,miniak/electron,voidbridge/electron,bpasero/electron,jsutcodes/electron,gbn972/electron,deepak1556/atom-shell,gbn972/electron,tonyganch/electron,adamjgray/electron,stevekinney/electron,yan-foto/electron,hokein/atom-shell,mirrh/electron,anko/electron,jannishuebl/electron,trankmichael/electron,tomashanacek/electron,ankitaggarwal011/electron,robinvandernoord/electron,maxogden/atom-shell,robinvandernoord/electron,shockone/electron,joneit/electron,baiwyc119/electron,davazp/electron,ervinb/electron,cqqccqc/electron,preco21/electron,micalan/electron,LadyNaggaga/electron,gabrielPeart/electron,howmuchcomputer/electron,fabien-d/electron,preco21/electron,tincan24/electron,gabrielPeart/electron,gstack/infinium-shell,JesselJohn/electron,mrwizard82d1/electron,Floato/electron,oiledCode/electron,shennushi/electron,jacksondc/electron,brave/electron,SufianHassan/electron,soulteary/electron,arturts/electron,bruce/electron,rajatsingla28/electron,fomojola/electron,jaanus/electron,medixdev/electron,bwiggs/electron,bitemyapp/electron,aecca/electron,saronwei/electron,felixrieseberg/electron,tylergibson/electron,eric-seekas/electron,beni55/electron,aliib/electron,tylergibson/electron,Faiz7412/electron,michaelchiche/electron,edulan/electron,yalexx/electron,synaptek/electron,icattlecoder/electron,gabriel/electron,yalexx/electron,kokdemo/electron,digideskio/electron,jsutcodes/electron,setzer777/electron,evgenyzinoviev/electron,ervinb/electron,benweissmann/electron,webmechanicx/electron,jjz/electron,noikiy/electron,noikiy/electron,seanchas116/electron,miniak/electron,bobwol/electron,MaxGraey/electron,christian-bromann/electron,coderhaoxin/electron,icattlecoder/electron,d-salas/electron,rreimann/electron,pombredanne/electron,voidbridge/electron,ianscrivener/electron,sky7sea/electron,ervinb/electron,the-ress/electron,astoilkov/electron,mrwizard82d1/electron,joaomoreno/atom-shell,aliib/electron,chrisswk/electron,rsvip/electron,Zagorakiss/electron,jonatasfreitasv/electron,abhishekgahlot/electron,rajatsingla28/electron,subblue/electron,yan-foto/electron,fritx/electron,John-Lin/electron,kenmozi/electron,evgenyzinoviev/electron,vipulroxx/electron,setzer777/electron,shennushi/electron,thompsonemerson/electron,SufianHassan/electron,cqqccqc/electron,fffej/electron,destan/electron,Evercoder/electron,etiktin/electron,astoilkov/electron,jtburke/electron,arturts/electron,mhkeller/electron,mattotodd/electron,mattdesl/electron,smczk/electron,jcblw/electron,cos2004/electron,Andrey-Pavlov/electron,chriskdon/electron,destan/electron,jlhbaseball15/electron,anko/electron,leftstick/electron,carsonmcdonald/electron,rprichard/electron,kikong/electron,adcentury/electron,posix4e/electron,chrisswk/electron,michaelchiche/electron,rreimann/electron,eric-seekas/electron,roadev/electron,synaptek/electron,MaxWhere/electron,bbondy/electron,rajatsingla28/electron,takashi/electron,Andrey-Pavlov/electron,leolujuyi/electron,brave/muon,eriser/electron,BionicClick/electron,jlord/electron,bitemyapp/electron,wan-qy/electron,mattotodd/electron,electron/electron,Rokt33r/electron,IonicaBizauKitchen/electron,jannishuebl/electron,webmechanicx/electron,roadev/electron,deepak1556/atom-shell,tonyganch/electron,Floato/electron,Jonekee/electron,davazp/electron,chriskdon/electron,mhkeller/electron,thomsonreuters/electron,jhen0409/electron,pandoraui/electron,Ivshti/electron,kostia/electron,Gerhut/electron,kcrt/electron,edulan/electron,matiasinsaurralde/electron,arusakov/electron,minggo/electron,jlhbaseball15/electron,mirrh/electron,neutrous/electron,leolujuyi/electron,RIAEvangelist/electron,bruce/electron,biblerule/UMCTelnetHub,ervinb/electron,dahal/electron,brenca/electron,meowlab/electron,medixdev/electron,webmechanicx/electron,gerhardberger/electron,fireball-x/atom-shell,tomashanacek/electron,joaomoreno/atom-shell,dahal/electron,oiledCode/electron,John-Lin/electron,sircharleswatson/electron,systembugtj/electron,etiktin/electron,iftekeriba/electron,tinydew4/electron,meowlab/electron,xiruibing/electron,roadev/electron,Jonekee/electron,bright-sparks/electron,adamjgray/electron,felixrieseberg/electron,jsutcodes/electron,arusakov/electron,nicobot/electron,sky7sea/electron,trigrass2/electron,jlhbaseball15/electron,vaginessa/electron,kcrt/electron,mubassirhayat/electron,bpasero/electron,shockone/electron,wolfflow/electron,bright-sparks/electron,Andrey-Pavlov/electron,astoilkov/electron,pandoraui/electron,sshiting/electron,electron/electron,leolujuyi/electron,christian-bromann/electron,deed02392/electron,kazupon/electron,DivyaKMenon/electron,brave/electron,posix4e/electron,bbondy/electron,wolfflow/electron,simonfork/electron,robinvandernoord/electron,wan-qy/electron,astoilkov/electron,fffej/electron,deepak1556/atom-shell,kokdemo/electron,joaomoreno/atom-shell,joaomoreno/atom-shell,yalexx/electron,bright-sparks/electron,Gerhut/electron,preco21/electron,pirafrank/electron,fomojola/electron,nicobot/electron,medixdev/electron,bitemyapp/electron,jonatasfreitasv/electron,mirrh/electron,webmechanicx/electron,mhkeller/electron,sshiting/electron,bright-sparks/electron,natgolov/electron,deepak1556/atom-shell,mjaniszew/electron,darwin/electron,saronwei/electron,Zagorakiss/electron,leethomas/electron,cos2004/electron,greyhwndz/electron,pandoraui/electron,MaxWhere/electron,gerhardberger/electron,minggo/electron,abhishekgahlot/electron,DivyaKMenon/electron,faizalpribadi/electron,vHanda/electron,bruce/electron,Andrey-Pavlov/electron,jcblw/electron,rreimann/electron,coderhaoxin/electron,joneit/electron,arturts/electron,gerhardberger/electron,mattdesl/electron,pirafrank/electron,darwin/electron,Faiz7412/electron,nicholasess/electron,coderhaoxin/electron,LadyNaggaga/electron,trankmichael/electron,takashi/electron,bitemyapp/electron,leolujuyi/electron,pandoraui/electron,xiruibing/electron,Zagorakiss/electron,gstack/infinium-shell,leftstick/electron,simongregory/electron,roadev/electron,voidbridge/electron,michaelchiche/electron,meowlab/electron,Jonekee/electron,mjaniszew/electron,natgolov/electron,kostia/electron,benweissmann/electron,seanchas116/electron,fritx/electron,jiaz/electron,mjaniszew/electron,aecca/electron,RobertJGabriel/electron,aliib/electron,jaanus/electron,rprichard/electron,yalexx/electron,wan-qy/electron,the-ress/electron,mattotodd/electron,kenmozi/electron,Neron-X5/electron,JussMee15/electron,eric-seekas/electron,kokdemo/electron,jtburke/electron,rajatsingla28/electron,mattotodd/electron,mattdesl/electron,LadyNaggaga/electron,LadyNaggaga/electron,zhakui/electron,stevemao/electron,jacksondc/electron,farmisen/electron,carsonmcdonald/electron,nicholasess/electron,shockone/electron,bitemyapp/electron,timruffles/electron,synaptek/electron,aliib/electron,brave/muon,simonfork/electron,ervinb/electron,darwin/electron,the-ress/electron,farmisen/electron,vipulroxx/electron,bbondy/electron,oiledCode/electron,Ivshti/electron,cqqccqc/electron,fireball-x/atom-shell,faizalpribadi/electron,simongregory/electron,Evercoder/electron,Jonekee/electron,joneit/electron,jtburke/electron,preco21/electron,ianscrivener/electron,nagyistoce/electron-atom-shell,kostia/electron,leethomas/electron,simonfork/electron,kikong/electron,brenca/electron,BionicClick/electron,RIAEvangelist/electron,jacksondc/electron,subblue/electron,tonyganch/electron,beni55/electron,MaxGraey/electron,timruffles/electron,nagyistoce/electron-atom-shell,posix4e/electron,Gerhut/electron,BionicClick/electron,kcrt/electron,benweissmann/electron,jlord/electron,jannishuebl/electron,leethomas/electron,miniak/electron,mirrh/electron,Jonekee/electron,faizalpribadi/electron,rprichard/electron,kcrt/electron,gerhardberger/electron,tylergibson/electron,MaxWhere/electron,dkfiresky/electron,Zagorakiss/electron,nagyistoce/electron-atom-shell,saronwei/electron,John-Lin/electron,thompsonemerson/electron,robinvandernoord/electron,stevemao/electron,JussMee15/electron,bbondy/electron,howmuchcomputer/electron,vHanda/electron,simonfork/electron,gbn972/electron,GoooIce/electron,aecca/electron,evgenyzinoviev/electron,kikong/electron,bpasero/electron,cos2004/electron,GoooIce/electron,LadyNaggaga/electron,electron/electron,jonatasfreitasv/electron,Neron-X5/electron,renaesop/electron,Floato/electron,biblerule/UMCTelnetHub,mubassirhayat/electron,dkfiresky/electron,dahal/electron,GoooIce/electron,jannishuebl/electron,John-Lin/electron,shaundunne/electron,simongregory/electron,mattdesl/electron,cos2004/electron,benweissmann/electron,edulan/electron,xfstudio/electron,nicobot/electron,preco21/electron,xiruibing/electron,deed02392/electron,MaxGraey/electron,ankitaggarwal011/electron,jaanus/electron,bobwol/electron,trankmichael/electron,fffej/electron,anko/electron,trigrass2/electron,jlhbaseball15/electron,tinydew4/electron,pombredanne/electron,sshiting/electron,natgolov/electron,farmisen/electron,neutrous/electron,wolfflow/electron,tincan24/electron,faizalpribadi/electron,thingsinjars/electron,subblue/electron,cqqccqc/electron,etiktin/electron,pirafrank/electron,subblue/electron,natgolov/electron,fomojola/electron,vaginessa/electron,seanchas116/electron,mhkeller/electron,electron/electron,MaxWhere/electron,maxogden/atom-shell,pombredanne/electron,eric-seekas/electron,mubassirhayat/electron,MaxGraey/electron,soulteary/electron,Neron-X5/electron,vaginessa/electron,jjz/electron,biblerule/UMCTelnetHub,gerhardberger/electron,nicholasess/electron,aecca/electron,eriser/electron,RobertJGabriel/electron,arusakov/electron,gerhardberger/electron,nagyistoce/electron-atom-shell,michaelchiche/electron,miniak/electron,twolfson/electron,DivyaKMenon/electron,aaron-goshine/electron,minggo/electron,benweissmann/electron,kazupon/electron,saronwei/electron,dkfiresky/electron,shiftkey/electron,kcrt/electron,mrwizard82d1/electron,destan/electron,noikiy/electron,dkfiresky/electron,simonfork/electron,brave/muon,destan/electron,oiledCode/electron,systembugtj/electron,JussMee15/electron,rreimann/electron,jannishuebl/electron,lrlna/electron,adcentury/electron,wolfflow/electron,Faiz7412/electron,shaundunne/electron,destan/electron,simongregory/electron,ankitaggarwal011/electron,meowlab/electron,gamedevsam/electron,jlhbaseball15/electron,baiwyc119/electron,fabien-d/electron,abhishekgahlot/electron,kcrt/electron,fomojola/electron,Neron-X5/electron,adamjgray/electron,cos2004/electron,bruce/electron,bobwol/electron,jtburke/electron,bwiggs/electron,brenca/electron,shiftkey/electron,joaomoreno/atom-shell,noikiy/electron,stevekinney/electron,leftstick/electron,electron/electron,thomsonreuters/electron,trankmichael/electron,lzpfmh/electron,jsutcodes/electron,the-ress/electron,edulan/electron,kenmozi/electron,greyhwndz/electron,gbn972/electron,synaptek/electron,mirrh/electron,electron/electron,SufianHassan/electron,shockone/electron,shiftkey/electron,Evercoder/electron,nekuz0r/electron,cqqccqc/electron,jhen0409/electron,trankmichael/electron,sky7sea/electron,setzer777/electron,thompsonemerson/electron,aichingm/electron,jhen0409/electron,sky7sea/electron,mjaniszew/electron,brenca/electron,Ivshti/electron,d-salas/electron,posix4e/electron,kazupon/electron,fabien-d/electron,simonfork/electron,shaundunne/electron,kikong/electron,deed02392/electron,Floato/electron,fffej/electron,tonyganch/electron,jcblw/electron,dahal/electron,mirrh/electron,matiasinsaurralde/electron,dahal/electron,d-salas/electron,brave/muon,jonatasfreitasv/electron,Rokt33r/electron,pirafrank/electron,the-ress/electron,rhencke/electron,kazupon/electron,adcentury/electron,tomashanacek/electron,micalan/electron,shiftkey/electron,thomsonreuters/electron,christian-bromann/electron,rsvip/electron,greyhwndz/electron,lrlna/electron,vaginessa/electron,iftekeriba/electron,fffej/electron,thingsinjars/electron,icattlecoder/electron,stevekinney/electron,JussMee15/electron,fireball-x/atom-shell,dongjoon-hyun/electron,dkfiresky/electron,tomashanacek/electron,dkfiresky/electron,gabriel/electron,lrlna/electron,sircharleswatson/electron,LadyNaggaga/electron,gbn972/electron,vHanda/electron,simongregory/electron,tomashanacek/electron,IonicaBizauKitchen/electron,lrlna/electron,abhishekgahlot/electron,nicobot/electron,pandoraui/electron,zhakui/electron,deepak1556/atom-shell,xfstudio/electron,bwiggs/electron,synaptek/electron,lzpfmh/electron,faizalpribadi/electron,oiledCode/electron,xfstudio/electron,darwin/electron,sshiting/electron,xfstudio/electron,baiwyc119/electron,jannishuebl/electron,bwiggs/electron,SufianHassan/electron,tylergibson/electron,bwiggs/electron,rreimann/electron,Zagorakiss/electron,shennushi/electron,JesselJohn/electron,christian-bromann/electron,simongregory/electron,bobwol/electron,aaron-goshine/electron,nekuz0r/electron,vipulroxx/electron,synaptek/electron,ianscrivener/electron,biblerule/UMCTelnetHub,sky7sea/electron,brenca/electron,gabrielPeart/electron,systembugtj/electron,hokein/atom-shell,saronwei/electron,JesselJohn/electron,adamjgray/electron,chriskdon/electron,icattlecoder/electron,deed02392/electron,mrwizard82d1/electron,fritx/electron,hokein/atom-shell,webmechanicx/electron,subblue/electron,renaesop/electron,gamedevsam/electron,bpasero/electron,bpasero/electron,Jacobichou/electron,smczk/electron,neutrous/electron,etiktin/electron,christian-bromann/electron,brave/electron,JussMee15/electron,tonyganch/electron,mubassirhayat/electron,John-Lin/electron,kazupon/electron,mjaniszew/electron,xfstudio/electron,rhencke/electron,jiaz/electron,brave/muon,Evercoder/electron,roadev/electron,IonicaBizauKitchen/electron,iftekeriba/electron,ankitaggarwal011/electron,yalexx/electron,nekuz0r/electron,beni55/electron,adamjgray/electron,coderhaoxin/electron,fabien-d/electron,neutrous/electron,yalexx/electron,tincan24/electron,jjz/electron,kokdemo/electron,medixdev/electron,voidbridge/electron,Jacobichou/electron,gstack/infinium-shell,Ivshti/electron,smczk/electron,sshiting/electron,fritx/electron,thomsonreuters/electron,dongjoon-hyun/electron,Faiz7412/electron,yan-foto/electron,deed02392/electron,baiwyc119/electron,pombredanne/electron,thomsonreuters/electron,Floato/electron,kostia/electron,bright-sparks/electron,lzpfmh/electron,ianscrivener/electron,mattotodd/electron,jtburke/electron,coderhaoxin/electron,webmechanicx/electron,fritx/electron,biblerule/UMCTelnetHub
099eb53d3c7a4be19fd79f11c9ccf52faff300d4
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e4b283c22236560fd289fe59c03e50adf39e7c4b' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'aa87035cc012ce0d533bb56b947bca81a6e71b82' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Upgrade libchromiumcontent to fix generating node.lib
Upgrade libchromiumcontent to fix generating node.lib
Python
mit
setzer777/electron,dkfiresky/electron,carsonmcdonald/electron,davazp/electron,michaelchiche/electron,gerhardberger/electron,systembugtj/electron,renaesop/electron,mirrh/electron,bbondy/electron,subblue/electron,Andrey-Pavlov/electron,joaomoreno/atom-shell,bpasero/electron,hokein/atom-shell,bpasero/electron,benweissmann/electron,iftekeriba/electron,neutrous/electron,gamedevsam/electron,Zagorakiss/electron,seanchas116/electron,jcblw/electron,arusakov/electron,aaron-goshine/electron,aecca/electron,tinydew4/electron,aecca/electron,gabriel/electron,benweissmann/electron,shockone/electron,lrlna/electron,shockone/electron,subblue/electron,dahal/electron,brave/electron,xfstudio/electron,matiasinsaurralde/electron,vaginessa/electron,wan-qy/electron,robinvandernoord/electron,smczk/electron,farmisen/electron,natgolov/electron,tonyganch/electron,cos2004/electron,pirafrank/electron,iftekeriba/electron,thompsonemerson/electron,bobwol/electron,ianscrivener/electron,ervinb/electron,digideskio/electron,noikiy/electron,lzpfmh/electron,dkfiresky/electron,aliib/electron,tomashanacek/electron,wolfflow/electron,joaomoreno/atom-shell,mjaniszew/electron,aichingm/electron,neutrous/electron,rsvip/electron,ervinb/electron,leolujuyi/electron,jsutcodes/electron,Faiz7412/electron,bobwol/electron,kokdemo/electron,sshiting/electron,oiledCode/electron,RobertJGabriel/electron,abhishekgahlot/electron,rhencke/electron,aichingm/electron,coderhaoxin/electron,baiwyc119/electron,Jonekee/electron,bright-sparks/electron,jhen0409/electron,eric-seekas/electron,rsvip/electron,beni55/electron,posix4e/electron,synaptek/electron,matiasinsaurralde/electron,minggo/electron,medixdev/electron,vHanda/electron,renaesop/electron,chriskdon/electron,neutrous/electron,brave/electron,chrisswk/electron,fritx/electron,christian-bromann/electron,tylergibson/electron,adcentury/electron,brenca/electron,DivyaKMenon/electron,aaron-goshine/electron,kenmozi/electron,rajatsingla28/electron,electron/electron,deepak1556/atom-shell,mattdesl/electron,leolujuyi/electron,zhakui/electron,mirrh/electron,kazupon/electron,tincan24/electron,Floato/electron,miniak/electron,deed02392/electron,bwiggs/electron,destan/electron,mjaniszew/electron,rajatsingla28/electron,edulan/electron,jsutcodes/electron,egoist/electron,ianscrivener/electron,electron/electron,shiftkey/electron,timruffles/electron,jacksondc/electron,michaelchiche/electron,gabriel/electron,webmechanicx/electron,thingsinjars/electron,davazp/electron,nekuz0r/electron,jtburke/electron,kenmozi/electron,leolujuyi/electron,stevemao/electron,LadyNaggaga/electron,kcrt/electron,cos2004/electron,simongregory/electron,anko/electron,synaptek/electron,adcentury/electron,jlord/electron,MaxWhere/electron,bruce/electron,bpasero/electron,MaxWhere/electron,greyhwndz/electron,JussMee15/electron,stevemao/electron,kcrt/electron,chriskdon/electron,rsvip/electron,arturts/electron,leethomas/electron,voidbridge/electron,wolfflow/electron,Faiz7412/electron,joaomoreno/atom-shell,cqqccqc/electron,stevekinney/electron,roadev/electron,jiaz/electron,shaundunne/electron,jcblw/electron,gerhardberger/electron,jtburke/electron,yalexx/electron,Jacobichou/electron,baiwyc119/electron,Rokt33r/electron,roadev/electron,arusakov/electron,Rokt33r/electron,kazupon/electron,yalexx/electron,gabrielPeart/electron,eric-seekas/electron,oiledCode/electron,jtburke/electron,vaginessa/electron,Rokt33r/electron,jannishuebl/electron,rreimann/electron,greyhwndz/electron,saronwei/electron,arusakov/electron,trigrass2/electron,aecca/electron,ankitaggarwal011/electron,benweissmann/electron,dkfiresky/electron,gabrielPeart/electron,jannishuebl/electron,Faiz7412/electron,Gerhut/electron,simonfork/electron,tonyganch/electron,aichingm/electron,cqqccqc/electron,carsonmcdonald/electron,LadyNaggaga/electron,trankmichael/electron,anko/electron,micalan/electron,the-ress/electron,coderhaoxin/electron,dahal/electron,wolfflow/electron,bitemyapp/electron,michaelchiche/electron,simongregory/electron,shockone/electron,gabrielPeart/electron,rajatsingla28/electron,farmisen/electron,d-salas/electron,joaomoreno/atom-shell,jonatasfreitasv/electron,jhen0409/electron,aichingm/electron,mhkeller/electron,wan-qy/electron,subblue/electron,lzpfmh/electron,stevekinney/electron,gamedevsam/electron,arturts/electron,SufianHassan/electron,eriser/electron,setzer777/electron,smczk/electron,mattdesl/electron,wolfflow/electron,egoist/electron,simongregory/electron,tylergibson/electron,nicobot/electron,tinydew4/electron,kcrt/electron,deed02392/electron,chrisswk/electron,takashi/electron,GoooIce/electron,kazupon/electron,natgolov/electron,trigrass2/electron,renaesop/electron,SufianHassan/electron,darwin/electron,twolfson/electron,tylergibson/electron,egoist/electron,fffej/electron,jjz/electron,jaanus/electron,jjz/electron,nicobot/electron,jacksondc/electron,tincan24/electron,Evercoder/electron,simonfork/electron,rsvip/electron,adamjgray/electron,Ivshti/electron,posix4e/electron,thomsonreuters/electron,felixrieseberg/electron,simongregory/electron,d-salas/electron,brave/muon,ervinb/electron,aliib/electron,mubassirhayat/electron,trigrass2/electron,coderhaoxin/electron,kenmozi/electron,webmechanicx/electron,aaron-goshine/electron,smczk/electron,trankmichael/electron,lrlna/electron,kcrt/electron,sircharleswatson/electron,felixrieseberg/electron,xiruibing/electron,sircharleswatson/electron,stevemao/electron,minggo/electron,brenca/electron,tinydew4/electron,kikong/electron,joaomoreno/atom-shell,nekuz0r/electron,RobertJGabriel/electron,beni55/electron,gamedevsam/electron,nicholasess/electron,tinydew4/electron,yan-foto/electron,shaundunne/electron,tomashanacek/electron,tincan24/electron,nicholasess/electron,christian-bromann/electron,jcblw/electron,natgolov/electron,eric-seekas/electron,DivyaKMenon/electron,Rokt33r/electron,biblerule/UMCTelnetHub,miniak/electron,matiasinsaurralde/electron,rajatsingla28/electron,gabrielPeart/electron,bbondy/electron,yalexx/electron,deepak1556/atom-shell,digideskio/electron,takashi/electron,shaundunne/electron,digideskio/electron,trigrass2/electron,mubassirhayat/electron,egoist/electron,bobwol/electron,kostia/electron,bitemyapp/electron,pirafrank/electron,jaanus/electron,medixdev/electron,IonicaBizauKitchen/electron,fomojola/electron,IonicaBizauKitchen/electron,lrlna/electron,deed02392/electron,electron/electron,pombredanne/electron,mhkeller/electron,fritx/electron,chriskdon/electron,Neron-X5/electron,darwin/electron,xfstudio/electron,MaxWhere/electron,RIAEvangelist/electron,fffej/electron,Floato/electron,takashi/electron,thingsinjars/electron,mattdesl/electron,joneit/electron,rreimann/electron,noikiy/electron,matiasinsaurralde/electron,brave/muon,baiwyc119/electron,icattlecoder/electron,bruce/electron,mrwizard82d1/electron,medixdev/electron,greyhwndz/electron,evgenyzinoviev/electron,MaxGraey/electron,nekuz0r/electron,iftekeriba/electron,minggo/electron,John-Lin/electron,edulan/electron,d-salas/electron,Ivshti/electron,trankmichael/electron,deepak1556/atom-shell,leftstick/electron,abhishekgahlot/electron,evgenyzinoviev/electron,the-ress/electron,timruffles/electron,thomsonreuters/electron,icattlecoder/electron,kenmozi/electron,kostia/electron,robinvandernoord/electron,Ivshti/electron,brave/muon,etiktin/electron,BionicClick/electron,RobertJGabriel/electron,leethomas/electron,icattlecoder/electron,gabriel/electron,pandoraui/electron,kenmozi/electron,maxogden/atom-shell,voidbridge/electron,RobertJGabriel/electron,xiruibing/electron,IonicaBizauKitchen/electron,subblue/electron,gstack/infinium-shell,chrisswk/electron,noikiy/electron,vHanda/electron,webmechanicx/electron,saronwei/electron,brave/electron,noikiy/electron,brenca/electron,arusakov/electron,yan-foto/electron,kostia/electron,Zagorakiss/electron,John-Lin/electron,yalexx/electron,biblerule/UMCTelnetHub,Neron-X5/electron,jhen0409/electron,carsonmcdonald/electron,bpasero/electron,tylergibson/electron,miniak/electron,stevemao/electron,xiruibing/electron,dongjoon-hyun/electron,zhakui/electron,aichingm/electron,chriskdon/electron,noikiy/electron,thingsinjars/electron,christian-bromann/electron,ankitaggarwal011/electron,preco21/electron,darwin/electron,fomojola/electron,shockone/electron,jlhbaseball15/electron,beni55/electron,oiledCode/electron,mjaniszew/electron,baiwyc119/electron,micalan/electron,simonfork/electron,leftstick/electron,greyhwndz/electron,fffej/electron,tonyganch/electron,soulteary/electron,howmuchcomputer/electron,darwin/electron,DivyaKMenon/electron,mjaniszew/electron,leethomas/electron,etiktin/electron,leethomas/electron,mrwizard82d1/electron,adamjgray/electron,roadev/electron,neutrous/electron,thompsonemerson/electron,GoooIce/electron,jannishuebl/electron,mubassirhayat/electron,robinvandernoord/electron,Andrey-Pavlov/electron,bwiggs/electron,medixdev/electron,synaptek/electron,yan-foto/electron,neutrous/electron,howmuchcomputer/electron,nagyistoce/electron-atom-shell,vaginessa/electron,fffej/electron,saronwei/electron,christian-bromann/electron,miniak/electron,tinydew4/electron,BionicClick/electron,iftekeriba/electron,astoilkov/electron,bright-sparks/electron,preco21/electron,RIAEvangelist/electron,vHanda/electron,bright-sparks/electron,the-ress/electron,lzpfmh/electron,synaptek/electron,kikong/electron,pandoraui/electron,yalexx/electron,sky7sea/electron,jsutcodes/electron,rhencke/electron,jlhbaseball15/electron,stevekinney/electron,Neron-X5/electron,RIAEvangelist/electron,Neron-X5/electron,adcentury/electron,preco21/electron,IonicaBizauKitchen/electron,rajatsingla28/electron,vHanda/electron,xfstudio/electron,wan-qy/electron,pirafrank/electron,wan-qy/electron,vipulroxx/electron,John-Lin/electron,egoist/electron,abhishekgahlot/electron,Andrey-Pavlov/electron,DivyaKMenon/electron,nicholasess/electron,maxogden/atom-shell,adamjgray/electron,coderhaoxin/electron,gstack/infinium-shell,simonfork/electron,brave/muon,setzer777/electron,edulan/electron,thomsonreuters/electron,jaanus/electron,astoilkov/electron,pandoraui/electron,gerhardberger/electron,thompsonemerson/electron,electron/electron,meowlab/electron,tonyganch/electron,LadyNaggaga/electron,howmuchcomputer/electron,leolujuyi/electron,gbn972/electron,nekuz0r/electron,posix4e/electron,Jonekee/electron,gbn972/electron,jhen0409/electron,arturts/electron,anko/electron,IonicaBizauKitchen/electron,benweissmann/electron,synaptek/electron,nicobot/electron,Floato/electron,mattotodd/electron,fomojola/electron,dongjoon-hyun/electron,gstack/infinium-shell,minggo/electron,bright-sparks/electron,meowlab/electron,roadev/electron,jiaz/electron,MaxGraey/electron,systembugtj/electron,wan-qy/electron,soulteary/electron,Floato/electron,RIAEvangelist/electron,benweissmann/electron,bbondy/electron,miniak/electron,destan/electron,coderhaoxin/electron,gbn972/electron,bruce/electron,nekuz0r/electron,aichingm/electron,renaesop/electron,gabriel/electron,jaanus/electron,trigrass2/electron,meowlab/electron,thomsonreuters/electron,michaelchiche/electron,rsvip/electron,sircharleswatson/electron,saronwei/electron,gamedevsam/electron,Gerhut/electron,nagyistoce/electron-atom-shell,tincan24/electron,meowlab/electron,jonatasfreitasv/electron,jlord/electron,renaesop/electron,hokein/atom-shell,preco21/electron,jiaz/electron,carsonmcdonald/electron,bitemyapp/electron,wolfflow/electron,adamjgray/electron,fomojola/electron,mirrh/electron,jtburke/electron,trankmichael/electron,shennushi/electron,jhen0409/electron,sircharleswatson/electron,sky7sea/electron,evgenyzinoviev/electron,jacksondc/electron,simongregory/electron,adamjgray/electron,twolfson/electron,bobwol/electron,tinydew4/electron,biblerule/UMCTelnetHub,eric-seekas/electron,micalan/electron,ankitaggarwal011/electron,farmisen/electron,dongjoon-hyun/electron,hokein/atom-shell,jonatasfreitasv/electron,destan/electron,Andrey-Pavlov/electron,xfstudio/electron,aliib/electron,kikong/electron,Zagorakiss/electron,ervinb/electron,astoilkov/electron,LadyNaggaga/electron,stevemao/electron,John-Lin/electron,thomsonreuters/electron,fomojola/electron,mirrh/electron,howmuchcomputer/electron,maxogden/atom-shell,faizalpribadi/electron,shaundunne/electron,vipulroxx/electron,baiwyc119/electron,meowlab/electron,takashi/electron,davazp/electron,SufianHassan/electron,Gerhut/electron,cos2004/electron,joneit/electron,vaginessa/electron,kazupon/electron,thompsonemerson/electron,mrwizard82d1/electron,robinvandernoord/electron,bbondy/electron,jsutcodes/electron,etiktin/electron,vHanda/electron,fomojola/electron,natgolov/electron,fabien-d/electron,aecca/electron,timruffles/electron,jtburke/electron,gabrielPeart/electron,shiftkey/electron,jiaz/electron,oiledCode/electron,astoilkov/electron,Rokt33r/electron,lzpfmh/electron,fireball-x/atom-shell,Evercoder/electron,shockone/electron,arturts/electron,greyhwndz/electron,LadyNaggaga/electron,Neron-X5/electron,sircharleswatson/electron,deepak1556/atom-shell,beni55/electron,preco21/electron,evgenyzinoviev/electron,Jacobichou/electron,eriser/electron,digideskio/electron,jlhbaseball15/electron,mattotodd/electron,dongjoon-hyun/electron,jhen0409/electron,stevekinney/electron,mubassirhayat/electron,anko/electron,arusakov/electron,gbn972/electron,shockone/electron,kazupon/electron,webmechanicx/electron,bwiggs/electron,chrisswk/electron,beni55/electron,electron/electron,sircharleswatson/electron,tomashanacek/electron,kcrt/electron,bitemyapp/electron,biblerule/UMCTelnetHub,nagyistoce/electron-atom-shell,nagyistoce/electron-atom-shell,tomashanacek/electron,sky7sea/electron,kokdemo/electron,thompsonemerson/electron,twolfson/electron,soulteary/electron,rreimann/electron,joneit/electron,astoilkov/electron,Faiz7412/electron,hokein/atom-shell,vipulroxx/electron,jlord/electron,jlhbaseball15/electron,egoist/electron,kcrt/electron,coderhaoxin/electron,sshiting/electron,gabriel/electron,christian-bromann/electron,rhencke/electron,mjaniszew/electron,adcentury/electron,nicholasess/electron,pirafrank/electron,SufianHassan/electron,jjz/electron,mhkeller/electron,arturts/electron,gbn972/electron,mhkeller/electron,meowlab/electron,JussMee15/electron,seanchas116/electron,micalan/electron,LadyNaggaga/electron,tincan24/electron,voidbridge/electron,sky7sea/electron,fabien-d/electron,MaxWhere/electron,JesselJohn/electron,gbn972/electron,smczk/electron,abhishekgahlot/electron,kostia/electron,shaundunne/electron,Evercoder/electron,etiktin/electron,iftekeriba/electron,voidbridge/electron,oiledCode/electron,brenca/electron,miniak/electron,JesselJohn/electron,vipulroxx/electron,lrlna/electron,destan/electron,mattotodd/electron,bruce/electron,systembugtj/electron,howmuchcomputer/electron,biblerule/UMCTelnetHub,deed02392/electron,felixrieseberg/electron,Evercoder/electron,aecca/electron,Gerhut/electron,jsutcodes/electron,brenca/electron,lrlna/electron,eric-seekas/electron,RobertJGabriel/electron,ervinb/electron,BionicClick/electron,bbondy/electron,shennushi/electron,vaginessa/electron,evgenyzinoviev/electron,MaxGraey/electron,vaginessa/electron,felixrieseberg/electron,brave/electron,soulteary/electron,d-salas/electron,rhencke/electron,bitemyapp/electron,ianscrivener/electron,nagyistoce/electron-atom-shell,brave/muon,kokdemo/electron,systembugtj/electron,farmisen/electron,jaanus/electron,kikong/electron,shiftkey/electron,roadev/electron,hokein/atom-shell,mattdesl/electron,leethomas/electron,MaxGraey/electron,felixrieseberg/electron,dongjoon-hyun/electron,cqqccqc/electron,bobwol/electron,the-ress/electron,Andrey-Pavlov/electron,bwiggs/electron,takashi/electron,electron/electron,systembugtj/electron,thingsinjars/electron,jsutcodes/electron,JussMee15/electron,brave/electron,chriskdon/electron,Evercoder/electron,robinvandernoord/electron,simonfork/electron,gerhardberger/electron,webmechanicx/electron,jannishuebl/electron,destan/electron,jlhbaseball15/electron,ianscrivener/electron,mirrh/electron,pombredanne/electron,faizalpribadi/electron,tomashanacek/electron,beni55/electron,xfstudio/electron,Gerhut/electron,Gerhut/electron,nicholasess/electron,vipulroxx/electron,Jonekee/electron,timruffles/electron,bbondy/electron,edulan/electron,rreimann/electron,synaptek/electron,fabien-d/electron,tincan24/electron,medixdev/electron,farmisen/electron,neutrous/electron,JesselJohn/electron,joneit/electron,chriskdon/electron,gabrielPeart/electron,Jonekee/electron,shiftkey/electron,faizalpribadi/electron,jjz/electron,digideskio/electron,the-ress/electron,dongjoon-hyun/electron,ankitaggarwal011/electron,gerhardberger/electron,deed02392/electron,christian-bromann/electron,lzpfmh/electron,pombredanne/electron,faizalpribadi/electron,davazp/electron,shennushi/electron,electron/electron,jcblw/electron,jacksondc/electron,nicobot/electron,John-Lin/electron,timruffles/electron,jannishuebl/electron,medixdev/electron,deed02392/electron,smczk/electron,destan/electron,posix4e/electron,aaron-goshine/electron,yan-foto/electron,bwiggs/electron,Zagorakiss/electron,vHanda/electron,Faiz7412/electron,noikiy/electron,darwin/electron,bitemyapp/electron,jjz/electron,ankitaggarwal011/electron,icattlecoder/electron,oiledCode/electron,shennushi/electron,pombredanne/electron,mhkeller/electron,ankitaggarwal011/electron,IonicaBizauKitchen/electron,webmechanicx/electron,JesselJohn/electron,gstack/infinium-shell,Rokt33r/electron,bpasero/electron,brave/muon,seanchas116/electron,dahal/electron,JussMee15/electron,adamjgray/electron,RIAEvangelist/electron,rhencke/electron,shennushi/electron,fabien-d/electron,sshiting/electron,baiwyc119/electron,pandoraui/electron,xiruibing/electron,kostia/electron,d-salas/electron,posix4e/electron,carsonmcdonald/electron,dahal/electron,soulteary/electron,JussMee15/electron,nicobot/electron,pombredanne/electron,maxogden/atom-shell,jonatasfreitasv/electron,leftstick/electron,cqqccqc/electron,kokdemo/electron,Neron-X5/electron,rajatsingla28/electron,vipulroxx/electron,systembugtj/electron,leolujuyi/electron,jlhbaseball15/electron,thomsonreuters/electron,bruce/electron,lzpfmh/electron,Ivshti/electron,fffej/electron,jlord/electron,SufianHassan/electron,shaundunne/electron,BionicClick/electron,davazp/electron,mattotodd/electron,setzer777/electron,trigrass2/electron,fritx/electron,gamedevsam/electron,SufianHassan/electron,mrwizard82d1/electron,simongregory/electron,xiruibing/electron,thingsinjars/electron,Jacobichou/electron,Jonekee/electron,dahal/electron,abhishekgahlot/electron,aliib/electron,fireball-x/atom-shell,seanchas116/electron,fritx/electron,cos2004/electron,howmuchcomputer/electron,biblerule/UMCTelnetHub,setzer777/electron,fritx/electron,Zagorakiss/electron,davazp/electron,bruce/electron,leethomas/electron,minggo/electron,jiaz/electron,jlord/electron,nicholasess/electron,subblue/electron,wan-qy/electron,rhencke/electron,jacksondc/electron,sshiting/electron,ervinb/electron,digideskio/electron,mattotodd/electron,jiaz/electron,arturts/electron,Jacobichou/electron,tonyganch/electron,trankmichael/electron,renaesop/electron,leolujuyi/electron,bpasero/electron,gabriel/electron,xiruibing/electron,evgenyzinoviev/electron,kokdemo/electron,rreimann/electron,bobwol/electron,twolfson/electron,bright-sparks/electron,ianscrivener/electron,jcblw/electron,benweissmann/electron,DivyaKMenon/electron,etiktin/electron,fabien-d/electron,mirrh/electron,GoooIce/electron,aliib/electron,yalexx/electron,pandoraui/electron,wolfflow/electron,fireball-x/atom-shell,kikong/electron,brave/electron,BionicClick/electron,thompsonemerson/electron,mattotodd/electron,Floato/electron,dkfiresky/electron,farmisen/electron,dahal/electron,seanchas116/electron,fffej/electron,anko/electron,cqqccqc/electron,joneit/electron,robinvandernoord/electron,BionicClick/electron,tonyganch/electron,anko/electron,Zagorakiss/electron,stevekinney/electron,lrlna/electron,matiasinsaurralde/electron,jonatasfreitasv/electron,faizalpribadi/electron,aaron-goshine/electron,deepak1556/atom-shell,stevemao/electron,zhakui/electron,sky7sea/electron,Jonekee/electron,greyhwndz/electron,Andrey-Pavlov/electron,leftstick/electron,yan-foto/electron,roadev/electron,chrisswk/electron,stevekinney/electron,MaxWhere/electron,eriser/electron,gerhardberger/electron,cos2004/electron,natgolov/electron,kokdemo/electron,bright-sparks/electron,fireball-x/atom-shell,fireball-x/atom-shell,GoooIce/electron,carsonmcdonald/electron,icattlecoder/electron,DivyaKMenon/electron,faizalpribadi/electron,maxogden/atom-shell,the-ress/electron,pirafrank/electron,adcentury/electron,bwiggs/electron,aaron-goshine/electron,fritx/electron,micalan/electron,abhishekgahlot/electron,edulan/electron,gamedevsam/electron,shiftkey/electron,eriser/electron,Jacobichou/electron,jannishuebl/electron,matiasinsaurralde/electron,astoilkov/electron,trankmichael/electron,kazupon/electron,joaomoreno/atom-shell,sshiting/electron,nekuz0r/electron,sky7sea/electron,ianscrivener/electron,pirafrank/electron,michaelchiche/electron,leftstick/electron,michaelchiche/electron,mattdesl/electron,yan-foto/electron,shiftkey/electron,shennushi/electron,dkfiresky/electron,minggo/electron,voidbridge/electron,jjz/electron,takashi/electron,mrwizard82d1/electron,Ivshti/electron,voidbridge/electron,tomashanacek/electron,mhkeller/electron,etiktin/electron,d-salas/electron,eric-seekas/electron,dkfiresky/electron,nicobot/electron,arusakov/electron,posix4e/electron,cqqccqc/electron,zhakui/electron,rreimann/electron,JesselJohn/electron,saronwei/electron,adcentury/electron,aecca/electron,gstack/infinium-shell,eriser/electron,simonfork/electron,tylergibson/electron,iftekeriba/electron,twolfson/electron,mrwizard82d1/electron,RobertJGabriel/electron,tylergibson/electron,John-Lin/electron,seanchas116/electron,subblue/electron,xfstudio/electron,JesselJohn/electron,brenca/electron,Evercoder/electron,preco21/electron,felixrieseberg/electron,twolfson/electron,sshiting/electron,natgolov/electron,bpasero/electron,mattdesl/electron,JussMee15/electron,GoooIce/electron,aliib/electron,icattlecoder/electron,kostia/electron,MaxWhere/electron,zhakui/electron,edulan/electron,Jacobichou/electron,joneit/electron,pandoraui/electron,jaanus/electron,jonatasfreitasv/electron,gerhardberger/electron,cos2004/electron,thingsinjars/electron,the-ress/electron,jcblw/electron,kenmozi/electron,mubassirhayat/electron,eriser/electron,micalan/electron,jacksondc/electron,setzer777/electron,GoooIce/electron,smczk/electron,leftstick/electron,RIAEvangelist/electron,Floato/electron,soulteary/electron,mjaniszew/electron,jtburke/electron,pombredanne/electron,MaxGraey/electron,saronwei/electron,zhakui/electron
3a78496f350c904ce64d30f422dfae8b6bc879c3
flask_api/tests/runtests.py
flask_api/tests/runtests.py
import unittest import sys import subprocess if __name__ == '__main__': if len(sys.argv) > 1: unittest.main(module='flask_api.tests') else: subprocess.call([sys.executable, '-m', 'unittest', 'discover'])
import unittest if __name__ == '__main__': unittest.main(module='flask_api.tests')
Simplify test execution to restore coverage measurement
Simplify test execution to restore coverage measurement
Python
bsd-2-clause
theskumar-archive/flask-api,theskumar-archive/flask-api,theskumar-archive/flask-api,theskumar-archive/flask-api
dcb8add6685dfb7dff626742b17ce03e013e72a1
src/enrich/kucera_francis_enricher.py
src/enrich/kucera_francis_enricher.py
__author__ = 's7a' # All imports from extras import KuceraFrancis from resource import Resource from os import path # The Kucera Francis enrichment class class KuceraFrancisEnricher: # Constructor for the Kucera Francis Enricher def __init__(self): self.kf = KuceraFrancis(path.join('data', 'kucera_francis.csv')) # Enrich the word def enrich_word(self, word): if self.kf.frequency(word) == 0: return Resource.link(word) return word
__author__ = 's7a' # All imports from extras import StemmedKuceraFrancis from resource import Resource from os import path # The Kucera Francis enrichment class class KuceraFrancisEnricher: # Constructor for the Kucera Francis Enricher def __init__(self): self.kf = StemmedKuceraFrancis(path.join('data', 'kucera_francis.csv')) # Enrich the word def enrich_word(self, word): if self.kf.frequency(word) == 0: return Resource.link(word) return word
Use stemmed Kucera Francis for Enrichment
Use stemmed Kucera Francis for Enrichment
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
d57844d1d6b2172fe196db4945517a5b3a68d343
satchless/process/__init__.py
satchless/process/__init__.py
class InvalidData(Exception): """ Raised for by step validation process """ pass class Step(object): """ A single step in a multistep process """ def validate(self): raise NotImplementedError() # pragma: no cover class ProcessManager(object): """ A multistep process handler """ def validate_step(self, step): try: step.validate() except InvalidData: return False return True def get_next_step(self): for step in self: if not self.validate_step(step): return step def get_errors(self): errors = {} for step in self: try: step.validate() except InvalidData as error: errors[str(step)] = error return errors def is_complete(self): return not self.get_next_step() def __getitem__(self, step_id): for step in self: if str(step) == step_id: return step raise KeyError('%r is not a valid step' % (step_id,))
class InvalidData(Exception): """ Raised for by step validation process """ pass class Step(object): """ A single step in a multistep process """ def validate(self): raise NotImplementedError() # pragma: no cover class ProcessManager(object): """ A multistep process handler """ def validate_step(self, step): try: step.validate() except InvalidData: return False return True def get_next_step(self): for step in self: if not self.validate_step(step): return step def get_errors(self): errors = {} for step in self: try: step.validate() except InvalidData as error: errors[str(step)] = error return errors def is_complete(self): return self.get_next_step() is None def __getitem__(self, step_id): for step in self: if str(step) == step_id: return step raise KeyError('%r is not a valid step' % (step_id,))
Check explicit that next step is None
Check explicit that next step is None
Python
bsd-3-clause
taedori81/satchless
221a84d52e5165013a5c7eb0b00c3ebcae294c8a
dashboard_app/extension.py
dashboard_app/extension.py
from lava_server.extension import LavaServerExtension class DashboardExtension(LavaServerExtension): @property def app_name(self): return "dashboard_app" @property def name(self): return "Dashboard" @property def main_view_name(self): return "dashboard_app.views.bundle_stream_list" @property def description(self): return "Validation Dashboard" @property def version(self): import versiontools import dashboard_app return versiontools.format_version(dashboard_app.__version__) def contribute_to_settings(self, settings): super(DashboardExtension, self).contribute_to_settings(settings) settings['INSTALLED_APPS'].extend([ "linaro_django_pagination", "south", ]) settings['MIDDLEWARE_CLASSES'].append( 'linaro_django_pagination.middleware.PaginationMiddleware') settings['RESTRUCTUREDTEXT_FILTER_SETTINGS'] = { "initial_header_level": 4} # TODO: Add dataview database support
from lava_server.extension import LavaServerExtension class DashboardExtension(LavaServerExtension): @property def app_name(self): return "dashboard_app" @property def name(self): return "Dashboard" @property def main_view_name(self): return "dashboard_app.views.bundle_stream_list" @property def description(self): return "Validation Dashboard" @property def version(self): import versiontools import dashboard_app return versiontools.format_version(dashboard_app.__version__) def contribute_to_settings(self, settings): super(DashboardExtension, self).contribute_to_settings(settings) settings['INSTALLED_APPS'].extend([ "linaro_django_pagination", "south", ]) settings['MIDDLEWARE_CLASSES'].append( 'linaro_django_pagination.middleware.PaginationMiddleware') settings['RESTRUCTUREDTEXT_FILTER_SETTINGS'] = { "initial_header_level": 4} def contribute_to_settings_ex(self, settings_module, settings_object): settings_module['DATAVIEW_DIRS'] = settings_object._settings.get( "DATAVIEW_DIRS", []) settings_module['DATAREPORT_DIRS'] = settings_object._settings.get( "DATAREPORT_DIRS", [])
Add support for configuring data views and reports
Add support for configuring data views and reports
Python
agpl-3.0
Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server
0003ee31f78d7861713a2bb7daacb9701b26a1b9
cinder/wsgi/wsgi.py
cinder/wsgi/wsgi.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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. """Cinder OS API WSGI application.""" import sys import warnings from cinder import objects warnings.simplefilter('once', DeprecationWarning) from oslo_config import cfg from oslo_log import log as logging from oslo_service import wsgi from cinder import i18n i18n.enable_lazy() # Need to register global_opts from cinder.common import config from cinder import rpc from cinder import version CONF = cfg.CONF def initialize_application(): objects.register_all() CONF(sys.argv[1:], project='cinder', version=version.version_string()) logging.setup(CONF, "cinder") config.set_middleware_defaults() rpc.init(CONF) return wsgi.Loader(CONF).load_app(name='osapi_volume')
# 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. """Cinder OS API WSGI application.""" import sys import warnings from cinder import objects warnings.simplefilter('once', DeprecationWarning) from oslo_config import cfg from oslo_log import log as logging from oslo_service import wsgi from cinder import i18n i18n.enable_lazy() # Need to register global_opts from cinder.common import config from cinder.common import constants from cinder import rpc from cinder import service from cinder import version CONF = cfg.CONF def initialize_application(): objects.register_all() CONF(sys.argv[1:], project='cinder', version=version.version_string()) logging.setup(CONF, "cinder") config.set_middleware_defaults() rpc.init(CONF) service.setup_profiler(constants.API_BINARY, CONF.host) return wsgi.Loader(CONF).load_app(name='osapi_volume')
Initialize osprofiler in WSGI application
Initialize osprofiler in WSGI application This patch adds missing initialization of OSProfiler when Cinder API is running as WSGI application. Change-Id: Ifaffa2d58eeadf5d47fafbdde5538d26bcd346a6
Python
apache-2.0
Datera/cinder,phenoxim/cinder,mahak/cinder,openstack/cinder,j-griffith/cinder,Datera/cinder,j-griffith/cinder,mahak/cinder,openstack/cinder,phenoxim/cinder
ef50e82c3c1f49d63d013ac538d932d40c430a46
pyradiator/endpoint.py
pyradiator/endpoint.py
import queue import threading class Producer(object): def __init__(self, period_in_seconds, queue, function): self._period_in_seconds = period_in_seconds self._queue = queue self._function = function self._event = threading.Event() self._thread = threading.Thread(target=self._loop) def start(self): self._thread.start() def stop(self): self._event.set() self._thread.join() def _loop(self): while not self._event.wait(self._period_in_seconds): self.__put_item_into_the_queue() def __put_item_into_the_queue(self): try: self._queue.put(self._function) except queue.Full: pass class Consumer(object): STOP_SENTINEL = "STOP" def __init__(self, queue, function): self._queue = queue self._function = function self._thread = threading.Thread(target=self._loop) self.no_date_from_the_queue = True def start(self): self._thread.start() def stop(self): self._queue.put(self.STOP_SENTINEL) self._thread.join() def _loop(self): for result in iter(self._queue.get, self.STOP_SENTINEL): self.no_date_from_the_queue = result is None if result: self._function(result)
try: import queue except ImportError: import Queue import threading class Producer(object): def __init__(self, period_in_seconds, queue, function): self._period_in_seconds = period_in_seconds self._queue = queue self._function = function self._event = threading.Event() self._thread = threading.Thread(target=self._loop) def start(self): self._thread.start() def stop(self): self._event.set() self._thread.join() def _loop(self): while not self._event.wait(self._period_in_seconds): self.__put_item_into_the_queue() def __put_item_into_the_queue(self): try: self._queue.put(self._function) except queue.Full: pass class Consumer(object): STOP_SENTINEL = "STOP" def __init__(self, queue, function): self._queue = queue self._function = function self._thread = threading.Thread(target=self._loop) self.no_date_from_the_queue = True def start(self): self._thread.start() def stop(self): self._queue.put(self.STOP_SENTINEL) self._thread.join() def _loop(self): for result in iter(self._queue.get, self.STOP_SENTINEL): self.no_date_from_the_queue = result is None if result: self._function(result)
Handle import error on older python versions
Handle import error on older python versions
Python
mit
crashmaster/pyradiator
511a133599b86deae83d9ad8a3f7a7c5c45e07bf
core/views.py
core/views.py
from django.shortcuts import render from django.http import Http404 from django.contrib.messages import success from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .models import HomePage, StaticPage from category.models import Category from .forms import ContactForm def home_page(request, slug="home-page"): home_page = HomePage.objects.get(slug=slug) return render(request, "core/home_page.html", { "page": home_page, "categories": Category.objects.all()[:9] }) def static_page(request, slug=None): try: page = Page.objects.get(slug=slug) except Page.DoesNotExist: raise Http404 if page.specific_class == HomePage: return home_page(request, page.slug) return render(request, "core/static_page.html", { "self": page.specific }) def contribute(request, slug=None): page = StaticPage.objects.get(slug=slug) return render(request, "core/contribute.html", { "self": page }) def contact_us(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() success(request, _("Your query has successfully been sent")) else: form = ContactForm() return render(request, "core/contact_us.html", { "contact_form": form })
from django.shortcuts import render from django.http import Http404 from django.contrib.messages import success from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .models import HomePage, StaticPage from category.models import Category from .forms import ContactForm def home_page(request, slug="home-page"): home_page = HomePage.objects.get(slug=slug) return render(request, "core/home_page.html", { "page": home_page, "categories": Category.objects.all()[:9] }) def static_page(request, slug=None): try: page = Page.objects.get(slug=slug) except Page.DoesNotExist: raise Http404 if page.specific_class == HomePage: return home_page(request, page.slug) return render(request, "core/static_page.html", { "self": page.specific }) def contribute(request, slug=None): page = StaticPage.objects.get(slug=slug) return render(request, "core/contribute.html", { "self": page }) def contact_us(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() success(request, _("Your query has successfully been sent")) form = ContactForm() else: form = ContactForm() return render(request, "core/contact_us.html", { "contact_form": form })
Clear the contact form after it has been successfully posted.
Clear the contact form after it has been successfully posted.
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
7cb68f6a749a38fef9820004a857e301c12a3044
morenines/util.py
morenines/util.py
import os import hashlib from fnmatch import fnmatchcase def get_files(index): paths = [] for dirpath, dirnames, filenames in os.walk(index.headers['root_path']): # Remove ignored directories dirnames = [d for d in dirnames if not index.ignores.match(d)] for filename in (f for f in filenames if not index.ignores.match(f)): # We want the path of the file, not its name path = os.path.join(dirpath, filename) # That path must be relative to the root, not absolute path = os.path.relpath(path, index.headers['root_path']) paths.append(path) return paths def get_ignores(ignores_path): with open(ignores_path, 'r') as ignores_file: ignores = [line.strip() for line in ignores_file] return ignores def get_hash(path): h = hashlib.sha1() with open(path, 'rb') as f: h.update(f.read()) return h.hexdigest() def get_new_and_missing(index): current_files = get_files(index) new_files = [path for path in current_files if path not in index.files] missing_files = [path for path in index.files.iterkeys() if path not in current_files] return new_files, missing_files
import os import hashlib def get_files(index): paths = [] for dirpath, dirnames, filenames in os.walk(index.headers['root_path']): # Remove ignored directories dirnames[:] = [d for d in dirnames if not index.ignores.match(d)] for filename in (f for f in filenames if not index.ignores.match(f)): # We want the path of the file, not its name path = os.path.join(dirpath, filename) # That path must be relative to the root, not absolute path = os.path.relpath(path, index.headers['root_path']) paths.append(path) return paths def get_ignores(ignores_path): with open(ignores_path, 'r') as ignores_file: ignores = [line.strip() for line in ignores_file] return ignores def get_hash(path): h = hashlib.sha1() with open(path, 'rb') as f: h.update(f.read()) return h.hexdigest() def get_new_and_missing(index): current_files = get_files(index) new_files = [path for path in current_files if path not in index.files] missing_files = [path for path in index.files.iterkeys() if path not in current_files] return new_files, missing_files
Fix in-place os.walk() dirs modification
Fix in-place os.walk() dirs modification
Python
mit
mcgid/morenines,mcgid/morenines
c157ddeae7131e4141bca43857730103617b42c4
froide/upload/serializers.py
froide/upload/serializers.py
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__'
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True
Make guid required in upload API
Make guid required in upload API
Python
mit
stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide
1d32debc1ea2ce8d11c8bc1abad048d6e4937520
froide_campaign/listeners.py
froide_campaign/listeners.py
from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from .consumers import PRESENCE_ROOM from .models import Campaign def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, ident = campaign_value.split('@', 1) except (ValueError, IndexError): return try: campaign_pk = int(campaign) except ValueError: return try: campaign = Campaign.objects.get(pk=campaign_pk) except Campaign.DoesNotExist: return provider = campaign.get_provider() iobj = provider.connect_request(ident, sender) broadcast_request_made(provider, iobj) def broadcast_request_made(provider, iobj): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( PRESENCE_ROOM.format(provider.campaign.id), { "type": "request_made", "data": provider.get_detail_data(iobj) } )
from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from .consumers import PRESENCE_ROOM from .models import Campaign def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, ident = campaign_value.split('@', 1) except (ValueError, IndexError): return if not ident: return try: campaign_pk = int(campaign) except ValueError: return try: campaign = Campaign.objects.get(pk=campaign_pk) except Campaign.DoesNotExist: return provider = campaign.get_provider() iobj = provider.connect_request(ident, sender) broadcast_request_made(provider, iobj) def broadcast_request_made(provider, iobj): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( PRESENCE_ROOM.format(provider.campaign.id), { "type": "request_made", "data": provider.get_detail_data(iobj) } )
Fix non-iobj campaign request connection
Fix non-iobj campaign request connection
Python
mit
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
de1ff8a480cc6d6e86bb179e6820ab9f21145679
byceps/services/user/event_service.py
byceps/services/user/event_service.py
""" byceps.services.user.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from typing import Sequence from ...database import db from ...typing import UserID from .models.event import UserEvent, UserEventData def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None: """Create a user event.""" event = _build_event(event_type, user_id, data) db.session.add(event) db.session.commit() def _build_event(event_type: str, user_id: UserID, data: UserEventData ) -> UserEvent: """Assemble, but not persist, a user event.""" now = datetime.utcnow() return UserEvent(now, event_type, user_id, data) def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]: """Return the events for that user.""" return UserEvent.query \ .filter_by(user_id=user_id) \ .order_by(UserEvent.occurred_at) \ .all()
""" byceps.services.user.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from typing import Optional, Sequence from ...database import db from ...typing import UserID from .models.event import UserEvent, UserEventData def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None: """Create a user event.""" event = _build_event(event_type, user_id, data) db.session.add(event) db.session.commit() def _build_event(event_type: str, user_id: UserID, data: UserEventData, occurred_at: Optional[datetime]=None) -> UserEvent: """Assemble, but not persist, a user event.""" if occurred_at is None: occurred_at = datetime.utcnow() return UserEvent(occurred_at, event_type, user_id, data) def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]: """Return the events for that user.""" return UserEvent.query \ .filter_by(user_id=user_id) \ .order_by(UserEvent.occurred_at) \ .all()
Allow to provide a custom `occurred_at` value when building a user event
Allow to provide a custom `occurred_at` value when building a user event
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
e4b2d60af93fd84407eb7107497b2b500d79f9d7
calexicon/dates/tests/test_distant.py
calexicon/dates/tests/test_distant.py
import unittest from datetime import date as vanilla_date, timedelta from calexicon.dates import DistantDate class TestDistantDate(unittest.TestCase): def test_subtraction(self): dd = DistantDate(10000, 1, 1) self.assertIsInstance(dd - vanilla_date(9999, 1, 1), timedelta) self.assertIsInstance(dd - timedelta(0), DistantDate) def test_subtract_correct_result(self): dd = DistantDate(10000, 1, 2) dd2 = DistantDate(10000, 1, 1) self.assertEqual(dd - dd2, timedelta(days=1)) def test_subtract_vanilla_date_from_distant_date(self): dd = DistantDate(10000, 1, 2) d = vanilla_date(9984, 2, 29) x = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 15 * 365 + 3 + 2 self.assertEqual(dd - d, timedelta(days=x))
import unittest from datetime import date as vanilla_date, timedelta from calexicon.calendars import ProlepticJulianCalendar from calexicon.dates import DateWithCalendar, DistantDate class TestDistantDate(unittest.TestCase): def test_subtraction(self): dd = DistantDate(10000, 1, 1) self.assertIsInstance(dd - vanilla_date(9999, 1, 1), timedelta) self.assertIsInstance(dd - timedelta(0), DistantDate) def test_subtract_correct_result(self): dd = DistantDate(10000, 1, 2) dd2 = DistantDate(10000, 1, 1) self.assertEqual(dd - dd2, timedelta(days=1)) def test_subtract_vanilla_date_from_distant_date(self): dd = DistantDate(10000, 1, 2) d = vanilla_date(9984, 2, 29) x = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 15 * 365 + 3 + 2 self.assertEqual(dd - d, timedelta(days=x)) def test_equality(self): dd = DistantDate(2010, 8, 1) ProlepticJulianCalendar().bless(dd) dwc = DateWithCalendar(ProlepticJulianCalendar, DistantDate(2010, 8, 1)) self.assertTrue(dwc == dd)
Add a passing test for equality.
Add a passing test for equality. Narrow down problems with constructing a date far in the future.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
1f2d8fadd114106cefbc23060f742163be415376
cherrypy/process/__init__.py
cherrypy/process/__init__.py
"""Site container for an HTTP server. A Web Site Process Bus object is used to connect applications, servers, and frameworks with site-wide services such as daemonization, process reload, signal handling, drop privileges, PID file management, logging for all of these, and many more. The 'plugins' module defines a few abstract and concrete services for use with the bus. Some use tool-specific channels; see the documentation for each class. """ from cherrypy.process.wspbus import bus # noqa from cherrypy.process import plugins, servers # noqa
"""Site container for an HTTP server. A Web Site Process Bus object is used to connect applications, servers, and frameworks with site-wide services such as daemonization, process reload, signal handling, drop privileges, PID file management, logging for all of these, and many more. The 'plugins' module defines a few abstract and concrete services for use with the bus. Some use tool-specific channels; see the documentation for each class. """ from .wspbus import bus from . import plugins, servers __all__ = ('bus', 'plugins', 'servers')
Use __all__ to avoid linter errors
Use __all__ to avoid linter errors
Python
bsd-3-clause
Safihre/cherrypy,Safihre/cherrypy,cherrypy/cherrypy,cherrypy/cherrypy
6dc4314f1c5510a6e5f857d739956654909d97b2
pronto/__init__.py
pronto/__init__.py
# coding: utf-8 """a Python frontend to ontologies """ from __future__ import absolute_import from __future__ import unicode_literals __version__ = 'dev' __author__ = 'Martin Larralde' __author_email__ = 'martin.larralde@ens-paris-saclay.fr' __license__ = "MIT" from .ontology import Ontology from .term import Term, TermList from .relationship import Relationship from .synonym import Synonym, SynonymType # Dynamically get the version of the installed module try: import pkg_resources __version__ = pkg_resources.get_distribution(__name__).version except Exception: pkg_resources = None finally: del pkg_resources
# coding: utf-8 """a Python frontend to ontologies """ from __future__ import absolute_import from __future__ import unicode_literals __version__ = 'dev' __author__ = 'Martin Larralde' __author_email__ = 'martin.larralde@ens-paris-saclay.fr' __license__ = "MIT" from .ontology import Ontology from .term import Term, TermList from .relationship import Relationship from .synonym import Synonym, SynonymType from .description import Description # Dynamically get the version of the installed module try: import pkg_resources __version__ = pkg_resources.get_distribution(__name__).version except Exception: pkg_resources = None finally: del pkg_resources
Add `Description` to top-level imports
Add `Description` to top-level imports
Python
mit
althonos/pronto
1e47f79647baffd62d2a434710fe98b3c2247f28
tests/pgcomplex_app/models.py
tests/pgcomplex_app/models.py
# -*- coding: utf-8 -*- from django.db import models from django_orm.postgresql.fields.arrays import ArrayField from django_orm.postgresql.fields.interval import IntervalField from django_orm.postgresql.fields.bytea import ByteaField from django_orm.postgresql.manager import PgManager class IntModel(models.Model): lista = ArrayField(dbtype='int') objects = PgManager() class TextModel(models.Model): lista = ArrayField(dbtype='text') objects = PgManager() class DoubleModel(models.Model): lista = ArrayField(dbtype='double precision') objects = PgManager() class VarcharModel(models.Model): lista = ArrayField(dbtype='varchar(40)') objects = PgManager() class IntervalModel(models.Model): iv = IntervalField() objects = PgManager() class ByteaModel(models.Model): bb = ByteaField() objects = PgManager() from django_orm.postgresql.geometric.fields import PointField, CircleField from django_orm.postgresql.geometric.fields import LsegField, BoxField from django_orm.postgresql.geometric.fields import PathField, PolygonField class GeomModel(models.Model): pt = PointField() pl = PolygonField() ln = LsegField() bx = BoxField() cr = CircleField() ph = PathField() objects = PgManager()
# -*- coding: utf-8 -*- from django.db import models from django_orm.postgresql.fields.arrays import ArrayField from django_orm.postgresql.fields.interval import IntervalField from django_orm.postgresql.fields.bytea import ByteaField from django_orm.manager import Manager class IntModel(models.Model): lista = ArrayField(dbtype='int') objects = Manager() class TextModel(models.Model): lista = ArrayField(dbtype='text') objects = Manager() class DoubleModel(models.Model): lista = ArrayField(dbtype='double precision') objects = Manager() class VarcharModel(models.Model): lista = ArrayField(dbtype='varchar(40)') objects = Manager() class IntervalModel(models.Model): iv = IntervalField() objects = Manager() class ByteaModel(models.Model): bb = ByteaField() objects = Manager() from django_orm.postgresql.geometric.fields import PointField, CircleField from django_orm.postgresql.geometric.fields import LsegField, BoxField from django_orm.postgresql.geometric.fields import PathField, PolygonField class GeomModel(models.Model): pt = PointField() pl = PolygonField() ln = LsegField() bx = BoxField() cr = CircleField() ph = PathField() objects = Manager()
Fix tests with last changes on api.
Fix tests with last changes on api.
Python
bsd-3-clause
EnTeQuAk/django-orm,EnTeQuAk/django-orm
7665e2b0af042948dfc7a1814275cd3309f5f6cf
pages/tests/__init__.py
pages/tests/__init__.py
"""Django page CMS test suite module""" from djangox.test.depth import alltests def suite(): return alltests(__file__, __name__)
"""Django page CMS test suite module""" import unittest def suite(): suite = unittest.TestSuite() from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase suite.addTest(unittest.makeSuite(FunctionnalTestCase)) suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) return suite
Remove the dependency to django-unittest-depth
Remove the dependency to django-unittest-depth
Python
bsd-3-clause
remik/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms
8dccce77f6c08a7c20f38b9f1bacc27b71ab56a1
examples/web/wiki/macros/utils.py
examples/web/wiki/macros/utils.py
"""Utils macros Utility macros """ def macros(macro, environ, *args, **kwargs): """Return a list of available macros""" s = "\n".join(["* %s" % k for k in environ["macros"].keys()]) return environ["parser"].generate(s, environ=environ)
"""Utils macros Utility macros """ from inspect import getdoc def macros(macro, environ, *args, **kwargs): """Return a list of available macros""" macros = environ["macros"].items() s = "\n".join(["== %s ==\n%s\n" % (k, getdoc(v)) for k, v in macros]) return environ["parser"].generate(s, environ=environ)
Change the output of <<macros>>
examples/web/wiki: Change the output of <<macros>>
Python
mit
treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,treemo/circuits,eriol/circuits
38833f68daabe845650250e3edf9cb4b3cc9cb62
events/templatetags/humantime.py
events/templatetags/humantime.py
# -*- encoding:utf-8 -*- # Template tag from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" if start == today: result += "aujourd'hui " else: result += "le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") return result
# -*- encoding:utf-8 -*- # Template tag from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template import locale register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" # Hack! get the correct user local from the request loc = locale.getlocale() locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8') if start == today: result += "Aujourd'hui " else: result += "Le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") locale.setlocale(locale.LC_ALL, loc) return result
Print date in fr_CA locale
hack: Print date in fr_CA locale
Python
agpl-3.0
mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord
e715dd65d3adf74624bc2102afd6a6d8f8706da6
dlm/models/components/linear.py
dlm/models/components/linear.py
import numpy import theano import theano.tensor as T class Linear(): def __init__(self, rng, input, n_in, n_out, W=None, b=None): self.input = input if W is None: W_values = numpy.asarray( rng.uniform( low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)), high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out) ), dtype=theano.config.floatX ) W = theano.shared(value=W_values, name='W', borrow=True) if b is None: b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) b = theano.shared(value=b_values, name='b', borrow=True) self.W = W self.b = b self.output = T.dot(input, self.W) + self.b # parameters of the model self.params = [self.W, self.b]
import numpy import theano import theano.tensor as T class Linear(): def __init__(self, rng, input, n_in, n_out, W_values=None, b_values=None): self.input = input if W_values is None: W_values = numpy.asarray( rng.uniform( low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)), high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out) ), dtype=theano.config.floatX ) W = theano.shared(value=W_values, name='W', borrow=True) if b_values is None: b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) # b_values = numpy.asarray( # rng.uniform( # low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)), # high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)), # size=(n_out,) # ), # dtype=theano.config.floatX ) b = theano.shared(value=b_values, name='b', borrow=True) self.W = W self.b = b self.output = T.dot(input, self.W) + self.b # parameters of the model self.params = [self.W, self.b]
Initialize from argument or using a uniform distribution
Initialize from argument or using a uniform distribution
Python
mit
nusnlp/corelm
e0091310ffdb39127f7138966026445b0bac53fc
salt/states/rdp.py
salt/states/rdp.py
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' def __virtual__(): ''' Load only if network_win is loaded ''' return 'rdp' if 'rdp.enable' in __salt__ else False def enabled(name): ''' Enable RDP the service on the server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if not stat: ret['changes'] = {'enabled rdp': True} if __opts__['test']: ret['result'] = None return ret ret['result'] = __salt__['rdp.enable']() return ret def disabled(name): ''' Disable RDP the service on the server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: ret['changes'] = {'disable rdp': True} if __opts__['test']: return ret ret['result'] = __salt__['rdp.disable']() return ret
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' def __virtual__(): ''' Load only if network_win is loaded ''' return 'rdp' if 'rdp.enable' in __salt__ else False def enabled(name): ''' Enable RDP the service on the server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if not stat: ret['changes'] = {'enabled rdp': True} if __opts__['test']: ret['result'] = stat return ret ret['result'] = __salt__['rdp.enable']() return ret def disabled(name): ''' Disable RDP the service on the server ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: ret['changes'] = {'disable rdp': True} if __opts__['test']: ret['result'] = stat return ret ret['result'] = __salt__['rdp.disable']() return ret
Return proper results for 'test=True'
Return proper results for 'test=True'
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
1a3c251abe2e8ebf3020a21a3449abae6b04c2b1
perf/tests/test_system.py
perf/tests/test_system.py
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks' '|OK! System ready for benchmarking' '|WARNING: no operation available for your platform)' % os.path.basename(sys.executable)) self.assertRegex(proc.stdout, regex, msg=proc) self.assertEqual(proc.returncode, 2, msg=proc) if __name__ == "__main__": unittest.main()
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks' '|OK! System ready for benchmarking' '|WARNING: no operation available for your platform)' % os.path.basename(sys.executable)) self.assertRegex(proc.stdout, regex, msg=proc) # The return code is either 0 if the system is tuned or 2 if the # system isn't self.assertIn(proc.returncode, (0, 2), msg=proc) if __name__ == "__main__": unittest.main()
Fix test_show test to support tuned systems
Fix test_show test to support tuned systems
Python
mit
vstinner/pyperf,haypo/perf
141eb2a647490142adf017d3a755d03ab89ed687
jrnl/plugins/tag_exporter.py
jrnl/plugins/tag_exporter.py
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, unicode_literals from .text_exporter import TextExporter from .util import get_tags_count class TagExporter(TextExporter): """This Exporter can convert entries and journals into json.""" names = ["tags"] extension = "tags" @classmethod def export_entry(cls, entry): """Returns a markdown representation of a single entry.""" return ", ".join(entry.tags) @classmethod def export_journal(cls, journal): """Returns a json representation of an entire journal.""" tag_counts = get_tags_count(journal) result = "" if not tag_counts: return '[No tags found in journal.]' elif min(tag_counts)[0] == 0: tag_counts = filter(lambda x: x[0] > 1, tag_counts) result += '[Removed tags that appear only once.]\n' result += "\n".join("{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=True)) return result
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, unicode_literals from .text_exporter import TextExporter from .util import get_tags_count class TagExporter(TextExporter): """This Exporter can lists the tags for entries and journals, exported as a plain text file.""" names = ["tags"] extension = "tags" @classmethod def export_entry(cls, entry): """Returns a list of tags for a single entry.""" return ", ".join(entry.tags) @classmethod def export_journal(cls, journal): """Returns a list of tags and their frequency for an entire journal.""" tag_counts = get_tags_count(journal) result = "" if not tag_counts: return '[No tags found in journal.]' elif min(tag_counts)[0] == 0: tag_counts = filter(lambda x: x[0] > 1, tag_counts) result += '[Removed tags that appear only once.]\n' result += "\n".join("{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=True)) return result
Update `Tag` exporter code documentation.
Update `Tag` exporter code documentation.
Python
mit
maebert/jrnl,notbalanced/jrnl,philipsd6/jrnl,MinchinWeb/jrnl