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
d0ce6af2bb893904e8a3e36dd725707bd6d9f201
indico/modules/attachments/tasks.py
indico/modules/attachments/tasks.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.core.celery import celery from indico.core.db import db from indico.modules.attachments.models.attachments import Attachment from indico.modules.files.models.files import File @celery.task(ignore_result=False) def generate_materials_package(attachment_ids, event): from indico.modules.attachments.controllers.event_package import AttachmentPackageGeneratorMixin attachments = Attachment.query.filter(Attachment.id.in_(attachment_ids)).all() attachment_package_mixin = AttachmentPackageGeneratorMixin() attachment_package_mixin.event = event generated_zip = attachment_package_mixin._generate_zip_file(attachments, return_file=True) f = File(filename='material-package.zip', content_type='application/zip', meta={'event_id': event.id}) context = ('event', event.id, 'attachment-package') f.save(context, generated_zip) db.session.add(f) db.session.commit() return f.signed_download_url
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core.celery import celery from indico.core.db import db from indico.modules.attachments.models.attachments import Attachment from indico.modules.files.models.files import File @celery.task(ignore_result=False) def generate_materials_package(attachment_ids, event): from indico.modules.attachments.controllers.event_package import AttachmentPackageGeneratorMixin attachments = Attachment.query.filter(Attachment.id.in_(attachment_ids)).all() attachment_package_mixin = AttachmentPackageGeneratorMixin() attachment_package_mixin.event = event generated_zip = attachment_package_mixin._generate_zip_file(attachments, return_file=True) f = File(filename='material-package.zip', content_type='application/zip', meta={'event_id': event.id}) context = ('event', event.id, 'attachment-package') f.save(context, generated_zip) db.session.add(f) db.session.commit() os.unlink(generated_zip.name) return f.signed_download_url
Delete material package temp file after creation
Delete material package temp file after creation
Python
mit
ThiefMaster/indico,ThiefMaster/indico,DirkHoffmann/indico,pferreir/indico,indico/indico,pferreir/indico,indico/indico,indico/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico,DirkHoffmann/indico,indico/indico,ThiefMaster/indico
b0e3e93c3af70e42edf110e09039815575195c00
packages/dependencies/spirv_tools.py
packages/dependencies/spirv_tools.py
{ 'repo_type' : 'git', 'rename_folder' : 'spirv-tools', 'url' : 'https://github.com/KhronosGroup/SPIRV-Tools.git', 'branch' : 'aa270e568a3fd637f4a329611107b384a8023195', 'needs_make' : False, 'needs_make_install' : False, 'needs_configure' : False, 'recursive_git' : True, '_info' : { 'version' : None, 'fancy_name' : 'SPIRV Tools' }, }
{ 'repo_type' : 'git', 'rename_folder' : 'spirv-tools', 'url' : 'https://github.com/KhronosGroup/SPIRV-Tools.git', 'needs_make' : False, 'needs_make_install' : False, 'needs_configure' : False, 'recursive_git' : True, '_info' : { 'version' : None, 'fancy_name' : 'SPIRV Tools' }, }
Revert "packages/spirvtools: stick to last working commit"
Revert "packages/spirvtools: stick to last working commit" This reverts commit cbaac43c95226b4ca5c9c1478467069966e9ef35.
Python
mpl-2.0
DeadSix27/python_cross_compile_script
12914961c0c2851dd720e84ff811389b1cd936dd
wsgi.py
wsgi.py
""" WSGI script run on Heroku using gunicorn. Exposes the app and configures it to use Heroku environment vars. """ import os from suddendev import create_app, socketio app = create_app() if __name__ == '__main__': app.run()
""" WSGI script run on Heroku using gunicorn. Exposes the app and configures it to use Heroku environment vars. """ import os from suddendev import create_app, socketio app = create_app() if __name__ == '__main__': socketio.run(app)
Change to socketio.run() so WebSockets work on local runs.
[NG] Change to socketio.run() so WebSockets work on local runs.
Python
mit
SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev
e050864d333e4b332a21671cb5f08f2ffd9172fe
pipeline/archivebot/shared_config.py
pipeline/archivebot/shared_config.py
import os import yaml def config(): my_dir = os.path.dirname(__file__) config_file = os.path.join(my_dir, '../../lib/shared_config.yml') with open(config_file, 'r') as f: return yaml.load(f.read()) def log_channel(): c = config() return c['channels']['log'] def pipeline_channel(): c = config() return c['channels']['pipeline'] def job_channel(ident): return '%s%s' % (job_channel_prefix(), ident) def job_channel_prefix(): c = config() return c['channels']['job_prefix'] # vim:ts=4:sw=4:et:tw=78
import os import yaml try: from yaml import CLoader as Loader except ImportError: from yaml import Loader def config(): my_dir = os.path.dirname(__file__) config_file = os.path.join(my_dir, '../../lib/shared_config.yml') with open(config_file, 'r') as f: return yaml.load(f.read(), Loader = Loader) def log_channel(): c = config() return c['channels']['log'] def pipeline_channel(): c = config() return c['channels']['pipeline'] def job_channel(ident): return '%s%s' % (job_channel_prefix(), ident) def job_channel_prefix(): c = config() return c['channels']['job_prefix'] # vim:ts=4:sw=4:et:tw=78
Fix compatibility with PyYAML 6.0 (mandatory `Loader`)
Fix compatibility with PyYAML 6.0 (mandatory `Loader`)
Python
mit
ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot
bb3d2927437a51d8144ec398085876bc3dedb5f6
project_generator/commands/clean.py
project_generator/commands/clean.py
# Copyright 2014-2015 0xc0170 # # 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 os import logging from ..generate import Generator help = 'Clean generated projects' def run(args): if os.path.exists(args.file): generator = Generator(args.file) for project in generator.generate(args.project): project.clean(args.tool) else: # not project known by progen logging.warning("%s not found." % args.file) return -1 return 0 def setup(subparser): subparser.add_argument("-f", "--file", help="YAML projects file", default='projects.yaml') subparser.add_argument("-p", "--project", required = True, help="Specify which project to be removed") subparser.add_argument( "-t", "--tool", help="Clean project files")
# Copyright 2014-2015 0xc0170 # # 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 os import logging from ..generate import Generator help = 'Clean generated projects' def run(args): if os.path.exists(args.file): generator = Generator(args.file) for project in generator.generate(args.project): project.clean(args.tool) else: # not project known by progen logging.warning("%s not found." % args.file) return -1 return 0 def setup(subparser): subparser.add_argument("-f", "--file", help="YAML projects file", default='projects.yaml') subparser.add_argument("-p", "--project", required = True, help="Specify which project to be removed") subparser.add_argument( "-t", "--tool", help="Clean project files for this tool")
Clean command - tool help fix
Clean command - tool help fix
Python
apache-2.0
sarahmarshy/project_generator,ohagendorf/project_generator,0xc0170/project_generator,project-generator/project_generator
d198b8d92ec42f8e5fc995f59c8776044b8950e8
analysis/data_process/uk_2017/config.py
analysis/data_process/uk_2017/config.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Config file for the cleaning - plotting and notebook process""" class CleaningConfig: # Unprocessed dataset raw_data = './dataset/raw_results-survey245554.csv' # load the different answers to questions to classify questions based on that question_file = '../../../survey_creation/uk_17/uk_17.csv' answer_folder = '../../../survey_creation/uk_17/listAnswers' # Location for the json file of all questions json_to_plot_location = './to_plot.json' cleaned_df_location = './dataset/cleaned_data.csv' count_na = True normalise = False class PlottingConfig(CleaningConfig): plot_na = False normalise = True class NotebookConfig(PlottingConfig): notebook_folder = './' notebook_filename = 'uk_17.ipynb' allow_errors = True to_import = ['import pandas as pd', 'import numpy as np', 'import matplotlib', 'import matplotlib.pyplot as plt', 'from config import CleaningConfig, PlottingConfig, NotebookConfig', 'from counting import get_count', 'from plotting import get_plot', 'from IPython.display import display', 'from likertScalePlot import likert_scale'] processing_options = {'metadata': {'path': './'}}
#!/usr/bin/env python # -*- coding: utf-8 -*- """Config file for the cleaning - plotting and notebook process""" class CleaningConfig: # Unprocessed dataset raw_data = './dataset/raw_results-survey245554.csv' # load the different answers to questions to classify questions based on that question_file = '../../../survey_creation/uk_17/uk_17.csv' answer_folder = '../../../survey_creation/uk_17/listAnswers' # Location for the json file of all questions json_to_plot_location = './to_plot.json' cleaned_df_location = './dataset/cleaned_data.csv' count_na = True normalise = False class PlottingConfig(CleaningConfig): plot_na = False normalise = True # Different than normalise, add a freq_table with percentage # in addition of the table with counts show_percent = True class NotebookConfig(PlottingConfig): notebook_folder = './' notebook_filename = 'uk_17.ipynb' allow_errors = True to_import = ['import pandas as pd', 'import numpy as np', 'import matplotlib', 'import matplotlib.pyplot as plt', 'from config import CleaningConfig, PlottingConfig, NotebookConfig', 'from counting import get_count', 'from plotting import get_plot', 'from IPython.display import display', 'from likertScalePlot import likert_scale'] processing_options = {'metadata': {'path': './'}}
Add the option for showing percent rather than count in plots
Add the option for showing percent rather than count in plots
Python
bsd-3-clause
softwaresaved/international-survey
da22196a8167a57c5edf39578ceece4efd8cfd63
app/views.py
app/views.py
from app import app from flask import make_response @app.route('/') @app.route('/index') def index(): return make_response(open(app.root_path + '/templates/index.html').read())
from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = { 'nickname': 'Marvolo' } # fake user posts = [ # fake array of posts { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title = 'Home', user = user, posts = posts)
Set up mock data for index
Set up mock data for index
Python
apache-2.0
happyraul/tv
158a2ffd17cf59a87092581dc0ce40cf0b82aa85
bigbuild/management/commands/publish.py
bigbuild/management/commands/publish.py
from django.conf import settings from bakery.management.commands.publish import Command as BaseCommand class Command(BaseCommand): def handle(self, *args, **options): # When in BIGBUILD_BRANCH_BUILD don't delete because we'll be syncing # a different subdirectory for each one of our git branches if settings.BIGBUILD_BRANCH_BUILD: options['no_delete'] = True super(Command, self).handle(*args, **options)
from django.conf import settings from bakery.management.commands.publish import Command as BaseCommand class Command(BaseCommand): def handle(self, *args, **options): # When in BIGBUILD_BRANCH_BUILD don't delete because we'll be syncing # a different subdirectory for each one of our git branches if getattr(settings, 'BIGBUILD_BRANCH_BUILD', False): options['no_delete'] = True super(Command, self).handle(*args, **options)
Make an attribute call a little smarter
Make an attribute call a little smarter
Python
mit
datadesk/django-bigbuild,datadesk/django-bigbuild,datadesk/django-bigbuild
939c5fd069fafbe353fc9a209d2bd376e8d9bbd6
gridded/gridded.py
gridded/gridded.py
class Gridded: _grid_obj_classes = [] _grids_loaded = False @classmethod def _load_grid_objs(cls): from pkg_resources import working_set for ep in working_set.iter_entry_points('gridded.grid_objects'): cls._grid_obj_classes.append(ep.load()) @classmethod def load(cls, nc, *args, **kwargs): for go in self._grid_obj_classes: if hasattr(go, 'is_mine') and go.is_mine(nc): return go(nc, *args, **kwargs)
class Gridded: _grid_obj_classes = [] _grids_loaded = False @classmethod def _load_grid_objs(cls): from pkg_resources import working_set for ep in working_set.iter_entry_points('gridded.grid_objects'): cls._grid_obj_classes.append(ep.load()) @classmethod def load(cls, *args, **kwargs): for go in cls._grid_obj_classes: if hasattr(go, 'is_mine') and go.is_mine(*args, **kwargs): return go(*args, **kwargs)
Fix self- > cls, make super generic (no `nc`)
Fix self- > cls, make super generic (no `nc`)
Python
mit
pyoceans/gridded
d2adf86767857e9b57527c3db1d720b1f8f086a2
openedx/stanford/djangoapps/register_cme/admin.py
openedx/stanford/djangoapps/register_cme/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo admin.site.register(ExtraInfo)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
Make `user` field read-only in `ExtraInfo` detail
Make `user` field read-only in `ExtraInfo` detail Previously, server would hang trying to load an `ExtraInfo` detail page, because the `user` field was rendering as a dropdown select menu loading all users in the system. We fix this by making the field read-only.
Python
agpl-3.0
caesar2164/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform
cf8621affe1e654bf5ec391d80f260cbce83445b
cli/cli.py
cli/cli.py
import argparse parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser('list', help='List commands') list_parser.add_argument('list_commands', action='store', choices=['all', 'basic'],help='List anayltics commands based on choice') # An run command to execute the analysis run_parser = subparsers.add_parser('run', help='Run commands') run_parser.add_argument('run_commands', help='Run analytics based on argument', nargs='?', default='basic') if __name__ == '__main__': args = parser.parse_args() print args
import argparse import os parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1.0') subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser('list', help='List commands') list_parser.add_argument('list_action', action='store', choices=['all', 'basic'],help='List anayltics commands based on choice') # An run command to execute the analysis run_parser = subparsers.add_parser('run', help='Run commands') run_parser.add_argument('db_name', help='Name of database where each database corresponds to a course offering') run_parser.add_argument('run_action', help='Run analytics based on argument', nargs='?', default='basic') run_parser.add_argument('-o', '--output', help='Path to directory to save CSV report (defaults to current directory: %(default)s)', default=os.getcwd()) run_parser.add_argument('-j', '--json', help='Path to JSON file that may be needed for some analytics commands') run_parser.add_argument('-c', '--csv', help='Path to CSV file that may be needed for some analytics commands') run_parser.add_argument('-p', '--problem-id', help='Course specifc problem ID that may be needed for some analytics commands') if __name__ == '__main__': args = parser.parse_args() print args
Define more arguments for command line parser
Define more arguments for command line parser
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
adfbd9b192316bc527259a1c0a01db0a8dbd5f3e
examples/rmg/liquid_phase/input.py
examples/rmg/liquid_phase/input.py
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List of species species( label='octane', reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationConversion={ 'octane': 0.9, }, terminationTime=(1e6,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, )
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List of species species( label='octane', reactive=True, structure=SMILES("C(CCCCC)CC"), ) species( label='oxygen', reactive=True, structure=SMILES("[O][O]"), ) # Reaction systems liquidReactor( temperature=(500,'K'), initialConcentrations={ "octane": (6.154e-3,'mol/cm^3'), "oxygen": (4.953e-6,'mol/cm^3') }, terminationTime=(5,'s'), ) solvation( solvent='octane' ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=1E-9, toleranceMoveToCore=0.001, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000 ) options( units='si', saveRestartPeriod=None, drawMolecules=False, generatePlots=False, saveConcentrationProfiles=True, )
Change termination criteria for liquid phase examples to attainable value.
Change termination criteria for liquid phase examples to attainable value. Conversion of octane was stuck at 8e-3 for quite some time...
Python
mit
nyee/RMG-Py,faribas/RMG-Py,enochd/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,chatelak/RMG-Py,enochd/RMG-Py,nyee/RMG-Py,KEHANG/RMG-Py,KEHANG/RMG-Py,nickvandewiele/RMG-Py,comocheng/RMG-Py
e4e38ecd09b4c96e5b801b1bc9f7a943934c6485
cobertura_clover_transform/converter.py
cobertura_clover_transform/converter.py
import lxml.etree as ET import argparse import pkg_resources def convert(inxml): dom = ET.parse(inxml) xslt = ET.parse(pkg_resources.resource_stream('cobertura_clover_transform', 'transform.xslt')) transform = ET.XSLT(xslt) newdom = transform(dom) return ET.tostring(newdom, pretty_print=True) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('coverage_xml') args = parser.parse_args() converted = convert(args.coverage_xml) print(converted)
import lxml.etree as ET import argparse import pkg_resources def convert(inxml): dom = ET.parse(inxml) xslt = ET.parse(pkg_resources.resource_stream('cobertura_clover_transform', 'transform.xslt')) transform = ET.XSLT(xslt) newdom = transform(dom) return ET.tostring(newdom, pretty_print=True) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('coverage_xml') parser.add_argument('-o', '--output', required=False) args = parser.parse_args() converted = convert(args.coverage_xml) if args.output: with open(args.output, 'w') as out: out.write(converted) else: print(converted)
Add support for output to a file
Add support for output to a file
Python
mit
cwacek/cobertura-clover-transform
270e222301cf8c61e7632b366fba349552356928
services/__init__.py
services/__init__.py
#!/usr/bin/env python import os import glob __all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/*.py")] class InvalidConfigException(Exception): pass class PluginMount(type): def __init__(cls, name, bases, attrs): if not hasattr(cls, 'plugins'): # This branch only executes when processing the mount point itself. # So, since this is a new plugin type, not an implementation, this # class shouldn't be registered as a plugin. Instead, it sets up a # list where plugins can be registered later. cls.plugins = [] else: # This must be a plugin implementation, which should be registered. # Simply appending it to the list is all that's needed to keep # track of it later. cls.plugins.append(cls) class Service: """ The constructor is passed a dictionary containing the configuration options for the service """ __metaclass__ = PluginMount def verify_up(self): """Returns a boolean representing whether the service is up or not""" pass def owner(self): """Returns a string containing the name of the owning team/player""" pass
#!/usr/bin/env python import os import glob __all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/*.py")] class InvalidConfigException(Exception): pass class PluginMount(type): def __init__(cls, name, bases, attrs): if not hasattr(cls, 'plugins'): # This branch only executes when processing the mount point itself. # So, since this is a new plugin type, not an implementation, this # class shouldn't be registered as a plugin. Instead, it sets up a # list where plugins can be registered later. cls.plugins = [] else: # This must be a plugin implementation, which should be registered. # Simply appending it to the list is all that's needed to keep # track of it later. cls.plugins.append(cls) def get_plugin(cls, name): """Get an new plugin by name""" for p in cls.plugins: if p.name == name: return p return None class Service: """ The constructor is passed a dictionary containing the configuration options for the service. All Services must specify the 'name' attribute. """ __metaclass__ = PluginMount def verify_up(self): """Returns a boolean representing whether the service is up or not""" pass def owner(self): """Returns a string containing the name of the owning team/player""" pass
Add get_plugin method to the plugin base.
Add get_plugin method to the plugin base.
Python
bsd-3-clause
vtcsec/wargame-scorer
3a3997b19966560b828efb1699ee29a58cacbfc8
spriteworld/configs/cobra/common.py
spriteworld/configs/cobra/common.py
# Copyright 2019 DeepMind Technologies Limited. # # 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 # # https://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. # ============================================================================ # python2 python3 """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
# Copyright 2019 DeepMind Technologies Limited. # # 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 # # https://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. # ============================================================================ # python2 python3 """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
Remove noise from default COBRA configs.
Remove noise from default COBRA configs. PiperOrigin-RevId: 265733849 Change-Id: Ie0e7c0385497852fd85c769ee85c951542c14463
Python
apache-2.0
deepmind/spriteworld
752dca349d9f93c2a756e0b1b891006159eecbad
impactstoryanalytics/highcharts.py
impactstoryanalytics/highcharts.py
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': 'null'}, 'subtitle': {'text': 'null'}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker': { 'enabled': False } } }, }
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': None}, 'subtitle': {'text': None}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker': { 'enabled': False } } }, }
Use None instead of "null" in Highcharts boilerplate
Use None instead of "null" in Highcharts boilerplate
Python
mit
Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics
aee8d2911c3f19a9b748f21ae82592d823e0c57e
update.py
update.py
#! /usr/bin/python import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', 'public/', 's3://tempura.8-p.info/' ])
#! /usr/bin/python import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ])
Set ACL explicitly to make files readable
Set ACL explicitly to make files readable
Python
mit
kzys/planet-tempura
9656b9fb1590513398bfca20f53483c6397b8095
morepath/generic.py
morepath/generic.py
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ @reg.generic def app(obj): """Get the application that this object is associated with. """ @reg.generic def base(model): """Get the base that this model is associated with. """ @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ @reg.generic def link(request, model): """Create a link (URL) to model. """ @reg.generic def traject(obj): """Get traject for obj. """ @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ raise NotImplementedError @reg.generic def app(obj): """Get the application that this object is associated with. """ raise NotImplementedError @reg.generic def base(model): """Get the base that this model is associated with. """ raise NotImplementedError @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ raise NotImplementedError @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ raise NotImplementedError @reg.generic def link(request, model): """Create a link (URL) to model. """ raise NotImplementedError @reg.generic def traject(obj): """Get traject for obj. """ raise NotImplementedError @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ raise NotImplementedError @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """ raise NotImplementedError
Raise NotImplementedError for basic stuff.
Raise NotImplementedError for basic stuff.
Python
bsd-3-clause
morepath/morepath,faassen/morepath,taschini/morepath
8723611817a982907f3f0a98ed4678d587597002
src/appleseed.python/test/runtests.py
src/appleseed.python/test/runtests.py
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import unittest from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import unittest from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
Add new unit tests to collection
Add new unit tests to collection
Python
mit
pjessesco/appleseed,dictoon/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,glebmish/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,dictoon/appleseed,luisbarrancos/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,dictoon/appleseed,aiivashchenko/appleseed,gospodnetic/appleseed,gospodnetic/appleseed,Biart95/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,Biart95/appleseed,dictoon/appleseed,aiivashchenko/appleseed,aiivashchenko/appleseed,Aakash1312/appleseed,Biart95/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,dictoon/appleseed,appleseedhq/appleseed,Aakash1312/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,pjessesco/appleseed,glebmish/appleseed,aiivashchenko/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,aytekaman/appleseed,est77/appleseed,est77/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,glebmish/appleseed,est77/appleseed,appleseedhq/appleseed
e85883389dd14377d63fc8c0b4decf486b3b7c2c
conveyor/exceptions.py
conveyor/exceptions.py
class HashMismatch(ValueError): """ Raised when the incoming hash of a file does not match the expected. """
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class HashMismatch(ValueError): """ Raised when the incoming hash of a file does not match the expected. """
Bring the standard imports over
Bring the standard imports over
Python
bsd-2-clause
crateio/carrier
d5acdacbbe4e4a5464b789a92a31b56cb94aa6a0
GTT/test/example_usage.py
GTT/test/example_usage.py
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) my_excel_writer = ew.ExcelWriter("test/testData/test_excel_write.xlsx") my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) excel_write = os.path.join(TEST_DATA_DIR, 'test_excel_write.xlsx') my_excel_writer = ew.ExcelWriter(excel_write) my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
Use the correct excel path.
Use the correct excel path.
Python
mit
314ish/StudbookToolkit
faac7b98d3270267b731c97aa0318d532f75610c
dash_table/__init__.py
dash_table/__init__.py
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table`""", stacklevel=2, )
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format import Group` with `from dash.dash_table.Format import Group`""", stacklevel=2, )
Add info on table format helpers to warning message
Add info on table format helpers to warning message
Python
mit
plotly/dash-table,plotly/dash-table,plotly/dash-table
34a2b3a93bd96643d74fcb3c8d2f8db52d18253f
desubot.py
desubot.py
from motobot.irc_bot import IRCBot, IRCLevel import desubot import threading def worker(): desubot.bot.run() def main(): desubot.bot.load_plugins('plugins') desubot.bot.join('#Moto-chan') thread = threading.Thread(target=worker) thread.start() while True: msg = input() if msg.startswith(':'): desubot.bot.load_plugins('plugins') else: desubot.bot.send(msg) if __name__ == '__main__': main() else: bot = IRCBot('desutest', 'irc.rizon.net', command_prefix='!')
from motobot.irc_bot import IRCBot, IRCLevel import desubot import threading import traceback def worker(): desubot.bot.run() def main(): desubot.bot.load_plugins('plugins') desubot.bot.join('#Moto-chan') desubot.bot.join('#animu') desubot.bot.join('#anime-planet.com') thread = threading.Thread(target=worker) thread.start() while True: try: msg = input() if msg.startswith(':'): desubot.bot.load_plugins('plugins') else: desubot.bot.send(msg) except: traceback.print_exc() if __name__ == '__main__': main() else: bot = IRCBot('desubot', 'irc.rizon.net', command_prefix='!')
Make exception on reload not crash input
Make exception on reload not crash input
Python
mit
Motoko11/MotoBot
fbd7c3b5627ba288ac400944ee242f3369143291
calico_containers/tests/st/test_container_to_host.py
calico_containers/tests/st/test_container_to_host.py
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop")
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
Clarify test_containers_to_host not using libnetwork
Clarify test_containers_to_host not using libnetwork
Python
apache-2.0
fasaxc/calicoctl,fasaxc/calicoctl,projectcalico/calico-containers,insequent/calico-docker,tomdee/calico-docker,robbrockbank/calico-containers,robbrockbank/calicoctl,Metaswitch/calico-docker,TrimBiggs/calico-containers,tomdee/calico-docker,dalanlan/calico-docker,CiscoCloud/calico-docker,TeaBough/calico-docker,webwurst/calico-docker,webwurst/calico-docker,caseydavenport/calico-containers,quater/calico-containers,quater/calico-containers,dalanlan/calico-docker,TrimBiggs/calico-containers,robbrockbank/calico-docker,fasaxc/calico-docker,tomdee/calico-containers,CiscoCloud/calico-docker,projectcalico/calico-docker,Metaswitch/calico-docker,fasaxc/calico-docker,insequent/calico-docker,projectcalico/calico-docker,caseydavenport/calico-containers,johscheuer/calico-docker,robbrockbank/calicoctl,caseydavenport/calico-docker,projectcalico/calico-containers,alexhersh/calico-docker,johscheuer/calico-docker,TrimBiggs/calico-docker,robbrockbank/calico-containers,caseydavenport/calico-docker,TrimBiggs/calico-docker,robbrockbank/calico-docker,caseydavenport/calico-containers,alexhersh/calico-docker,TeaBough/calico-docker,tomdee/calico-containers,projectcalico/calico-containers
a5585f7e437a402b10e4fa9094172a10a8955eac
__init__.py
__init__.py
import sys import importlib sys.modules[__package__] = importlib.import_module('.dataset', __package__)
import os __path__.append(os.path.dirname(__file__) + '/dataset') from .dataset import *
Replace importlib hack with __path__
Replace importlib hack with __path__
Python
apache-2.0
analysiscenter/dataset
e230f3af592ffce613fa7c2bcf05e2993df9e1a6
__init__.py
__init__.py
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by Gabriel Brammer on 2011-05-18. $URL$ $Author$ $Date$ """ __version__ = "$Rev$" from socket import gethostname as hostname if hostname().startswith('uni'): GRISM_HOME = '/3DHST/Spectra/Work/' else: GRISM_HOME = '/research/HST/GRISM/3DHST/' if hostname().startswith('850dhcp8'): GRISM_HOME = '/3DHST/Spectra/Work/' #threedhst.sex.RUN_MODE='direct' import threedhst try: import utils_c #as utils_c except: print """Couldn't import "utils_c" """ import prepare import reduce import candels import analysis import go_3dhst import galfit import plotting import catalogs import survey_paper import go_acs import fast import interlace_fit import intersim noNewLine = '\x1b[1A\x1b[1M'
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by Gabriel Brammer on 2011-05-18. $URL$ $Author$ $Date$ """ __version__ = "$Rev$" from socket import gethostname as hostname if hostname().startswith('uni'): GRISM_HOME = '/3DHST/Spectra/Work/' else: GRISM_HOME = '/research/HST/GRISM/3DHST/' if hostname().startswith('850dhcp8'): GRISM_HOME = '/3DHST/Spectra/Work/' #threedhst.sex.RUN_MODE='direct' import threedhst try: import utils_c #as utils_c except: print """Couldn't import "utils_c" """ import plotting import prepare import reduce import candels import analysis import go_3dhst import galfit import catalogs import survey_paper import go_acs import fast import interlace_fit import intersim noNewLine = '\x1b[1A\x1b[1M'
Add separate "plotting" script for general plot setup.
Add separate "plotting" script for general plot setup. git-svn-id: b93d21f79df1f7407664ec6e512ac344bf52ef2a@711 f9184c78-529c-4a83-b317-4cf1064cc5e0
Python
mit
gbrammer/pygrism,gbrammer/unicorn,gbrammer/unicorn,gbrammer/pygrism
57f5d8c1f02aa5d3a1be5fdc7302a15d416071dc
utils/decorators.py
utils/decorators.py
from functools import wraps def bot_only(func): @wraps(func) def inner(self, *args, **kwargs): if not self.user.bot: return return func(self, *args, **kwargs) return inner
from functools import wraps def bot_only(coro): @wraps(coro) async def inner(self, *args, **kwargs): if not self.user.bot: return return await coro(self, *args, **kwargs) return inner
Make bot_only async, because duh
Make bot_only async, because duh
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
1e775fbc8e11f44b8a680e17ac35e735e52d5739
fabfile.py
fabfile.py
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def fetch_episodes(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py fetchepisodes') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
Add fab command for fetching episodes
Add fab command for fetching episodes
Python
mit
matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik
e41d46fe0539aa102a8af92236add5ba876db7a0
elections/mixins.py
elections/mixins.py
from django.conf import settings from django.http import Http404 from django.utils.translation import ugettext as _ class ElectionMixin(object): '''A mixin to add election data from the URL to the context''' def dispatch(self, request, *args, **kwargs): self.election = election = self.kwargs['election'] if election not in settings.ELECTIONS: raise Http404(_("Unknown election: '{election}'").format(election=election)) self.election_data = settings.ELECTIONS[election] return super(ElectionMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ElectionMixin, self).get_context_data(**kwargs) context['election'] = self.election context['election_data'] = self.election_data return context
from django.utils.translation import ugettext as _ from django.shortcuts import get_object_or_404 from models import Election class ElectionMixin(object): '''A mixin to add election data from the URL to the context''' def dispatch(self, request, *args, **kwargs): self.election = election = self.kwargs['election'] self.election_data = get_object_or_404(Election, slug=election) return super(ElectionMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ElectionMixin, self).get_context_data(**kwargs) context['election'] = self.election context['election_data'] = self.election_data return context
Use the Election model in the elections Mixin
Use the Election model in the elections Mixin
Python
agpl-3.0
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit
d9e7816da08a3d66e63356ea6f4474cc5f7d6b26
bush/main.py
bush/main.py
from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() spinner.stop() if output: print("\n".join(output))
import sys import traceback from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() try: output = run_aws(options, args) except: spinner.stop() traceback.print_exc() sys.exit(2) spinner.stop() if output: print("\n".join(output)) def run_aws(options, args): if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() return output
Fix keep turning spinner when error occurred
Fix keep turning spinner when error occurred
Python
mit
okamos/bush
18c99ee2b96564913cbd406bb540af10b078b2f3
example.py
example.py
from datetime import datetime from timetabler.schedule import Schedule from timetabler.ssc.course import Lecture, Discussion def main(): s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"], session="2014W", terms=[2]) # STTs are for Vantage College students s.courses["GEOG 122"].add_constraint( lambda acts: all(a.status not in [u"STT"] for a in acts) ) # Default sections contained a Tutorial but that is for Vantage # students, so removing that and only setting Lecture and Discussion s.courses["GEOG 122"].num_section_constraints = [ (Lecture, 1), (Discussion, 1) ] return s.generate_schedules() if __name__ == '__main__': start_time = datetime.now() scheds = main() print(datetime.now() - start_time)
import json from datetime import datetime from timetabler.schedule import Schedule from timetabler.ssc.course import Lecture, Discussion def main(): s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"], session="2014W", terms=[2]) # STTs are for Vantage College students s.courses["GEOG 122"].add_constraint( lambda acts: all(a.status not in [u"STT"] for a in acts) ) # Default sections contained a Tutorial but that is for Vantage # students, so removing that and only setting Lecture and Discussion s.courses["GEOG 122"].num_section_constraints = [ (Lecture, 1), (Discussion, 1) ] return s.generate_schedules() if __name__ == '__main__': start_time = datetime.now() scheds = main() # Unwrap activities out of course-specific tuples scheds = [[act for crs in sched for act in crs] for sched in scheds] # Sort so that the sum of starting times for courses # throughout the week are greatest scheds = sorted( scheds, key=lambda s: sum(int(a.start_time.replace(":", "")) for a in s), reverse=True ) print("Schedule with latest starting times (sum): {}".format( json.dumps([repr(s) for s in scheds[0]], indent=4) )) print("This took {} to calculate.".format( datetime.now() - start_time ))
Add latest starting time sorting
Add latest starting time sorting
Python
mit
hfaran/ubc-timetabler
d5e3a4f76121b4c1c38787156c50e0602c4de43f
fabfile.py
fabfile.py
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ] def deploy_page(): run('rm -rf fabric-workshop') run('git clone https://github.com/zkan/fabric-workshop.git') run('sudo cp fabric-workshop/index.html /usr/share/nginx/html') run('sudo service nginx restart')
Add deploy task to deploy a new Nginx index page
Add deploy task to deploy a new Nginx index page
Python
mit
zkan/fabric-workshop,zkan/fabric-workshop
35308ba3dbfc25e86fab720e67d6a9576d6937c9
fabfile.py
fabfile.py
from fabric.api import lcd, local from fabric.decorators import runs_once import os fabfile_dir = os.path.dirname(__file__) def update_theme(): theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx') if not os.path.exists('/tmp/sphinx_rtd_theme'): local('git clone https://github.com/snide/sphinx_rtd_theme.git /tmp/sphinx_rtd_theme') with lcd('/tmp/sphinx_rtd_theme'): local('git remote update') local('git reset --hard origin/master ') local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme %s' % theme_dir) local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/fonts/ %s' % os.path.join(fabfile_dir, 'media', 'font')) local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/badge_only.css %s' % os.path.join(fabfile_dir, 'media', 'css')) local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/theme.css %s' % os.path.join(fabfile_dir, 'media', 'css', 'sphinx_rtd_theme.css')) def i18n(): with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('tx pull') local('./manage.py makemessages --all') #local('tx push -s') local('./manage.py compilemessages') def i18n_docs(): with lcd('docs'): # Update our tanslations local('tx pull -a') local('sphinx-intl build') # Push new ones local('make gettext') local('tx push -s') @runs_once def spider(): local('patu.py -d1 readthedocs.org')
from fabric.api import lcd, local from fabric.decorators import runs_once import os fabfile_dir = os.path.dirname(__file__) def i18n(): with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('tx pull') local('./manage.py makemessages --all') #local('tx push -s') local('./manage.py compilemessages') def i18n_docs(): with lcd('docs'): # Update our tanslations local('tx pull -a') local('sphinx-intl build') # Push new ones local('make gettext') local('tx push -s') @runs_once def spider(): local('patu.py -d1 readthedocs.org')
Drop fab file task for updating theme as well
Drop fab file task for updating theme as well
Python
mit
espdev/readthedocs.org,pombredanne/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,techtonik/readthedocs.org,wijerasa/readthedocs.org,techtonik/readthedocs.org,espdev/readthedocs.org,stevepiercy/readthedocs.org,gjtorikian/readthedocs.org,espdev/readthedocs.org,clarkperkins/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,SteveViss/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,stevepiercy/readthedocs.org,emawind84/readthedocs.org,SteveViss/readthedocs.org,emawind84/readthedocs.org,wijerasa/readthedocs.org,espdev/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,SteveViss/readthedocs.org,stevepiercy/readthedocs.org,pombredanne/readthedocs.org,tddv/readthedocs.org,rtfd/readthedocs.org,clarkperkins/readthedocs.org,istresearch/readthedocs.org,clarkperkins/readthedocs.org,istresearch/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,SteveViss/readthedocs.org,safwanrahman/readthedocs.org,gjtorikian/readthedocs.org,istresearch/readthedocs.org,techtonik/readthedocs.org,gjtorikian/readthedocs.org,istresearch/readthedocs.org,emawind84/readthedocs.org,techtonik/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,clarkperkins/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org
97990ea039228eb3311b148c047fae015a4f4d7e
examples/boilerplates/base_test_case.py
examples/boilerplates/base_test_case.py
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. With Python 3, simplify "super(...)" to super().setUp() and super().tearDown() ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def setUp(self): super(BaseTestCase, self).setUp() # <<< Add custom setUp code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() # <<< Add custom tearDown code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. With Python 3, simplify "super(...)" to super().setUp() and super().tearDown() ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def setUp(self): super(BaseTestCase, self).setUp() # <<< Run custom setUp() code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() if self.has_exception(): # <<< Run custom code if the test failed. >>> pass else: # <<< Run custom code if the test passed. >>> pass # (Wrap unreliable tearDown() code in a try/except block.) # <<< Run custom tearDown() code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
Update the boilerplate example by adding "has_exception()"
Update the boilerplate example by adding "has_exception()"
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
88964dc79be1c88f1a197c5a59f342c9b7749ed2
fantasyStocks/stocks/views.py
fantasyStocks/stocks/views.py
from django.shortcuts import render from django.http import HttpResponse from stocks import forms # Create your views here. def index(request): regForm = forms.RegistrationForm() logForm = forms.LoginForm() return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) def instructions(request): return render(request, "instructions.html")
from django.shortcuts import render from django.http import HttpResponse from stocks import forms from django.contrib.auth.models import User # Create your views here. def index(request): # If we got here through a submission... if request.method == "POST": if request.POST.get("password1", None): form = forms.RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data["email"], email=form.cleaned_data["email"], password=form.cleaned_data["password"]) user.save() else: if form._errors["already_exists"]: error = form._errors["already_exists"] else: error = "There was an error with your registration" elif request.POST["password"]: form = forms.LoginForm(request.POST) else: regForm = forms.RegistrationForm() logForm = forms.LoginForm() return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) def instructions(request): return render(request, "instructions.html")
Make some progress on the view.
Make some progress on the view. I need to make it return a HttpResponse though. oops.
Python
apache-2.0
ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks
93af551b8f0ce03b16dd7aad1a2963cc4e5b6d6a
fabfile.py
fabfile.py
from fabric.api import cd, run, sudo, env, roles, execute from datetime import datetime env.roledefs = { 'webuser': ['bloge@andrewlorente.com'], 'sudoer': ['alorente@andrewlorente.com'], } env.hosts = ['andrewlorente.com'] def deploy(): release_id = datetime.now().strftime("%Y%m%d%H%M%S") execute(build, release_id) release(release) @roles('webuser') def build(release_id): releases_dir = "/u/apps/bloge/releases/" run("git clone -q https://github.com/AndrewLorente/bloge.git " + releases_dir + release_id) with cd(releases_dir + release_id): run("cabal update") run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v") run("cabal configure") run("cabal build") run("ln -nfs /u/apps/bloge/releases/{0} " "/u/apps/bloge/current".format(release_id)) @roles('sudoer') def release(*args): sudo("initctl restart bloge")
from fabric.api import cd, run, sudo, env, roles, execute from datetime import datetime env.roledefs = { 'webuser': ['bloge@andrewlorente.com'], 'sudoer': ['alorente@andrewlorente.com'], } env.hosts = ['andrewlorente.com'] def deploy(): release_id = datetime.now().strftime("%Y%m%d%H%M%S") execute(build, release_id) execute(release) @roles('webuser') def build(release_id): releases_dir = "/u/apps/bloge/releases/" run("git clone -q https://github.com/AndrewLorente/bloge.git " + releases_dir + release_id) with cd(releases_dir + release_id): run("cabal update") run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v") run("cabal configure") run("cabal build") run("ln -nfs /u/apps/bloge/releases/{0} " "/u/apps/bloge/current".format(release_id)) @roles('sudoer') def release(): sudo("initctl restart bloge")
Fix the `release` step of deploy
Fix the `release` step of deploy lol
Python
mit
ErinCall/bloge
cf026dbabffd92cb51baeb63c1e1e88045e946b9
netfields/forms.py
netfields/forms.py
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return self.python_type(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return IP(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
Fix casting in form to_python() method
Fix casting in form to_python() method NetAddressFormField.to_python() was calling "self.python_type()" to cast the form value to an IP() object. Unfortunately, for is no such method defined here, or in the Django forms.Field() class, at least in 1.4 and up
Python
bsd-3-clause
jmacul2/django-postgresql-netfields
87bd987ebb802200540c23cfccaba2c56a672ed5
openmc/__init__.py
openmc/__init__.py
from openmc.arithmetic import * from openmc.cell import * from openmc.checkvalue import * from openmc.mesh import * from openmc.element import * from openmc.geometry import * from openmc.nuclide import * from openmc.macroscopic import * from openmc.material import * from openmc.plots import * from openmc.region import * from openmc.volume import * from openmc.source import * from openmc.settings import * from openmc.surface import * from openmc.universe import * from openmc.lattice import * from openmc.filter import * from openmc.filter_expansion import * from openmc.trigger import * from openmc.tally_derivative import * from openmc.tallies import * from openmc.mgxs_library import * from openmc.executor import * from openmc.statepoint import * from openmc.summary import * from openmc.particle_restart import * from openmc.mixin import * from openmc.plotter import * from openmc.search import * from openmc.polynomial import * from . import examples # Import a few convencience functions that used to be here from openmc.model import rectangular_prism, hexagonal_prism __version__ = '0.13.0-dev'
from openmc.arithmetic import * from openmc.cell import * from openmc.checkvalue import * from openmc.mesh import * from openmc.element import * from openmc.geometry import * from openmc.nuclide import * from openmc.macroscopic import * from openmc.material import * from openmc.plots import * from openmc.region import * from openmc.volume import * from openmc.source import * from openmc.settings import * from openmc.surface import * from openmc.universe import * from openmc.lattice import * from openmc.filter import * from openmc.filter_expansion import * from openmc.trigger import * from openmc.tally_derivative import * from openmc.tallies import * from openmc.mgxs_library import * from openmc.executor import * from openmc.statepoint import * from openmc.summary import * from openmc.particle_restart import * from openmc.mixin import * from openmc.plotter import * from openmc.search import * from openmc.polynomial import * from . import examples # Import a few names from the model module from openmc.model import rectangular_prism, hexagonal_prism, Model __version__ = '0.13.0-dev'
Make Model available in main openmc namespace
Make Model available in main openmc namespace
Python
mit
amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,walshjon/openmc,amandalund/openmc
3d58796f9bedb607cd2c23aa7dcb6ce86b8af075
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = 'markdown' cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
Add more markdown syntax detection's
Add more markdown syntax detection's Detect 'markdown gfm', 'multimarkdown' and 'markdown extended'. Closes #2
Python
mit
jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint
8b4b5705907e1ec5f9dd3148560dc1bf4cd5b9b7
bin/detail/get_nmake_environment.py
bin/detail/get_nmake_environment.py
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual Studio {} is not installed'.format( vs_path_env, vs_version ) ) vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') if not os.path.isdir(vcvarsall_dir): sys.exit( 'Directory `{}` not exists ' '({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat') if not os.path.isfile(vcvarsall_path): sys.exit( 'File vcvarsall.bat not found in directory ' '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual Studio {} is not installed'.format( vs_path_env, vs_version ) ) if vs_version == '15': vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC', 'Auxiliary', 'Build') else: vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') if not os.path.isdir(vcvarsall_dir): sys.exit( 'Directory `{}` not exists ' '({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat') if not os.path.isfile(vcvarsall_path): sys.exit( 'File vcvarsall.bat not found in directory ' '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])
Fix vcvarsall_dir for Visual Studio 2017
polly.py: Fix vcvarsall_dir for Visual Studio 2017 [skip ci]
Python
bsd-2-clause
idscan/polly,idscan/polly,ruslo/polly,ruslo/polly
07e300e393701d8bddf6646a76542555b92c9f4d
pmxbot/__init__.py
pmxbot/__init__.py
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'irc.freenode.net', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) "The config object" if __name__ == '__main__': importlib.import_module('pmxbot.core').run()
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) "The config object" if __name__ == '__main__': importlib.import_module('pmxbot.core').run()
Use IRC server on localhost by default
Use IRC server on localhost by default
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
b3807e5ddb50ca34af3f4f187bc01fcc284afb20
bin/jenkins.py
bin/jenkins.py
#!/usr/bin/env python3 # Copyright (c) 2014, Ruslan Baratov # All rights reserved. import os import subprocess import sys def run(): toolchain = os.getenv('TOOLCHAIN') if not toolchain: sys.exit('Environment variable TOOLCHAIN is empty') build_type = os.getenv('BUILD_TYPE') if not build_type: sys.exit('Environment variable BUILD_TYPE is empty') build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py') print('Run script: {}'.format(build)) print('Toolchain: {}'.format(toolchain)) print('Config: {}'.format(build_type)) args = [ sys.executable, build, '--toolchain', toolchain, '--config', build_type, '--verbose', '--test' ] try: subprocess.check_call(args) except subprocess.CalledProcessError as error: print(error) print(error.output) sys.exit(1)
#!/usr/bin/env python3 # Copyright (c) 2014, Ruslan Baratov # All rights reserved. import os import subprocess import sys def run(): toolchain = os.getenv('TLC') if not toolchain: sys.exit('Environment variable TLC is empty (TooLChain)') config = os.getenv('CFG') if not config: sys.exit('Environment variable CFG is empty (ConFiG)') build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py') print('Run script: {}'.format(build)) print('Toolchain: {}'.format(toolchain)) print('Config: {}'.format(config)) args = [ sys.executable, build, '--toolchain', toolchain, '--config', config, '--verbose', '--test' ] try: subprocess.check_call(args) except subprocess.CalledProcessError as error: print(error) print(error.output) sys.exit(1)
Use short axis names to prevent windows path overflow
Use short axis names to prevent windows path overflow
Python
bsd-2-clause
headupinclouds/polly,ruslo/polly,headupinclouds/polly,idscan/polly,idscan/polly,headupinclouds/polly,ruslo/polly
92340a1238636d9160ce120cd9a12ed260007aca
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' from . import views, models
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' login_manager.login_message_category = "info" from . import views, models
Add default login manager message category
Add default login manager message category
Python
mit
timzdevz/fm-flask-app
dbfc1a11c0ced8ab7a997944e943a17ff0069199
lexer.py
lexer.py
import ply.lex as lex import re tokens = ( 'SECTION', 'IDENTIFIER', 'LBRACE', 'RBRACE', 'SEMI', 'TRUE', 'FALSE' ) def t_SECTION(t): r'section' return t def t_TRUE(t): r'(true|1)' return t def t_FALSE(t): r'(false|0)' return t def t_IDENTIFIER(t): r'[a-zA-Z\-0-9]+' return t def t_LBRACE(t): r'{' return t def t_RBRACE(t): r'}' return t def t_SEMI(t): r';' return t def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) return t t_ignore = ' \t\n' # Error handling rule def t_error(t): print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno)) t.lexer.skip(1) lexer = lex.lex()
import ply.lex as lex import re tokens = ( 'SECTION', 'IDENTIFIER', 'STRING', 'LBRACE', 'RBRACE', 'SEMI', 'EQU', 'TRUE', 'FALSE' ) def t_SECTION(t): r'section' return t def t_TRUE(t): r'(true|1)' return t def t_FALSE(t): r'(false|0)' return t def t_IDENTIFIER(t): r'[a-zA-Z\-0-9]+' return t def t_STRING(t): r'(\".*\"|\'.*\')' t.value = t.value[1:-1] return t def t_LBRACE(t): r'{' return t def t_EQU(t): r'=' return t def t_RBRACE(t): r'}' return t def t_SEMI(t): r';' return t def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) return t t_ignore = ' \t\n' # Error handling rule def t_error(t): print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno)) t.lexer.skip(1) lexer = lex.lex()
Add rudimentary string support and a token for '=' sign.
Add rudimentary string support and a token for '=' sign.
Python
cc0-1.0
dmbaturin/ply-example
8e28c627c0a84939bb44c2c77fa3e4b3de4932bf
erroneous/models.py
erroneous/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class Error(models.Model): """ Model for storing the individual errors. """ kind = models.CharField(_('type'), null=True, blank=True, max_length=128, db_index=True ) info = models.TextField( null=False, ) data = models.TextField( blank=True, null=True ) path = models.URLField( null=True, blank=True, verify_exists=False, ) when = models.DateTimeField( null=False, auto_now_add=True, db_index=True, ) html = models.TextField( null=True, blank=True, ) modified = models.DateTimeField(auto_now=True) class Meta: """ Meta information for the model. """ verbose_name = _('Error') verbose_name_plural = _('Errors') def __unicode__(self): """ String representation of the object. """ return "%s: %s" % (self.kind, self.info)
from django.db import models from django.utils.translation import ugettext_lazy as _ class Error(models.Model): """ Model for storing the individual errors. """ kind = models.CharField(_('type'), null=True, blank=True, max_length=128, db_index=True ) info = models.TextField( null=False, ) data = models.TextField( blank=True, null=True ) path = models.URLField( null=True, blank=True, ) when = models.DateTimeField( null=False, auto_now_add=True, db_index=True, ) html = models.TextField( null=True, blank=True, ) modified = models.DateTimeField(auto_now=True) class Meta: """ Meta information for the model. """ verbose_name = _('Error') verbose_name_plural = _('Errors') def __unicode__(self): """ String representation of the object. """ return "%s: %s" % (self.kind, self.info)
Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5
Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5
Python
mit
mbelousov/django-erroneous,mbelousov/django-erroneous,mridang/django-erroneous
79d02616ab6d70b029876b8a2de425026e6268c4
pycalc.py
pycalc.py
import sys import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
# vim: set fileencoding=utf-8 import sys if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
Make main program throw warning on python2.
Make main program throw warning on python2.
Python
mit
5225225/pycalc,5225225/pycalc
b636affedea494f1733bf413986a8546d3495c53
chipy_org/apps/meetings/urls.py
chipy_org/apps/meetings/urls.py
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from meetings.views import (PastMeetings, ProposeTopic, MyTopics, RSVP, PastTopics, ) urlpatterns = patterns("", url(r'^past/$', PastMeetings.as_view(), name='past_meetings'), url(r'^rsvp/$', RSVP.as_view(), name='rsvp'), url(r'^rsvp/anonymous/$', RSVP.as_view(), name='anonymous_rsvp'), url(r'^topics/propose$', login_required(ProposeTopic.as_view()), name='propose_topic'), url(r'^topics/mine$', login_required(MyTopics.as_view()), name='my_topics'), url(r'^topics/past$', PastTopics.as_view(), name='past_topics'), )
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from meetings.views import (PastMeetings, ProposeTopic, MyTopics, RSVP, PastTopics, ) urlpatterns = patterns("", url(r'^past/$', PastMeetings.as_view(), name='past_meetings'), url(r'^rsvp/$', RSVP.as_view(), name='rsvp'), url(r'^rsvp/anonymous/$', RSVP.as_view(), name='anonymous_rsvp'), url(r'^rsvp/anonymous/(?P<rsvp_key>[a-z0-1]{40})/$', RSVP.as_view(), name='anonymous_rsvp_with_key'), url(r'^topics/propose$', login_required(ProposeTopic.as_view()), name='propose_topic'), url(r'^topics/mine$', login_required(MyTopics.as_view()), name='my_topics'), url(r'^topics/past$', PastTopics.as_view(), name='past_topics'), )
Add url for anonymous rsvp with key
Add url for anonymous rsvp with key
Python
mit
agfor/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,agfor/chipy.org
ee61dab40c4c3eaa1553397091a17a3292dcf9d6
grako/ast.py
grako/ast.py
from collections import OrderedDict, Mapping import json class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable)
from collections import OrderedDict, Mapping import json __all__ = ['AST'] class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __setitem__(self, key, value): self._elements[key] = value def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable)
Allow to set items in AST.
Allow to set items in AST.
Python
bsd-2-clause
frnknglrt/grako,vmuriart/grako
5442facddbcf9b8adff247edcf3bd27a8fda2c10
great/tap.py
great/tap.py
from __future__ import absolute_import from minion.twisted import MinionResource from twisted.application import strports from twisted.python import usage from twisted.python.filepath import FilePath from twisted.web import server from twisted.web.static import File import twisted.web.resource from great.web import create_app import great class Options(usage.Options): optParameters = [ [ "access-log", "l", None, "Path to web CLF (Combined Log Format) log file for access logs.", ], ["port", "p", "tcp:8080", "The endpoint to listen on."], ] def makeService(options): greatPath = FilePath(great.__file__).parent() staticPath = greatPath.child("static") templatesPath = greatPath.child("templates") rootResource = twisted.web.resource.Resource() rootResource.putChild("", File(staticPath.child("index.html").path)) rootResource.putChild("static", File(staticPath.path)) rootResource.putChild("templates", File(templatesPath.path)) rootResource.putChild("great", MinionResource(create_app())) site = server.Site(rootResource) return strports.service(description=options["port"], factory=site)
from __future__ import absolute_import from minion.twisted import MinionResource from twisted.application import strports from twisted.python import usage from twisted.python.filepath import FilePath from twisted.web import server from twisted.web.static import File import alembic import alembic.config import twisted.web.resource from great.web import create_app import great class Options(usage.Options): optFlags = [ [ "migrate", "", "Run `alembic upgrade head` first to migrate the DB if necessary.", ], ] optParameters = [ [ "access-log", "l", None, "Path to web CLF (Combined Log Format) log file for access logs.", ], ["port", "p", "tcp:8080", "The endpoint to listen on."], ] def makeService(options): if options["migrate"]: alembic_config = alembic.config.Config(FilePath("alembic.ini").path) alembic.command.upgrade(alembic_config, "head") greatPath = FilePath(great.__file__).parent() staticPath = greatPath.child("static") templatesPath = greatPath.child("templates") rootResource = twisted.web.resource.Resource() rootResource.putChild("", File(staticPath.child("index.html").path)) rootResource.putChild("static", File(staticPath.path)) rootResource.putChild("templates", File(templatesPath.path)) rootResource.putChild("great", MinionResource(create_app())) site = server.Site(rootResource) return strports.service(description=options["port"], factory=site)
Add a flag during startup.
Add a flag during startup.
Python
mit
Julian/Great,Julian/Great,Julian/Great
b4613b6b20c6fae1b73095363078201e666bd5bc
djangosaml2/urls.py
djangosaml2/urls.py
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Fix imports for Django 1.6 and above
Fix imports for Django 1.6 and above
Python
apache-2.0
damienmarie-alation/djangosaml2,writepython/djangosaml2,BetterWorks/djangosaml2,knaperek/djangosaml2,writepython/djangosaml2,WebSpider/djangosaml2,knaperek/djangosaml2,MiguelSR/djangosaml2,WebSpider/djangosaml2,BetterWorks/djangosaml2,MiguelSR/djangosaml2,damienmarie-alation/djangosaml2
99ea4348efe1212ddb814680272643829ffabf8f
djangosaml2/urls.py
djangosaml2/urls.py
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Fix imports for Django 1.6 and above
Fix imports for Django 1.6 and above
Python
apache-2.0
City-of-Helsinki/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,advisory/djangosaml2_tenant,GradConnection/djangosaml2,WiserTogether/djangosaml2,City-of-Helsinki/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,kviktor/djangosaml2-py3
22ba81ee7bed81c3a1da4b8d2ace4c38a957b5dd
server.py
server.py
import bottle import waitress import controller import breathe if __name__ == '__main__': bottle_app = bottle.app() breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) waitress.serve(bottle_app, host='0.0.0.0', port=7000)
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, None) @scheduler.scheduled_job(trigger='cron', hour=21, minute=0) def on_job(): """Start at 9:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=23, minute=0) def off_job(): """End at 11:00pm PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm
Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm
Python
mit
tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,YonasBerhe/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse
b8f893089a35627305b2a6dd1f6ba27268f8e865
openphoto/multipart_post.py
openphoto/multipart_post.py
import mimetypes import mimetools def encode_multipart_formdata(params, files): boundary = mimetools.choose_boundary() lines = [] for name in params: lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"" % name) lines.append("") lines.append(str(params[name])) for name in files: filename = files[name] content_type, _ = mimetypes.guess_type(filename) if content_type is None: content_type = "application/octet-stream" lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (name, filename)) lines.append("Content-Type: %s" % content_type) lines.append("") lines.append(open(filename, "rb").read()) lines.append("--" + boundary + "--") lines.append("") body = "\r\n".join(lines) headers = {'Content-Type': "multipart/form-data; boundary=%s" % boundary, 'Content-Length': str(len(body))} return headers, body
import os import mimetypes import mimetools def encode_multipart_formdata(params, files): boundary = mimetools.choose_boundary() lines = [] for name in params: lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"" % name) lines.append("") lines.append(str(params[name])) for name in files: filename = files[name] content_type, _ = mimetypes.guess_type(filename) if content_type is None: content_type = "application/octet-stream" lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (name, filename)) lines.append("Content-Type: %s" % content_type) lines.append("") lines.append(open(os.path.expanduser(filename), "rb").read()) lines.append("--" + boundary + "--") lines.append("") body = "\r\n".join(lines) headers = {'Content-Type': "multipart/form-data; boundary=%s" % boundary, 'Content-Length': str(len(body))} return headers, body
Expand "~" to home path
Expand "~" to home path
Python
apache-2.0
photo/openphoto-python,photo/openphoto-python
605011cbb7953e8629f844d16d62f4632727b023
core/cachecontroller/schedinstances/ArtPackages.py
core/cachecontroller/schedinstances/ArtPackages.py
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'))) return urlsQueue
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 N_DAYS_WINDOW = 14 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=self.N_DAYS_WINDOW)).strftime('%Y-%m-%d'))) return urlsQueue
Increase the timewindow check of ART tests in cachecontroller
Increase the timewindow check of ART tests in cachecontroller
Python
apache-2.0
PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core
a5626b61892549aa376969e44a26c01a69ddd8f8
lib/oeqa/runtime/cases/parselogs_rpi.py
lib/oeqa/runtime/cases/parselogs_rpi.py
from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
Add 5.4 specific error messages to ignore list
oeqa: Add 5.4 specific error messages to ignore list with 5.4 fd580000.genet has been replaced with fd580000.ethernet in the error text Fixes https://github.com/raspberrypi/linux/issues/3884 Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
Python
mit
agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,agherzan/meta-raspberrypi
b4e065bb15cdc7eda91c89fc0bc3472064d5aac0
djangocms_spa/decorators.py
djangocms_spa/decorators.py
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.path cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.get_full_path() cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
Use full path as cache key
Use full path as cache key
Python
mit
dreipol/djangocms-spa,dreipol/djangocms-spa
8a34e665539b10a8e90c86f89a7e2d5881b36519
functional_tests.py
functional_tests.py
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get('http://localhost:8000') # User notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # User is invited to enter a to-do item straight away # User types "Buy peacock feathers" # When user hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list # There is still a text box inviting the user to add another item. # User enters "Use peacock feathers to make a fly" # The page updates again, and now shows both items on their list # User wonders whether the site will remember their list. # Then user sees that the site has generated a unique URL for them # -- there is some explanatory text to that effect. # User visits that URL - their to-do list is still there. # Satisfied, user goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
Add first FT spec comments
Add first FT spec comments
Python
mit
rodowi/remember-the-beer
e53232a0d4118f415f694084deb602bcc05cb635
scripts/server_socket.py
scripts/server_socket.py
# Echo server program import socket HOST = '' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close()
#!/usr/bin/python import socket import rospy from geometry_msgs.msg import ( Twist ) from std_msgs.msg import ( String, ) class SocketListener(object): def __init__(self, host, port, topic): # ROS stuff first rospy.init_node("myo_socket_listener") self._pub = rospy.Publisher(topic, String) # networking stuff later self.host = host self.port = port self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket.bind((self.host, self.port)) self._socket.listen(1) self._conn, self.addr = self._socket.accept() rospy.loginfo("Connected by %s", self.addr) def loop(self): while 1: data = self._conn.recv(1024) s = repr(data) if not data: break rospy.loginfo("Received: %s", s) self._pub.publish(s) self._conn.sendall(data) self._conn.close() def main(): s = SocketListener('', 50007, 'myo_data') s.loop() if __name__ == "__main__": main()
Create class for server and create publisher
Create class for server and create publisher
Python
mit
ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo,ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc
7a408eb5186ef5a7adce026f0629ee1592cd6077
inpassing/config.py
inpassing/config.py
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3' SQLALCHEMY_TRACK_MODIFICATIONS=False
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. import os SECRET_KEY=os.getenv('INPASSING_SECRET_KEY') SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3' SQLALCHEMY_TRACK_MODIFICATIONS=False
Use a secret key (get it from an env var)
Use a secret key (get it from an env var)
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
7c2311534cf1cbef7880795827c88e7ce075e2ae
tests/pthread_barrier/tests/01-run.py
tests/pthread_barrier/tests/01-run.py
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect(f'Start {i + 1}') for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect('Start {}'.format(i + 1)) for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
Remove f string in test
tests/thread_pthread_barrier: Remove f string in test This causes nightlies to fail as the HiL test runners don't have python3.6+
Python
lgpl-2.1
kYc0o/RIOT,OlegHahm/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,jasonatran/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,kaspar030/RIOT,RIOT-OS/RIOT,kYc0o/RIOT,kYc0o/RIOT,ant9000/RIOT,miri64/RIOT,miri64/RIOT,OlegHahm/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,ant9000/RIOT,jasonatran/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,RIOT-OS/RIOT,jasonatran/RIOT,kYc0o/RIOT,RIOT-OS/RIOT,miri64/RIOT,OlegHahm/RIOT,kaspar030/RIOT,ant9000/RIOT,kaspar030/RIOT,kYc0o/RIOT
bfbb685854724285bdbfcd583b3d6c41674a6222
vext/syspy/pyinfo.py
vext/syspy/pyinfo.py
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'], "sys.path": sys.path } return data if __name__ == '__main__': print json.dumps(py_info())
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'].split(os.pathsep), "sys.path": sys.path } return data if __name__ == '__main__': print json.dumps(py_info())
Make sure path is in a list
Make sure path is in a list
Python
mit
stuaxo/vext
fd48bda18bac9fe5380205ba1333af0d4066ae82
tests/test_types.py
tests/test_types.py
import numpy as np from pybotics.types import Vector def test_vector(): x = [1.1, 2.2, 3.3] assert isinstance(x, Vector) x = np.array([1.1, 2.2, 3.3]) assert isinstance(x, Vector) x = (1.1, 2.2, 3.3) assert isinstance(x, Vector) pass
import numpy as np from typing import List from pybotics.types import Vector def test_vector(): pass
Revert "want to be able to test for Vector type"
Revert "want to be able to test for Vector type" This reverts commit 93f09d784a73adcdccef3a77cf8fdc2d12ce4518.
Python
mit
nnadeau/pybotics
436b005217ab92fd06526d9681bc37266c394212
estmator_project/est_quote/views.py
estmator_project/est_quote/views.py
from .models import Quote, Category, Product from django.views.generic.edit import CreateView, UpdateView class QuoteCreateView(CreateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self, form): form = super(QuoteCreateView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteCreateView, self).form_valid(form) class QuoteEditView(UpdateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self, form): form = super(QuoteEditView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteEditView, self).form_valid(form)
from .models import Quote, Category, Product from django.views.generic.edit import CreateView, UpdateView class QuoteCreateView(CreateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self): form = super(QuoteCreateView, self).get_form() # form.fields['category'].queryset = Category.objects.all() # form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteCreateView, self).form_valid(form) class QuoteEditView(UpdateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self): form = super(QuoteEditView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteEditView, self).form_valid(form)
Update view for basic quote form.
Update view for basic quote form.
Python
mit
Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp
9d2161ada6a0d957ca13e49431533770ef672014
files.py
files.py
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1))): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor return samples, fs
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1)), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
Allow mixing the loaded WAV file from stereo to mono.
Allow mixing the loaded WAV file from stereo to mono.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
a4bdb7113dba8ed819d8454a1e8f2916ee33d9a6
dns/exception.py
dns/exception.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNS Exceptions.""" class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" pass class FormError(DNSException): """DNS message is malformed.""" pass class SyntaxError(DNSException): """Text input is malformed.""" pass class UnexpectedEnd(SyntaxError): """Raised if text input ends unexpectedly.""" pass class TooBig(DNSException): """The message is too big.""" pass class Timeout(DNSException): """The operation timed out.""" pass
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNS Exceptions.""" class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" def __init__(self, *args): if args: super(DNSException, self).__init__(*args) else: # doc string is better implicit message than empty string super(DNSException, self).__init__(self.__doc__) class FormError(DNSException): """DNS message is malformed.""" pass class SyntaxError(DNSException): """Text input is malformed.""" pass class UnexpectedEnd(SyntaxError): """Raised if text input ends unexpectedly.""" pass class TooBig(DNSException): """The message is too big.""" pass class Timeout(DNSException): """The operation timed out.""" pass
Support string representation for all DNSExceptions.
Support string representation for all DNSExceptions. Doc string is used in cases where more specific message was not provided during instantiation/raise.
Python
isc
rcorrieri/dnspython,leeclemens/dnspython,Abhayakara/dnspython,fjxhkj/dnspython,tow/dnspython,cluck/dnspython,tomlanyon/dnspython,preo/dnspython
b3b85d3a481e4b2cf9df37666a9527ccf8a13bfc
build/fbcode_builder/specs/fbthrift.py
build/fbcode_builder/specs/fbthrift.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.fmt as fmt import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
Migrate from Folly Format to fmt
Migrate from Folly Format to fmt Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size. Reviewed By: alandau Differential Revision: D14954926 fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
Python
unknown
phoad/rsocket-cpp,rsocket/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,phoad/rsocket-cpp,phoad/rsocket-cpp,rsocket/rsocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp
3dc90a8173dd3520fd4f335efe9adb77b9167f80
setup.py
setup.py
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
Fix data_files to install man and license documents
Setup: Fix data_files to install man and license documents
Python
isc
toddgaunt/imgfetch
f94bc30004aa9977bac652d337f69069efc132bd
marmoset/pxe/__init__.py
marmoset/pxe/__init__.py
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
Implement better result output for pxe config file crete
Python
agpl-3.0
aibor/marmoset
bfbc2bc38cbc7cbcd0afbb8d077fccf1925c0c16
gaphor/SysML/blocks/grouping.py
gaphor/SysML/blocks/grouping.py
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class NodeGroup(AbstractGroup): """ Add node to another node. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class PropertyGroup(AbstractGroup): """ Add Property to a Block. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
Fix name for property/block group
Fix name for property/block group
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
a48eb39dacba67b4c8638664c9df717837099c05
genthreads/actor.py
genthreads/actor.py
from multiprocessing import process class Actor(process.BaseProcess): def __init__(self): super(Actor, self).__init__() self._inbox = list() def send(self, value): self._inbox.append(value) @property def inbox(self): return self._inbox
from multiprocessing import Process class Actor(Process): def __init__(self): super(Actor, self).__init__() self._inbox = list() def send(self, value): self._inbox.append(value) @property def inbox(self): return self._inbox
Change BaseProcess to Process as a parent class for Actor
Change BaseProcess to Process as a parent class for Actor
Python
mit
f1sty/genthreads
04f3003c8ac261edd862323624bbdba565b9e36c
download.py
download.py
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) jsondata = resp.read() data = json.loads(jsondata) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
Remove jsondata variable to simplify the code
Remove jsondata variable to simplify the code
Python
mit
bangbangbear/ximalayaDownloader
7d82f3accce0cf174fd7cf176d5c289ffc791647
ds_queue.py
ds_queue.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): queue = Queue() print('Is empty: {}'.format(queue.is_empty())) print('Enqueue "dog", 4 & 8.4') queue.enqueue('dog') queue.enqueue(4) queue.enqueue(8.4) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Dequeue: {}'.format(queue.dequeue())) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Show: {}'.format(queue.show())) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def peek(self): return self.items[-1] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): q = Queue() print('Is empty: {}'.format(q.is_empty())) print('Enqueue "dog", 4 & 8.4') q.enqueue('dog') q.enqueue(4) q.enqueue(8.4) print(q.peek()) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Dequeue: {}'.format(q.dequeue())) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Show: {}'.format(q.show())) if __name__ == '__main__': main()
Revise Queue instance to q
Revise Queue instance to q
Python
bsd-2-clause
bowen0701/algorithms_data_structures
2916006bf7dc9a689a9ab5678d37a858d380345e
api/migrations/0002_migrate_legacy.py
api/migrations/0002_migrate_legacy.py
from django.apps import apps as global_apps from django.db import migrations from django.db.utils import OperationalError sql = ''' ''' reverse_sql = ''' ''' def forwards(app, schema_editor): models = app.all_models['api'] try: schema_editor.execute('alter table south_migrationhistory rename to legacy_south_migrationhistory;') print 'Found legacy application' for model in models: schema_editor.execute('drop table api_{0};'.format(model)) schema_editor.execute('alter table portal_{0} rename to api_{0};'.format(model)) except Exception as e: pass def backwards(app, schema_editor): models = app.all_models['api'] try: schema_editor.execute('alter table legacy_south_migrationhistory rename to south_migrationhistory;') print 'Found migrated application' for model in models: schema_editor.execute('alter table api_{0} rename to portal_{0};'.format(model)) except Exception as e: pass class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, backwards), ] dependencies = [ ('api', '0001_initial'), ]
from django.apps import apps as global_apps from django.db import migrations from django.db.utils import OperationalError from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PgSE sql = ''' ''' reverse_sql = ''' ''' def forwards(app, schema_editor): models = app.all_models['api'] if not isinstance(schema_editor, PgSE): print 'this migration is only guaranteed to work with Postgres!' return try: schema_editor.execute('alter table south_migrationhistory rename to legacy_south_migrationhistory;') print 'Found legacy application' for model in models: schema_editor.execute('drop table api_{0} cascade;'.format(model)) schema_editor.execute('alter table portal_{0} rename to api_{0};'.format(model)) schema_editor.execute('alter sequence portal_{0}_id_seq rename to api_{0}_id_seq;'.format(model)) except Exception as e: pass def backwards(app, schema_editor): models = app.all_models['api'] if not isinstance(schema_editor, PgSE): print 'this migration is only guaranteed to work with Postgres!' return try: schema_editor.execute('alter table legacy_south_migrationhistory rename to south_migrationhistory;') print 'Found migrated application' for model in models: schema_editor.execute('alter table api_{0} rename to portal_{0};'.format(model)) schema_editor.execute('alter sequence api_{0}_id_seq rename to portal_{0}_id_seq;'.format(model)) except Exception as e: pass class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, backwards), ] dependencies = [ ('api', '0001_initial'), ]
Update migration to check for Postgres as target
Update migration to check for Postgres as target
Python
bsd-2-clause
chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal
f94347a734df84811b627e767a55dc99831e0076
src/models.py
src/models.py
from flask_sqlalchemy import Model from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey from sqlalchemy.orm import relationship class User(Model): __tablename__ = "user" ROLE_ADMIN = 0 ROLE_USER = 1 id = Column(Integer, primary_key=True) name = Column(Unicode(64), index=True) username = Column(Unicode(20), index=True) password_hash = Column(Unicode(120)) role = Column(Integer, default=ROLE_USER) postings = relationship("Posting", backref="user") class Posting(Model): __tablename__ = "posting" id = Column(Integer, primary_key=True) title = Column(Unicode(64), index=True) description = Column(1200) price = Column(Integer, default=100) user_id = ForeignKey("user.id", index=True)
from flask_sqlalchemy import Model from __init__ import db class User(Model): __tablename__ = "user" ROLE_ADMIN = 0 ROLE_USER = 1 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(64), index=True) username = db.Column(db.Unicode(20), index=True) password_hash = db.Column(db.Unicode(120)) role = db.Column(db.Integer, default=ROLE_USER) postings = db.relationship("Posting", backref="user") class Posting(Model): __tablename__ = "posting" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Unicode(64), index=True) description = db.Column(1200) price = db.Column(db.Integer, default=100) user_id = db.ForeignKey("user.id", index=True)
Use local database namespace instead of package.
Use local database namespace instead of package.
Python
mit
BrambleLLC/Artizanz,BrambleLLC/Artizanz,BrambleLLC/Artizanz
12bb9882c1e2cc3f04b7bef30d4aaf8267793622
opps/images/tests/__init__.py
opps/images/tests/__init__.py
# -*- coding: utf-8 -*- from opps.images.tests.generate import *
# -*- coding: utf-8 -*- from opps.images.tests.generate import * from opps.images.tests.test_models import *
Add test_models on image test init
Add test_models on image test init
Python
mit
williamroot/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps
7606689e5d83a6c3bfa71ede25e4b92978d94bd4
hdbscan/__init__.py
hdbscan/__init__.py
from .hdbscan_ import HDBSCAN, hdbscan from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
from .hdbscan_ import HDBSCAN, hdbscan from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage from .validity import validity_index
Add validity_index to default imports.
Add validity_index to default imports.
Python
bsd-3-clause
scikit-learn-contrib/hdbscan,scikit-learn-contrib/hdbscan,lmcinnes/hdbscan,lmcinnes/hdbscan
f8b52162748ccf62db881fad101e6a91ed014bd4
plugins/Hitman_Codename_47.py
plugins/Hitman_Codename_47.py
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
Add backuping config files for Hitman: Codename 47
Add backuping config files for Hitman: Codename 47
Python
mit
Pr0Ger/SGSB
85542282162158e9e3d0ff339ee67d7809fb2a3c
src/models.py
src/models.py
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_website_table(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True)
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_db_tables(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True) class WebsitesContent(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites_content" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=False) words = Column('words', ARRAY(String), nullable=False)
Add model for storing words.
Add model for storing words.
Python
mit
piatra/ssl-project
f9f65019230f8c694a61053d571093cd87db4950
setup.py
setup.py
from distutils.core import setup setup( name = 'gdaxcli', packages = ['gdaxcli'], version = '0.1', description = 'Commandline client for trading on GDAX', author = 'Son Pham', author_email = 'sp@sonpham.me', url = 'https://github.com/sonph/gdaxcli', download_url = 'https://github.com/sonph/gdaxcli/archive/0.1.0.zip', keywords = ['gdax', 'cli', 'tool', 'client', 'cryptocurrency', 'bitcoin', 'ethereum', 'trading'], classifiers = [], ) # To upload to PyPI: # python setup.py register -r pypi # python setup.py sdist upload -r pypi
from distutils.core import setup setup( name = 'gdaxcli', packages = ['gdaxcli'], version = '0.1', description = 'Commandline client for trading on GDAX', author = 'Son Pham', author_email = 'sp@sonpham.me', url = 'https://github.com/sonph/gdaxcli', download_url = 'https://github.com/sonph/gdaxcli/archive/0.1.0.zip', keywords = ['gdax', 'cli', 'tool', 'client', 'cryptocurrency', 'bitcoin', 'ethereum', 'trading'], classifiers = [], ) # To upload to testpypi.python.org: # python setup.py register -r pypitest # python setup.py sdist upload -r pypitest # To upload to pypi.python.org: # python setup.py register -r pypi # python setup.py sdist upload -r pypi
Add instructions for uploading to pypitest
Add instructions for uploading to pypitest
Python
mit
sonph/gdaxcli,sonph/gdaxcli
542ab347d5a0195c88be212d966253d4385b8af5
api.py
api.py
import webapp2 from google.appengine.api import channel from google.appengine.api import users open_channels = set() class ChannelDidConnect(webapp2.RequestHandler): def post(self): print "Got connection" open_channels.add(self.request.get("from")) class ChannelDisconnect(webapp2.RequestHandler): def post(self): print "Got disconnection" channelId = self.request.get("from") if channelId in open_channels: open_channels.remove(channelId) class ChannelRequest(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({"token": ""}) return token = channel.create_channel(user.user_id()) self.response.write( "{\"token\": \"%s\"}" % token ) class Message(webapp2.RequestHandler): def post(self): # Only accept messages from logged in users user = users.get_current_user() if not user: return print open_channels for channelId in open_channels: channel.send_message(channelId, "message=%s&author=%s" % (self.request.POST["message"], self.request.POST["author"])) app = webapp2.WSGIApplication([ ('/api/channel', ChannelRequest), ('/api/message', Message), ('/_ah/channel/connected/', ChannelDidConnect), ('/_ah/channel/disconnected/', ChannelDisconnect), ])
import webapp2 from google.appengine.api import channel from google.appengine.api import users open_channels = set() class ChannelDidConnect(webapp2.RequestHandler): def post(self): print "Got connection" open_channels.add(self.request.get("from")) class ChannelDisconnect(webapp2.RequestHandler): def post(self): print "Got disconnection" channelId = self.request.get("from") if channelId in open_channels: open_channels.remove(channelId) class ChannelRequest(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({"token": ""}) return token = channel.create_channel(user.user_id()) self.response.write( "{\"token\": \"%s\"}" % token ) class Message(webapp2.RequestHandler): def post(self): self.handleRequest() def get(self): self.handleRequest() def handleRequest(self): print open_channels for channelId in open_channels: channel.send_message(channelId, "message=%s&author=%s" % (self.request.params["message"], self.request.params["author"])) app = webapp2.WSGIApplication([ ('/api/channel', ChannelRequest), ('/api/message', Message), ('/_ah/channel/connected/', ChannelDidConnect), ('/_ah/channel/disconnected/', ChannelDisconnect), ])
Allow messages to come in through GET
Allow messages to come in through GET
Python
mit
misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample
c69b7b80c75e170f1b83d1204fb531544a9fc831
rpifake/__init__.py
rpifake/__init__.py
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
Make override more global, not just within patch scope
Make override more global, not just within patch scope
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
9a2e56c5721fad4df75339feac6676897f40ac01
src/tpn/data_io.py
src/tpn/data_io.py
#!/usr/bin/env python import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w') print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} for key in track[0]: track_obj[key] = np.asarray([box[key] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close()
#!/usr/bin/env python import zipfile import cPickle import numpy as np """ track_obj: { frames: 1 by n numpy array, anchors: 1 by n numpy array, features: m by n numpy array, scores: c by n numpy array, boxes: 4 by n numpy array, rois: 4 by n numpy array } """ def save_track_proto_to_zip(track_proto, save_file): zf = zipfile.ZipFile(save_file, 'w', allowZip64=True) print "Writing to zip file {}...".format(save_file) for track_id, track in enumerate(track_proto['tracks']): track_obj = {} for key in track[0]: track_obj[key] = np.asarray([box[key] for box in track]) zf.writestr('{:06d}.pkl'.format(track_id), cPickle.dumps(track_obj, cPickle.HIGHEST_PROTOCOL)) if (track_id + 1) % 1000 == 0: print "\t{} tracks written.".format(track_id + 1) print "\tTotally {} tracks written.".format(track_id + 1) zf.close()
Enable zip64 to store tracks larger than 2GB.
Enable zip64 to store tracks larger than 2GB.
Python
mit
myfavouritekk/TPN
59d44ba76a9b2f98375fa2f893dabc0376de6f82
localeurl/models.py
localeurl/models.py
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse if settings.USE_I18N: patch_reverse()
from django.conf import settings from django.core import urlresolvers from django.utils import translation from django.contrib.auth import views as auth_views from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse def redirect_to_login(next, login_url, *args, **kwargs): if not login_url: login_url = settings.LOGIN_URL login_url = utils.locale_url(login_url, translation.get_language()) return django_redirect_to_login(next, login_url, *args, **kwargs) django_redirect_to_login = None def patch_redirect_to_login(): """ Monkey-patches the redirect_to_login function. Will not patch twice. """ global django_redirect_to_login if auth_views.redirect_to_login is not redirect_to_login: django_redirect_to_login = auth_views.redirect_to_login auth_views.redirect_to_login = redirect_to_login if settings.USE_I18N: patch_reverse() patch_redirect_to_login()
Patch redirect_to_login to maintain locale
Patch redirect_to_login to maintain locale Signed-off-by: Simon Luijk <088e16a1019277b15d58faf0541e11910eb756f6@simonluijk.com>
Python
mit
simonluijk/django-localeurl
7cd3cc1a6a023a093c9c6d8df4dd1b9d6c871faa
auto/src/rabird/auto/mouse_xdotool.py
auto/src/rabird/auto/mouse_xdotool.py
''' @date 2015-02-21 @author Hong-She Liang <starofrainnight@gmail.com> ''' import os import re import subprocess from .mouse_constant import * class Mouse(object): ## return current mouse absolute position @classmethod def position(cls): p = subprocess.Popen(["xdotool", "getmouselocation"], stdout=subprocess.PIPE) output = p.communicate()[0] matched = re.match(".*x:(\d+)\s*y:(\d+)\s*.*", output) return [int(matched.group(1)), int(matched.group(2))] @classmethod def move(cls, position): os.system("xdotool mousemove --sync %s %s" % (int(position[0]), int(position[1]))) ## @classmethod def button_up(cls, button_type = ButtonType.LEFT ): if ButtonType.LEFT == button_type: os.system("xdotool mouseup 1") elif ButtonType.RIGHT == button_type: os.system("xdotool mouseup 3") elif ButtonType.MIDDLE == button_type: os.system("xdotool mouseup 2") @classmethod def button_down(cls, button_type = ButtonType.LEFT ): if ButtonType.LEFT == button_type: os.system("xdotool mousedown 1") elif ButtonType.RIGHT == button_type: os.system("xdotool mousedown 3") elif ButtonType.MIDDLE == button_type: os.system("xdotool mousedown 2")
''' @date 2015-02-21 @author Hong-She Liang <starofrainnight@gmail.com> ''' import os import re import subprocess from .mouse_constant import * class Mouse(object): ## return current mouse absolute position @classmethod def position(cls): output = subprocess.check_output(["xdotool", "getmouselocation"]) matched = re.match(".*x:(\d+)\s*y:(\d+)\s*.*", output) return [int(matched.group(1)), int(matched.group(2))] @classmethod def move(cls, position): subprocess.call(["xdotool", "mousemove", "--sync", position[0], position[1]]) ## @classmethod def button_up(cls, button_type = ButtonType.LEFT ): if ButtonType.LEFT == button_type: subprocess.call(["xdotool", "mouseup", "1"]) elif ButtonType.RIGHT == button_type: subprocess.call(["xdotool", "mouseup", "3"]) elif ButtonType.MIDDLE == button_type: subprocess.call(["xdotool", "mouseup", "2"]) @classmethod def button_down(cls, button_type = ButtonType.LEFT ): if ButtonType.LEFT == button_type: subprocess.call(["xdotool", "mousedown", "1"]) elif ButtonType.RIGHT == button_type: subprocess.call(["xdotool", "mousedown", "3"]) elif ButtonType.MIDDLE == button_type: subprocess.call(["xdotool", "mousedown", "2"])
Convert all os.system() to subprocess.check_output().
Convert all os.system() to subprocess.check_output().
Python
apache-2.0
starofrainnight/rabird.core,starofrainnight/rabird.auto
ad069a50ec7a4b4e6b1dac679e071279e128c824
been/source/markdowndirectory.py
been/source/markdowndirectory.py
from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown # slugify from Django source (BSD license) def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) event['content'] = md.convert(event['raw']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['raw'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory)
from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown # slugify from Django source (BSD license) def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) event['content'] = md.convert(event['raw']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['author'] = ' '.join(md.Meta.get('author', [''])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['raw'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory)
Allow MarkdownDirectory events to specify author.
Allow MarkdownDirectory events to specify author.
Python
bsd-3-clause
chromakode/been
f286dc748670c67845df226ca7d400e745dd502f
awx/main/notifications/email_backend.py
awx/main/notifications/email_backend.py
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import pprint from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host", "type": "string"}, "port": {"label": "Port", "type": "int"}, "username": {"label": "Username", "type": "string"}, "password": {"label": "Password", "type": "password"}, "use_tls": {"label": "Use TLS", "type": "bool"}, "use_ssl": {"label": "Use SSL", "type": "bool"}, "sender": {"label": "Sender Email", "type": "string"}, "recipients": {"label": "Recipient List", "type": "list"}} recipient_parameter = "recipients" sender_parameter = "sender" def format_body(self, body): body_actual = smart_text("{} #{} had status {} on Ansible Tower, view details at {}\n\n".format(body['friendly_name'], body['id'], body['status'], body['url'])) body_actual += pprint.pformat(body, indent=4) return body_actual
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import pprint from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host", "type": "string"}, "port": {"label": "Port", "type": "int"}, "username": {"label": "Username", "type": "string"}, "password": {"label": "Password", "type": "password"}, "use_tls": {"label": "Use TLS", "type": "bool"}, "use_ssl": {"label": "Use SSL", "type": "bool"}, "sender": {"label": "Sender Email", "type": "string"}, "recipients": {"label": "Recipient List", "type": "list"}} recipient_parameter = "recipients" sender_parameter = "sender" def format_body(self, body): if "body" in body: body_actual = body['body'] else: body_actual = smart_text("{} #{} had status {} on Ansible Tower, view details at {}\n\n".format(body['friendly_name'], body['id'], body['status'], body['url'])) body_actual += pprint.pformat(body, indent=4) return body_actual
Fix an issue with the email notifier
Fix an issue with the email notifier Incorrect body format assumptions in the email notifier
Python
apache-2.0
wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx
ae1c6c020225423bcfaff5b3c830345467d87b2d
tedx/views.py
tedx/views.py
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import RegistrationForm from .models import Registration import utils def handle_registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): registration = form.save(commit=False) # If user is logged-in, let's try sending a tweet! if request.user.is_authenticated(): registration.user = request.user utils.create_tweet(request.user) registration.save() return HttpResponseRedirect(reverse('tedx:thanks')) else: form = RegistrationForm() context = {'form': form} return render(request, 'tedx/index.html', context) def list_registration(request): list_registration = Registration.objects.all() context = {'list_registration' : list_registration} return render(request, 'tedx/list_registration.html', context)
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect from django.shortcuts import render from clubs.models import Team from .forms import RegistrationForm from .models import Registration import utils def handle_registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): registration = form.save(commit=False) # If user is logged-in, let's try sending a tweet! if request.user.is_authenticated(): registration.user = request.user utils.create_tweet(request.user) registration.save() return HttpResponseRedirect(reverse('tedx:thanks')) else: form = RegistrationForm() context = {'form': form} return render(request, 'tedx/index.html', context) @login_required def list_registration(request): tedx_team = Team.objects.get(code_name="tedx_2017_registration") is_tedx_member = tedx_team.members.filter(pk=request.user.pk).exists() or\ tedx_team.coordinator == request.user if not request.user.is_superuser and\ not is_tedx_member: raise PermissionDenied list_registration = Registration.objects.all() context = {'list_registration' : list_registration} return render(request, 'tedx/list_registration.html', context)
Add permission check for TEDx
Add permission check for TEDx
Python
agpl-3.0
osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz
a47ab820870caebcc00daf32531cfad3abd2e532
src/engine/SCons/Platform/darwin.py
src/engine/SCons/Platform/darwin.py
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004 Steven Knight # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib'
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib'
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
Python
mit
andrewyoung1991/scons,timj/scons,timj/scons,andrewyoung1991/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,andrewyoung1991/scons,timj/scons,timj/scons,andrewyoung1991/scons,timj/scons
a2430b67423ce036d2a96541e86d356ace04db69
Twitch/cogs/words.py
Twitch/cogs/words.py
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) else: await ctx.send("Definition not found.")
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
Use f-string for define command
[TwitchIO] Use f-string for define command
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
7be606951b22d77a53274d014cd94aae30af93f5
samples/oauth2_for_devices.py
samples/oauth2_for_devices.py
# -*- coding: utf-8 -*- # See: https://developers.google.com/accounts/docs/OAuth2ForDevices import httplib2 from six.moves import input from oauth2client.client import OAuth2WebServerFlow from googleapiclient.discovery import build CLIENT_ID = "some+client+id" CLIENT_SECRET = "some+client+secret" SCOPES = ("https://www.googleapis.com/auth/youtube",) flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES)) # Step 1: get user code and verification URL # https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode flow_info = flow.step1_get_device_and_user_codes() print "Enter the following code at %s: %s" % (flow_info.verification_url, flow_info.user_code) print "Then press Enter." input() # Step 2: get credentials # https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken credentials = flow.step2_exchange(device_flow_info=flow_info) print "Access token:", credentials.access_token print "Refresh token:", credentials.refresh_token # Get YouTube service # https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
# -*- coding: utf-8 -*- # See: https://developers.google.com/accounts/docs/OAuth2ForDevices import httplib2 from six.moves import input from oauth2client.client import OAuth2WebServerFlow from googleapiclient.discovery import build CLIENT_ID = "some+client+id" CLIENT_SECRET = "some+client+secret" SCOPES = ("https://www.googleapis.com/auth/youtube",) flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES)) # Step 1: get user code and verification URL # https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode flow_info = flow.step1_get_device_and_user_codes() print("Enter the following code at {0}: {1}".format(flow_info.verification_url, flow_info.user_code)) print("Then press Enter.") input() # Step 2: get credentials # https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken credentials = flow.step2_exchange(device_flow_info=flow_info) print("Access token: {0}".format(credentials.access_token)) print("Refresh token: {0}".format(credentials.refresh_token)) # Get YouTube service # https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
Fix example to be Python3 compatible, use format()
Fix example to be Python3 compatible, use format() Both print() and format() are compatible from 2.6. Also, format() is much nicer to use for internationalization since you can define the location of your substitutions. It works similarly to Java and .net's format() as well. Great stuff! Should I tackle the other examples as well, or is piece meal all right?
Python
apache-2.0
googleapis/oauth2client,jonparrott/oauth2client,google/oauth2client,jonparrott/oauth2client,clancychilds/oauth2client,googleapis/oauth2client,google/oauth2client,clancychilds/oauth2client
033ee318e6694ca4b251adf759d8cb62a100fdca
tickertape.py
tickertape.py
#!/usr/bin/env python """Display stock quotes on LEDs.""" import RPi.GPIO as GPIO from seven_segment import print_leds from ystockquote import get_price, get_change pins = [17, 23, 24, 22, 27, 25, 5] GPIO.setmode(GPIO.BCM) GPIO.setup(pins, GPIO.OUT) print_leds(' ') symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK'] ticker_string = '' print "Downloading", len(symbols), "symbols..." for s in symbols: ticker_string += (s + ' ' + get_price(s) + ' ' + get_change(s) + ' ') print "Done!" print_leds(ticker_string, pins, 1) #print_leds('try', pins, 1) GPIO.cleanup()
#!/usr/bin/env python """Display stock quotes on LEDs.""" import RPi.GPIO as GPIO from seven_segment import print_leds from ystockquote import get_price, get_change pins = [17, 23, 24, 22, 27, 25, 5] GPIO.setmode(GPIO.BCM) GPIO.setup(pins, GPIO.OUT) print_leds(' ', pins) symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK'] for s in symbols: try: ticker_string = s + ' ' + get_price(s) + ' ' + get_change(s) + ' ' except KeyboardInterrupt: break print_leds(ticker_string, pins, 1) GPIO.cleanup()
Improve ctrl-c handling. Fix the clear-display line.
Improve ctrl-c handling. Fix the clear-display line.
Python
mit
zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie
18b4d5196fe18479e4aedfaa9030e5ba443d6a85
test_input/test70.py
test_input/test70.py
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1: print x break return 0 def func3(x): 'should produce a warning' if 21: return 1 if 31: return 2 assert(x, 'test') assert(5, 'test') assert 5, 'test' if 'str': return 3 return 4 def func4(x): 'should not produce a warning' if x == 204 or x == 201 or 200 <= x < 300: x = 0 if x == 1: pass while x == 'str': print x break return 0
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1: print x break return 0 def func3(x): 'should produce a warning' if 21: return 1 if 31: return 2 assert(x, 'test') assert(5, 'test') assert 5, 'test' if 'str': return 3 return 4 def func4(x): 'should not produce a warning' if x == 204 or x == 201 or 200 <= x < 300: x = 0 if x == 1: pass while x == 'str': print x break return 0 def func5(need_quotes, text): 'should not produce a warning' return (need_quotes) and ('"%s"' % text) or (text)
Fix a problem reported by Greg Ward and pointed out by John Machin when doing:
Fix a problem reported by Greg Ward and pointed out by John Machin when doing: return (need_quotes) and ('"%s"' % text) or (text) The following warning was generated: Using a conditional statement with a constant value ("%s") This was because even the stack wasn't modified after a BINARY_MODULO to say the value on the stack was no longer const.
Python
bsd-3-clause
mitar/pychecker,mitar/pychecker
1f7f058d97c6599401558a280d85affed7fb5394
testing/hdiv_proj.py
testing/hdiv_proj.py
from __future__ import absolute_import, print_function, division from firedrake import * mesh = UnitSquareMesh(2, 2) RT = FiniteElement("RT", triangle, 1) V = FunctionSpace(mesh, RT) u = TrialFunction(V) v = TestFunction(V) f = Function(V) x = SpatialCoordinate(mesh) f.project(as_vector([x[1], x[0]])) r = Function(V) a = inner(u, v)*dx L = inner(f, v)*dx solve(a == L, r) V_d = FunctionSpace(mesh, BrokenElement(RT)) phi_d = TestFunction(V_d) r_d = assemble(inner(r, phi_d)*dx) ref = assemble(inner(f, phi_d)*dx) print(errornorm(r_d, ref))
from __future__ import absolute_import, print_function, division from firedrake import * mesh = UnitSquareMesh(2, 2) RT = FiniteElement("RT", triangle, 1) V = FunctionSpace(mesh, RT) u = TrialFunction(V) v = TestFunction(V) f = Function(V) x = SpatialCoordinate(mesh) assemble(42*dot(v, FacetNormal(mesh))*ds, tensor=f) r = Function(V) a = inner(u, v)*dx L = inner(f, v)*dx solve(a == L, r) V_d = FunctionSpace(mesh, BrokenElement(RT)) phi_d = TestFunction(V_d) r_d = assemble(inner(r, phi_d)*dx) ref = assemble(inner(f, phi_d)*dx) projection_rd = project(f, V_d) print(errornorm(r_d, ref))
Update projection experiment for HDiv functions
Update projection experiment for HDiv functions
Python
mit
thomasgibson/firedrake-hybridization
b172ee1c1ed76836e570e08f0624a456c07cc388
get_max_audio.py
get_max_audio.py
""" Test obtaining peak audio values with PyAV: time python pyav_audio_vol.py ~/Videos/sample.mp4 Reference: https://ffmpeg.org/doxygen/trunk/group__lavu__sampfmts.html """ import sys import av import numpy as np # import matplotlib.pyplot as plt video_file = sys.argv[1] container = av.open(video_file) audioStream = container.streams.audio[0] audio_max = np.fromiter((np.abs(frame.to_ndarray()).max() for frame in container.decode(audioStream)), np.float) print(audio_max.max()) # with open("out.bin", "bw") as out_f: # np.save(out_f,audio_max) # plt.plot(audio_max) # plt.show()
""" Test obtaining peak audio values with PyAV: time python pyav_audio_vol.py ~/Videos/sample.mp4 Reference: https://ffmpeg.org/doxygen/trunk/group__lavu__sampfmts.html """ import sys import av import numpy as np import matplotlib.pyplot as plt video_file = sys.argv[1] container = av.open(video_file) audioStream = container.streams.audio[0] def rms(x): # https://stackoverflow.com/a/28398092 o_O noice! return np.sqrt(np.vdot(x, x)/x.size) audio_max = np.fromiter((rms(frame.to_ndarray()) for frame in container.decode(audioStream)), np.float) print(audio_max.max()) # with open("out.bin", "bw") as out_f: # np.save(out_f,audio_max) plt.plot(audio_max) plt.show()
Use RMS for better filtering
Use RMS for better filtering
Python
bsd-2-clause
yan123/BitBox,yan123/QABox,yan123/QABox
0d90da8fca411033d66c3a82096a67e12fca830e
util/time_multi.py
util/time_multi.py
#!/usr/bin/python # # Small helper for perftest runs. # import os import sys import subprocess def main(): count = int(sys.argv[1]) time_min = None for i in xrange(count): cmd = [ 'time', '-f', '%U', '--quiet', sys.argv[2], # cmd sys.argv[3] # testcase ] #print(repr(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() retval = p.wait() #print(i, retval, stdout, stderr) if retval != 0: print 'n/a' return time = float(stderr) #print(i, time) if time_min is None: time_min = time else: time_min = min(time_min, time) # /usr/bin/time has only two digits of resolution print('%.02f' % time_min) if __name__ == '__main__': main()
#!/usr/bin/python # # Small helper for perftest runs. # import os import sys import subprocess def main(): count = int(sys.argv[1]) time_min = None for i in xrange(count): cmd = [ 'time', '-f', '%U', '--quiet', sys.argv[2], # cmd sys.argv[3] # testcase ] #print(repr(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() retval = p.wait() #print(i, retval, stdout, stderr) if retval == 139: print 'segv' sys.exit(1) elif retval != 0: print 'n/a' sys.exit(1) time = float(stderr) #print(i, time) if time_min is None: time_min = time else: time_min = min(time_min, time) # /usr/bin/time has only two digits of resolution print('%.02f' % time_min) sys.exit(0) if __name__ == '__main__': main()
Add exitcode and segv check for timing util
Add exitcode and segv check for timing util
Python
mit
reqshark/duktape,jmptrader/duktape,harold-b/duktape,chenyaqiuqiu/duktape,harold-b/duktape,nivertech/duktape,zeropool/duktape,harold-b/duktape,zeropool/duktape,harold-b/duktape,chenyaqiuqiu/duktape,jmptrader/duktape,harold-b/duktape,chenyaqiuqiu/duktape,kphillisjr/duktape,skomski/duktape,nivertech/duktape,skomski/duktape,zeropool/duktape,kphillisjr/duktape,tassmjau/duktape,eddieh/duktape,reqshark/duktape,markand/duktape,jmptrader/duktape,svaarala/duktape,skomski/duktape,svaarala/duktape,nivertech/duktape,tassmjau/duktape,eddieh/duktape,nivertech/duktape,zeropool/duktape,zeropool/duktape,sloth4413/duktape,nivertech/duktape,tassmjau/duktape,eddieh/duktape,sloth4413/duktape,chenyaqiuqiu/duktape,eddieh/duktape,reqshark/duktape,nivertech/duktape,tassmjau/duktape,markand/duktape,reqshark/duktape,reqshark/duktape,jmptrader/duktape,jmptrader/duktape,harold-b/duktape,eddieh/duktape,nivertech/duktape,sloth4413/duktape,harold-b/duktape,zeropool/duktape,markand/duktape,tassmjau/duktape,tassmjau/duktape,skomski/duktape,markand/duktape,reqshark/duktape,nivertech/duktape,markand/duktape,eddieh/duktape,kphillisjr/duktape,sloth4413/duktape,kphillisjr/duktape,svaarala/duktape,chenyaqiuqiu/duktape,eddieh/duktape,svaarala/duktape,kphillisjr/duktape,skomski/duktape,sloth4413/duktape,svaarala/duktape,zeropool/duktape,skomski/duktape,chenyaqiuqiu/duktape,jmptrader/duktape,jmptrader/duktape,sloth4413/duktape,eddieh/duktape,sloth4413/duktape,reqshark/duktape,jmptrader/duktape,kphillisjr/duktape,harold-b/duktape,nivertech/duktape,nivertech/duktape,chenyaqiuqiu/duktape,svaarala/duktape,kphillisjr/duktape,svaarala/duktape,markand/duktape,svaarala/duktape,svaarala/duktape,harold-b/duktape,zeropool/duktape,chenyaqiuqiu/duktape,kphillisjr/duktape,skomski/duktape,kphillisjr/duktape,reqshark/duktape,skomski/duktape,jmptrader/duktape,reqshark/duktape,sloth4413/duktape,markand/duktape,tassmjau/duktape,markand/duktape,skomski/duktape,tassmjau/duktape,zeropool/duktape,skomski/duktape,sloth4413/duktape,eddieh/duktape,chenyaqiuqiu/duktape,tassmjau/duktape,tassmjau/duktape,jmptrader/duktape,sloth4413/duktape,zeropool/duktape,chenyaqiuqiu/duktape,kphillisjr/duktape,eddieh/duktape,reqshark/duktape,markand/duktape,harold-b/duktape,markand/duktape
3d7459f7b1d40bb94a64d3f08d41942feabf4c12
manager/jobs/migrations/0003_auto_20200723_0219.py
manager/jobs/migrations/0003_auto_20200723_0219.py
# Generated by Django 3.0.8 on 2020-07-23 02:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.AlterField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
# Generated by Django 3.0.8 on 2020-07-23 02:19. # Manually modified by Nokome Bentley on 2020-11-09 because the original # `AlterField` operation was causing the following error on Postgres: # django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint # In production, that error had to be dealt with manually, but it still # meant that creating a new Postgres DB (e.g. in development) would fail. # Therefore, it was changes to a `RemoveField` + `CreateField`. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.RemoveField( model_name='job', name='id', ), migrations.AddField( model_name='job', name='id', field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False), ), migrations.AlterField( model_name='job', name='method', field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32), ), ]
Allow migration to run on Postgres
chore(Jobs): Allow migration to run on Postgres
Python
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
5b8edee2b6fa13fc1b05e15961d8b7920e6f9739
csunplugged/general/urls.py
csunplugged/general/urls.py
"""URL routing for the general application.""" from django.conf.urls import url from . import views urlpatterns = [ url(r"^$", views.GeneralIndexView.as_view(), name="home"), url(r"^about/$", views.GeneralAboutView.as_view(), name="about"), url(r"^computational-thinking/$", views.ComputationalThinkingView.as_view(), name="computational_thinking"), url(r"^contact/$", views.GeneralContactView.as_view(), name="contact"), url(r"^people/$", views.GeneralPeopleView.as_view(), name="people"), url(r"^principles/$", views.GeneralPrinciplesView.as_view(), name="principles"), ]
"""URL routing for the general application.""" from django.conf.urls import url from . import views urlpatterns = [ url( r"^$", views.GeneralIndexView.as_view(), name="home" ), url( r"^about/$", views.GeneralAboutView.as_view(), name="about" ), url( r"^computational-thinking/$", views.ComputationalThinkingView.as_view(), name="computational_thinking" ), url( r"^contact/$", views.GeneralContactView.as_view(), name="contact" ), url( r"^people/$", views.GeneralPeopleView.as_view(), name="people" ), url( r"^principles/$", views.GeneralPrinciplesView.as_view(), name="principles" ), ]
Update URLs file to match layout of other URLs files
Update URLs file to match layout of other URLs files
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
48d18015b2cf55638cc7bda43ae3751789fa2323
games/management/commands/autocreate_steamdb_installers.py
games/management/commands/autocreate_steamdb_installers.py
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
Update installer autocreate for games with no icon
Update installer autocreate for games with no icon
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website
0c89a78d3a0574ef491d3695366cd786b4c3f950
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py
"""Add column for profile picture type to User Revision ID: f37d509e221c Revises: c997dc927fbc Create Date: 2020-09-04 15:43:18.413156 """ import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum from indico.modules.users.models.users import ProfilePictureSource # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
"""Add column for profile picture type to User Revision ID: f37d509e221c Revises: c997dc927fbc Create Date: 2020-09-04 15:43:18.413156 """ from enum import Enum import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
Use embedded enum in alembic revision
Use embedded enum in alembic revision Unlikely to matter here but like this it will work correctly even in a future where someone may add new sources to the original enum (in that case this particular revision should not add those newer ones, which would be the case when using the imported enum)
Python
mit
DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,indico/indico,pferreir/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico
75fc7888cf4db89ae55324b325afc44452799cb3
filesystems/interfaces.py
filesystems/interfaces.py
from zope.interface import Interface from filesystems import _PY3 class Path(Interface): def __str__(): """ Render the path as a string. """ if _PY3: def __truediv__(other): """ Traverse to a child of this path. """ def __fspath__(other): """ Render the path as a string. """ else: def __div__(other): """ Render the path as a string. """ def basename(): """ The tail component of this path. """ def dirname(): """ The head components of this path. """ def heritage(): """ The top-down set of this path's parents. """ def descendant(*segments): """ Traverse to a descendant of this path. """ def parent(): """ Traverse to the parent of this path. """ def sibling(name): """ Traverse to a sibling of this path. """ def relative_to(path): """ Resolve a path relative to this one. """
from zope.interface import Interface from filesystems import _PY3 class Path(Interface): def __str__(): """ Render the path as a string. """ if _PY3: def __fspath__(): """ Render the path as a string. """ def __truediv__(other): """ Traverse to a child of this path. """ else: def __div__(other): """ Traverse to a child of this path. """ def basename(): """ The tail component of this path. """ def dirname(): """ The head components of this path. """ def heritage(): """ The top-down set of this path's parents. """ def descendant(*segments): """ Traverse to a descendant of this path. """ def parent(): """ Traverse to the parent of this path. """ def sibling(name): """ Traverse to a sibling of this path. """ def relative_to(path): """ Resolve a path relative to this one. """
Fix the fspath interface and div docstring.
Fix the fspath interface and div docstring.
Python
mit
Julian/Filesystems