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
4e1ff55e0575e710648867ada8fe421df280fb6a
utils.py
utils.py
import vx def _expose(f, name=None): if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c()
import vx def _expose(f=None, name=None): if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) if f is None: def g(f): setattr(vx, name, f) return f return g setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c()
Fix vx.expose so it works when a name is passed
Fix vx.expose so it works when a name is passed
Python
mit
philipdexter/vx,philipdexter/vx
ec96c3173a770949c13e560b16272bc265a80da4
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='mass_api_client', version=0.1, install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
#!/usr/bin/env python from distutils.core import setup setup(name='mass_api_client', version=0.1, install_requires=['requests==2.13.0', 'marshmallow==2.12.2'], packages=['mass_api_client', ], )
Add mass_api_client as Package; fix typo
Add mass_api_client as Package; fix typo
Python
mit
mass-project/mass_api_client,mass-project/mass_api_client
596613c964311104098e64eeb349216bc7cd0023
saleor/demo/views.py
saleor/demo/views.py
from django.conf import settings from django.shortcuts import render from ..graphql.views import API_PATH, GraphQLView EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API! # # Type queries into this side of the screen, and you will see # intelligent typeaheads aware of the current GraphQL type schema # and live syntax and validation errors highlighted within the text. # # Here is an example query to fetch a list of products: # { products(first: 5, channel: "%(channel_slug)s") { edges { node { id name description } } } } """ % { "channel_slug": settings.DEFAULT_CHANNEL_SLUG } class DemoGraphQLView(GraphQLView): def render_playground(self, request): ctx = { "query": EXAMPLE_QUERY, "api_url": request.build_absolute_uri(str(API_PATH)), } return render(request, "graphql/playground.html", ctx)
from django.conf import settings from django.shortcuts import render from ..graphql.views import GraphQLView EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API! # # Type queries into this side of the screen, and you will see # intelligent typeaheads aware of the current GraphQL type schema # and live syntax and validation errors highlighted within the text. # # Here is an example query to fetch a list of products: # { products(first: 5, channel: "%(channel_slug)s") { edges { node { id name description } } } } """ % { "channel_slug": settings.DEFAULT_CHANNEL_SLUG } class DemoGraphQLView(GraphQLView): def render_playground(self, request): pwa_origin = settings.PWA_ORIGINS[0] ctx = { "query": EXAMPLE_QUERY, "api_url": f"https://{pwa_origin}/graphql/", } return render(request, "graphql/playground.html", ctx)
Fix playground CSP for demo if deployed under proxied domain
Fix playground CSP for demo if deployed under proxied domain
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
53594f372a45e425076e5dbf36f399503df1972c
salt/output/yaml_out.py
salt/output/yaml_out.py
''' YAML Outputter ''' # Third Party libs import yaml def __virtual__(): return 'yaml' def output(data): ''' Print out YAML ''' return yaml.dump(data)
''' Output data in YAML, this outputter defaults to printing in YAML block mode for better readability. ''' # Third Party libs import yaml def __virtual__(): return 'yaml' def output(data): ''' Print out YAML using the block mode ''' return yaml.dump(data, default_flow_style=False)
Change the YAML outputter to use block mode and add some docs
Change the YAML outputter to use block mode and add some docs
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
eb5bcf3130f5fdc0d6be68e7e81555def46a53af
setup.py
setup.py
from distutils.core import setup setup( name = 'mstranslator', packages = ['mstranslator'], version = '0.0.1', description = 'Python wrapper to consume Microsoft translator API', author = 'Ayush Goel', author_email = 'ayushgoel111@gmail.com', url = 'https://github.com/ayushgoel/mstranslator', download_url = 'https://github.com/peterldowns/mypackage/tarball/0.1', keywords = ['microsoft', 'translator', 'language'], requires = ['requests'] )
from distutils.core import setup setup( name = 'mstranslator-2016', packages = ['mstranslator'], version = '0.0.1', description = 'Python wrapper to consume Microsoft translator API', author = 'Ayush Goel', author_email = 'ayushgoel111@gmail.com', url = 'https://github.com/ayushgoel/mstranslator', download_url = 'https://github.com/ayushgoel/mstranslator/archive/0.0.1.tar.gz', keywords = ['microsoft', 'translator', 'language'], requires = ['requests'] )
Update nemae and download URL
Update nemae and download URL
Python
mit
ayushgoel/mstranslator
ccbe4a1c48765fdd9e785392dff949bcc49192a2
setup.py
setup.py
from distutils.core import setup setup( name='Zinc', version='0.1.7', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
from distutils.core import setup setup( name='Zinc', version='0.1.8', author='John Wang', author_email='john@zinc.io', packages=['zinc'], package_dir={'zinc': ''}, package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']}, include_package_data=True, url='https://github.com/wangjohn/zinc_cli', license='LICENSE.txt', description='Wrapper for Zinc ecommerce API (zinc.io)', install_requires=[ "requests >= 1.1.0" ], )
Remove readme from package data.
Remove readme from package data.
Python
mit
wangjohn/zinc_cli
2c03fec9a1afb22e2075fa537615d3802fef7ec6
setup.py
setup.py
#!/usr/bin/env python3 import sys from distutils.core import setup setup( name='pathlib', version=open('VERSION.txt').read().strip(), py_modules=['pathlib'], license='MIT License', description='Object-oriented filesystem paths', long_description=open('README.txt').read(), author='Antoine Pitrou', author_email='solipsis@pitrou.net', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', ], download_url='https://pypi.python.org/pypi/pathlib/', url='http://readthedocs.org/docs/pathlib/', )
#!/usr/bin/env python3 import sys from distutils.core import setup setup( name='pathlib', version=open('VERSION.txt').read().strip(), py_modules=['pathlib'], license='MIT License', description='Object-oriented filesystem paths', long_description=open('README.txt').read(), author='Antoine Pitrou', author_email='solipsis@pitrou.net', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', ], download_url='https://pypi.python.org/pypi/pathlib/', url='http://readthedocs.org/docs/pathlib/', )
Add classifier for Python 3.3
Add classifier for Python 3.3
Python
mit
mcmtroffaes/pathlib2,saddingtonbaynes/pathlib2
949c8b8dc18d0732e6ada3a98cdf1a61028887dc
stagecraft/apps/datasets/admin/backdrop_user.py
stagecraft/apps/datasets/admin/backdrop_user.py
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email', 'data_sets'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
Remove data_sets from backdrop user search. Fixes
Remove data_sets from backdrop user search. Fixes
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
7e88739d91cd7db35ffb36804ae59d1878eb2da3
setup.py
setup.py
import os from distutils.core import setup requirements = map(str.strip, open('requirements.txt').readlines()) setup( name='py_eventsocket', version='0.1.4', author="Aaron Westendorf", author_email="aaron@agoragames.com", packages = ['eventsocket'], url='https://github.com/agoragames/py-eventsocket', license='LICENSE.txt', description='Easy to use TCP socket based on libevent', install_requires = requirements, long_description=open('README.rst').read(), keywords=['socket', 'event'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Topic :: Software Development :: Libraries' ] )
import os from distutils.core import setup requirements = map(str.strip, open('requirements.txt').readlines()) setup( name='py_eventsocket', version='0.1.4', author="Aaron Westendorf", author_email="aaron@agoragames.com", url='https://github.com/agoragames/py-eventsocket', license='LICENSE.txt', py_modules = ['eventsocket'], description='Easy to use TCP socket based on libevent', install_requires = requirements, long_description=open('README.rst').read(), keywords=['socket', 'event'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Topic :: Software Development :: Libraries' ] )
Use py_modules and not packages
Use py_modules and not packages
Python
bsd-3-clause
agoragames/py-eventsocket
c0b9c9712e464f304bee7c63bfd6b197a1c5fb0f
cmsplugin_bootstrap_carousel/cms_plugins.py
cmsplugin_bootstrap_carousel/cms_plugins.py
# coding: utf-8 import re from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cmsplugin_bootstrap_carousel.models import * from django.utils.translation import ugettext as _ from django.contrib import admin from django.forms import ModelForm, ValidationError class CarouselForm(ModelForm): class Meta: model = Carousel def clean_domid(self): data = self.cleaned_data['domid'] if not re.match(r'^[a-zA-Z_]\w*$', data): raise ValidationError(_("The name must be a single word beginning with a letter")) return data class CarouselItemInline(admin.StackedInline): model = CarouselItem class CarouselPlugin(CMSPluginBase): model = Carousel form = CarouselForm name = _("Carousel") render_template = "cmsplugin_bootstrap_carousel/carousel.html" inlines = [ CarouselItemInline, ] def render(self, context, instance, placeholder): context.update({'instance' : instance}) return context plugin_pool.register_plugin(CarouselPlugin)
# coding: utf-8 import re from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cmsplugin_bootstrap_carousel.models import * from django.utils.translation import ugettext as _ from django.contrib import admin from django.forms import ModelForm, ValidationError class CarouselForm(ModelForm): class Meta: model = Carousel def clean_domid(self): data = self.cleaned_data['domid'] if not re.match(r'^[a-zA-Z_]\w*$', data): raise ValidationError(_("The name must be a single word beginning with a letter")) return data class CarouselItemInline(admin.StackedInline): model = CarouselItem extra = 0 class CarouselPlugin(CMSPluginBase): model = Carousel form = CarouselForm name = _("Carousel") render_template = "cmsplugin_bootstrap_carousel/carousel.html" inlines = [ CarouselItemInline, ] def render(self, context, instance, placeholder): context.update({'instance' : instance}) return context plugin_pool.register_plugin(CarouselPlugin)
Change extra from 3 to 0.
Change extra from 3 to 0.
Python
bsd-3-clause
360youlun/cmsplugin-bootstrap-carousel,360youlun/cmsplugin-bootstrap-carousel
554e79ada3f351ecb6287b08d0f7d1c4e5a5b5f6
setup.py
setup.py
#!/usr/bin/env python import sys from distutils.core import setup setup_args = {} setup_args.update(dict( name='param', version='0.05', description='Declarative Python programming using Parameters.', long_description=open('README.txt').read(), author= "IOAM", author_email= "developers@topographica.org", maintainer= "IOAM", maintainer_email= "developers@topographica.org", platforms=['Windows', 'Mac OS X', 'Linux'], license='BSD', url='http://ioam.github.com/param/', packages = ["param"], classifiers = [ "License :: OSI Approved :: BSD License", # (until packaging tested) "Development Status :: 4 - Beta", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Natural Language :: English", "Topic :: Scientific/Engineering", "Topic :: Software Development :: Libraries"] )) if __name__=="__main__": setup(**setup_args)
#!/usr/bin/env python import sys from distutils.core import setup setup_args = {} setup_args.update(dict( name='param', version='1.0', description='Declarative Python programming using Parameters.', long_description=open('README.txt').read(), author= "IOAM", author_email= "developers@topographica.org", maintainer= "IOAM", maintainer_email= "developers@topographica.org", platforms=['Windows', 'Mac OS X', 'Linux'], license='BSD', url='http://ioam.github.com/param/', packages = ["param"], classifiers = [ "License :: OSI Approved :: BSD License", "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Natural Language :: English", "Topic :: Scientific/Engineering", "Topic :: Software Development :: Libraries"] )) if __name__=="__main__": setup(**setup_args)
Update version number to 1.0.
Update version number to 1.0.
Python
bsd-3-clause
ceball/param,ioam/param
81b6a138c476084f9ddd6063f31d3efd0ba6e2cf
start.py
start.py
# -*- coding: utf-8 -*- import argparse import logging import os import sys from twisted.internet import reactor from desertbot.config import Config, ConfigError from desertbot.factory import DesertBotFactory if __name__ == '__main__': parser = argparse.ArgumentParser(description='An IRC bot written in Python.') parser.add_argument('-c', '--config', help='the config file to read from', type=str, required=True) cmdArgs = parser.parse_args() os.chdir(os.path.dirname(os.path.abspath(__file__))) # Set up logging for stdout on the root 'desertbot' logger # Modules can then just add more handlers to the root logger to capture all logs to files in various ways rootLogger = logging.getLogger('desertbot') rootLogger.setLevel(logging.INFO) # TODO change this from config value once it's loaded logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S') streamHandler = logging.StreamHandler(stream=sys.stdout) streamHandler.setFormatter(logFormatter) rootLogger.addHandler(streamHandler) config = Config(cmdArgs.config) try: config.loadConfig() except ConfigError: rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config)) else: factory = DesertBotFactory(config) reactor.run()
# -*- coding: utf-8 -*- import argparse import logging import os import sys from twisted.internet import reactor from desertbot.config import Config, ConfigError from desertbot.factory import DesertBotFactory if __name__ == '__main__': parser = argparse.ArgumentParser(description='An IRC bot written in Python.') parser.add_argument('-c', '--config', help='the config file to read from', type=str, required=True) parser.add_argument('-l', '--loglevel', help='the logging level (default INFO)', type=str, default='INFO') cmdArgs = parser.parse_args() os.chdir(os.path.dirname(os.path.abspath(__file__))) # Set up logging for stdout on the root 'desertbot' logger # Modules can then just add more handlers to the root logger to capture all logs to files in various ways rootLogger = logging.getLogger('desertbot') numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None) if isinstance(numericLevel, int): rootLogger.setLevel(numericLevel) else: raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel)) logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S') streamHandler = logging.StreamHandler(stream=sys.stdout) streamHandler.setFormatter(logFormatter) rootLogger.addHandler(streamHandler) config = Config(cmdArgs.config) try: config.loadConfig() except ConfigError: rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config)) else: factory = DesertBotFactory(config) reactor.run()
Make the logging level configurable
Make the logging level configurable
Python
mit
DesertBot/DesertBot
23341ce8a8ff44996c9b502ffe0524f5a1f69946
test/interactive/test_exporter.py
test/interactive/test_exporter.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import sys import time from PySide import QtGui from segue import discover_processors from segue.backend.host.base import Host from segue.frontend.exporter import ExporterWidget class MockHost(Host): '''Mock host implementation.''' def get_selection(self): '''Return current selection.''' return ['|group1|objectA', '|group2|objectB', '|objectC', '|group3|group4|objectD'] def get_frame_range(self): '''Return current frame range.''' return (1.0, 24.0) def save(self): '''Export.''' print 'Export.''' for index in range(10): print 10 - index time.sleep(1) if __name__ == '__main__': '''Interactively test the exporter.''' app = QtGui.QApplication(sys.argv) host = MockHost() processors = discover_processors(paths=[ os.path.join(os.path.dirname(__file__), 'plugin') ]) widget = ExporterWidget(host=host, processors=processors) widget.show() raise SystemExit(app.exec_())
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import sys import time from PySide import QtGui from segue import discover_processors from segue.backend.host.base import Host from segue.frontend.exporter import ExporterWidget class MockHost(Host): '''Mock host implementation.''' def get_selection(self): '''Return current selection.''' return ['|group1|objectA', '|group2|objectB', '|objectC', '|group3|group4|objectD'] def get_frame_range(self): '''Return current frame range.''' return (1.0, 24.0) def save(self, target=None): '''Save scene.''' pass def save_package(self, selection=None, source=None, target=None, start=None, stop=None, step=1): '''Export.''' print 'Export.''' for index in range(10): print 10 - index time.sleep(1) if __name__ == '__main__': '''Interactively test the exporter.''' app = QtGui.QApplication(sys.argv) host = MockHost() processors = discover_processors(paths=[ os.path.join(os.path.dirname(__file__), 'plugin') ]) widget = ExporterWidget(host=host, processors=processors) widget.show() raise SystemExit(app.exec_())
Update mock host to match new interface.
Update mock host to match new interface.
Python
apache-2.0
4degrees/segue
f13fc280f25996ec7f4924647fdc879779f51737
project/tools/normalize.py
project/tools/normalize.py
#!/usr/bin/env python # mdstrip.py: makes new notebook from old, stripping md out """A tool to copy cell_type=("code") into a new file without grabbing headers/markdown (most importantly the md) NOTE: may want to grab the headers after all, or define new ones?""" import os import IPython.nbformat.current as nbf from glob import glob from lib import get_project_dir import sys def normalize(in_file, out_file): worksheet = in_file.worksheets[0] cell_list = [] # add graphic here & append to cell_list for cell in worksheet.cells: if cell.cell_type == ("code"): cell.outputs = [] cell.prompt_number = "" cell_list.append(cell) output_nb = nbf.new_notebook() # XXX should set name ... output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list)) nbf.write(output_nb, out_file, "ipynb") if __name__ == "__main__": if len(sys.argv) == 3: infile = open(sys.argv[1]) outfile = open(sys.argv[2],"w") else: infile = sys.stdin outfile = sys.stdout normalize(nbf.read(infile, "ipynb"), sys.stdout)
#!/usr/bin/env python # mdstrip.py: makes new notebook from old, stripping md out """A tool to copy cell_type=("code") into a new file without grabbing headers/markdown (most importantly the md) NOTE: may want to grab the headers after all, or define new ones?""" import os import IPython.nbformat.current as nbf from glob import glob from lib import get_project_dir import sys def normalize(in_file, out_file): worksheet = in_file.worksheets[0] cell_list = [] # add graphic here & append to cell_list for cell in worksheet.cells: if cell.cell_type == ("code"): cell.outputs = [] cell.prompt_number = "" cell_list.append(cell) output_nb = nbf.new_notebook() # XXX should set name ... output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list)) nbf.write(output_nb, out_file, "ipynb") if __name__ == "__main__": if len(sys.argv) == 3: infile = open(sys.argv[1]) outfile = open(sys.argv[2],"w") elif len(sys.argv) != 1: sys.exit("normalize: two arguments or none, please") else: infile = sys.stdin outfile = sys.stdout try: normalize(nbf.read(infile, "ipynb"), outfile) except Exception as e: sys.exit("Normalization error: '{}'".format(str(e)))
Allow two command arguments for in and out files, or none for standard filter operations
Allow two command arguments for in and out files, or none for standard filter operations
Python
mit
holdenweb/nbtools,holdenweb/nbtools
7e98a76ac455a8c69950104766719cde313bbb74
tests/CrawlerProcess/asyncio_deferred_signal.py
tests/CrawlerProcess/asyncio_deferred_signal.py
import asyncio import sys import scrapy from scrapy.crawler import CrawlerProcess from twisted.internet.defer import Deferred class UppercasePipeline: async def _open_spider(self, spider): spider.logger.info("async pipeline opened!") await asyncio.sleep(0.1) def open_spider(self, spider): loop = asyncio.get_event_loop() return Deferred.fromFuture(loop.create_task(self._open_spider(spider))) def process_item(self, item, spider): return {"url": item["url"].upper()} class UrlSpider(scrapy.Spider): name = "url_spider" start_urls = ["data:,"] custom_settings = { "ITEM_PIPELINES": {UppercasePipeline: 100}, } def parse(self, response): yield {"url": response.url} if __name__ == "__main__": try: ASYNCIO_EVENT_LOOP = sys.argv[1] except IndexError: ASYNCIO_EVENT_LOOP = None process = CrawlerProcess(settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": ASYNCIO_EVENT_LOOP, }) process.crawl(UrlSpider) process.start()
import asyncio import sys from scrapy import Spider from scrapy.crawler import CrawlerProcess from scrapy.utils.defer import deferred_from_coro from twisted.internet.defer import Deferred class UppercasePipeline: async def _open_spider(self, spider): spider.logger.info("async pipeline opened!") await asyncio.sleep(0.1) def open_spider(self, spider): loop = asyncio.get_event_loop() return deferred_from_coro(self._open_spider(spider)) def process_item(self, item, spider): return {"url": item["url"].upper()} class UrlSpider(Spider): name = "url_spider" start_urls = ["data:,"] custom_settings = { "ITEM_PIPELINES": {UppercasePipeline: 100}, } def parse(self, response): yield {"url": response.url} if __name__ == "__main__": try: ASYNCIO_EVENT_LOOP = sys.argv[1] except IndexError: ASYNCIO_EVENT_LOOP = None process = CrawlerProcess(settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": ASYNCIO_EVENT_LOOP, }) process.crawl(UrlSpider) process.start()
Use deferred_from_coro in asyncio test
Use deferred_from_coro in asyncio test
Python
bsd-3-clause
elacuesta/scrapy,elacuesta/scrapy,scrapy/scrapy,pablohoffman/scrapy,dangra/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,scrapy/scrapy,pawelmhm/scrapy,dangra/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,elacuesta/scrapy,scrapy/scrapy
7119930b662a20d9e9bbca230f8a6485efcb7c44
flask_appconfig/middleware.py
flask_appconfig/middleware.py
# from: http://flask.pocoo.org/snippets/35/ # written by Peter Hansen class ReverseProxied(object): '''Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind this to a URL other than / and to an HTTP scheme that is different than what is used locally. In nginx: location /myprefix { proxy_pass http://192.168.0.1:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_set_header X-Script-Name /myprefix; } :param app: the WSGI application ''' def __init__(self, app): self.app = app def __call__(self, environ, start_response): script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme return self.app(environ, start_response)
# from: http://flask.pocoo.org/snippets/35/ # written by Peter Hansen class ReverseProxied(object): '''Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind this to a URL other than / and to an HTTP scheme that is different than what is used locally. In nginx: location /myprefix { proxy_pass http://192.168.0.1:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_set_header X-Script-Name /myprefix; } :param app: the WSGI application ''' def __init__(self, app): self.app = app def __call__(self, environ, start_response): script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme return self.app(environ, start_response) # pass through other attributes, like .run() when using werkzeug def __getattr__(self, key): return getattr(self.app, key)
Add __getattr__ passthrough on ReverseProxied.
Add __getattr__ passthrough on ReverseProxied.
Python
mit
mbr/flask-appconfig
ba32a22cc0cb41c4548c658a7195fab56dab6dbf
atlas/prodtask/tasks.py
atlas/prodtask/tasks.py
from __future__ import absolute_import, unicode_literals from atlas.celerybackend.celery import app from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed from atlas.prodtask.hashtag import hashtag_request_to_tasks from atlas.prodtask.mcevgen import sync_cvmfs_db from atlas.prodtask.open_ended import check_open_ended from atlas.prodtask.task_views import sync_old_tasks import logging _logger = logging.getLogger('prodtaskwebui') @app.task def test_celery(): _logger.info('test celery') return 2 @app.task(ignore_result=True) def sync_tasks(): sync_old_tasks(-1) return None @app.task(ignore_result=True) def step_actions(): find_action_to_execute() return None @app.task(ignore_result=True) def data_carousel(): submit_all_tapes_processed() return None @app.task(ignore_result=True) def open_ended(): check_open_ended() return None @app.task(ignore_result=True) def request_hashtags(): hashtag_request_to_tasks() return None @app.task(ignore_result=True) def sync_evgen_jo(): sync_cvmfs_db() return None
from __future__ import absolute_import, unicode_literals from atlas.celerybackend.celery import app from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules from atlas.prodtask.hashtag import hashtag_request_to_tasks from atlas.prodtask.mcevgen import sync_cvmfs_db from atlas.prodtask.open_ended import check_open_ended from atlas.prodtask.task_views import sync_old_tasks import logging _logger = logging.getLogger('prodtaskwebui') @app.task def test_celery(): _logger.info('test celery') return 2 @app.task(ignore_result=True) def sync_tasks(): sync_old_tasks(-1) return None @app.task(ignore_result=True) def step_actions(): find_action_to_execute() return None @app.task(ignore_result=True) def data_carousel(): submit_all_tapes_processed() return None @app.task(ignore_result=True) def open_ended(): check_open_ended() return None @app.task(ignore_result=True) def request_hashtags(): hashtag_request_to_tasks() return None @app.task(ignore_result=True) def sync_evgen_jo(): sync_cvmfs_db() return None @app.task(ignore_result=True) def remove_done_staging(production_requests): delete_done_staging_rules(production_requests) return None
Add remove done staged rules
Add remove done staged rules
Python
apache-2.0
PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas
eede55d9cd39c68ef03091614096e51d7df01336
test_scraper.py
test_scraper.py
from scraper import search_CL from scraper import read_search_results from scraper import parse_source from scraper import extract_listings import bs4 def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100, maxAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_read_search_result(): test_body, test_encoding = read_search_results() assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_parse_source(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) assert isinstance(test_parse, bs4.BeautifulSoup) def test_extract_listings(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) for row in extract_listings(test_parse): print type(row) assert isinstance(row, bs4.element.Tag)
from scraper import search_CL from scraper import read_search_results from scraper import parse_source from scraper import extract_listings import bs4 def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100, maxAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_read_search_result(): test_body, test_encoding = read_search_results() assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_parse_source(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) assert isinstance(test_parse, bs4.BeautifulSoup) def test_extract_listings(): test_body, test_encoding = read_search_results() test_parse = parse_source(test_body, test_encoding) test_data = extract_listings(test_parse) assert isinstance(test_data, list) for dict_ in test_data: assert isinstance(dict_, dict)
Modify test_extract_listings() to account for the change in output from extract_listings()
Modify test_extract_listings() to account for the change in output from extract_listings()
Python
mit
jefrailey/basic-scraper
b823233978f70d8e34a3653b309ee43b4b1e0c0d
fuel/transformers/defaults.py
fuel/transformers/defaults.py
"""Commonly-used default transformers.""" from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer from fuel.transformers.image import ImagesFromBytes def uint8_pixels_to_floatX(which_sources): return ( (ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}), (Cast, ['floatX'], {'which_sources': which_sources})) class ToBytes(SourcewiseTransformer): """Transform a stream of ndarray examples to bytes. Notes ----- Used for retrieving variable-length byte data stored as, e.g. a uint8 ragged array. """ def __init__(self, stream, **kwargs): kwargs.setdefault('produces_examples', stream.produces_examples) axis_labels = stream.axis_labels for source in kwargs.get('which_sources', stream.sources): axis_labels[source] = (('batch', 'bytes') if 'batch' in axis_labels.get(source, ()) else ('bytes',)) kwargs.setdefault('axis_labels', axis_labels) super(ToBytes, self).__init__(stream, **kwargs) def transform_source_example(self, example, _): return example.tostring() def transform_source_batch(self, batch, _): return [example.tostring() for example in batch] def rgb_images_from_encoded_bytes(which_sources): return ((ToBytes, [], {'which_sources': ('encoded_images',)}), (ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
"""Commonly-used default transformers.""" from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer from fuel.transformers.image import ImagesFromBytes def uint8_pixels_to_floatX(which_sources): return ( (ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}), (Cast, ['floatX'], {'which_sources': which_sources})) class ToBytes(SourcewiseTransformer): """Transform a stream of ndarray examples to bytes. Notes ----- Used for retrieving variable-length byte data stored as, e.g. a uint8 ragged array. """ def __init__(self, stream, **kwargs): kwargs.setdefault('produces_examples', stream.produces_examples) axis_labels = (stream.axis_labels if stream.axis_labels is not None else {}) for source in kwargs.get('which_sources', stream.sources): axis_labels[source] = (('batch', 'bytes') if 'batch' in axis_labels.get(source, ()) else ('bytes',)) kwargs.setdefault('axis_labels', axis_labels) super(ToBytes, self).__init__(stream, **kwargs) def transform_source_example(self, example, _): return example.tostring() def transform_source_batch(self, batch, _): return [example.tostring() for example in batch] def rgb_images_from_encoded_bytes(which_sources): return ((ToBytes, [], {'which_sources': ('encoded_images',)}), (ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
Handle None axis_labels in ToBytes.
Handle None axis_labels in ToBytes.
Python
mit
udibr/fuel,markusnagel/fuel,vdumoulin/fuel,mila-udem/fuel,dmitriy-serdyuk/fuel,udibr/fuel,markusnagel/fuel,aalmah/fuel,vdumoulin/fuel,aalmah/fuel,capybaralet/fuel,janchorowski/fuel,mila-udem/fuel,dribnet/fuel,capybaralet/fuel,dmitriy-serdyuk/fuel,janchorowski/fuel,dribnet/fuel
65010bed4885223be3ed424b4189de368d28080f
sites/shared_conf.py
sites/shared_conf.py
from datetime import datetime import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] extensions = ['alabaster'] # Paths relative to invoking conf.py - not this shared file html_static_path = ['../_shared_static'] html_theme = 'alabaster' html_theme_options = { 'description': "Pythonic remote execution", 'github_user': 'fabric', 'github_repo': 'fabric', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-1', } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = 'Fabric' year = datetime.now().year copyright = '%d Jeff Forcier' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
from os.path import join from datetime import datetime import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] extensions = ['alabaster'] # Paths relative to invoking conf.py - not this shared file html_static_path = [join('..', '_shared_static')] html_theme = 'alabaster' html_theme_options = { 'description': "Pythonic remote execution", 'github_user': 'fabric', 'github_repo': 'fabric', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-1', } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = 'Fabric' year = datetime.now().year copyright = '%d Jeff Forcier' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
Make shared static path OS-agnostic
Make shared static path OS-agnostic
Python
bsd-2-clause
haridsv/fabric,cgvarela/fabric,ploxiln/fabric,tekapo/fabric,bitmonk/fabric,kmonsoor/fabric,amaniak/fabric,sdelements/fabric,likesxuqiang/fabric,TarasRudnyk/fabric,mathiasertl/fabric,tolbkni/fabric,pgroudas/fabric,SamuelMarks/fabric,jaraco/fabric,rbramwell/fabric,bspink/fabric,raimon49/fabric,kxxoling/fabric,qinrong/fabric,rodrigc/fabric,xLegoz/fabric,elijah513/fabric,opavader/fabric,cmattoon/fabric,askulkarni2/fabric,rane-hs/fabric-py3,fernandezcuesta/fabric,StackStorm/fabric,itoed/fabric
beeae2daf35da275d5f9e1ad01516c917319bf00
gapipy/resources/geo/state.py
gapipy/resources/geo/state.py
from __future__ import unicode_literals from ..base import Resource from ...utils import enforce_string_type class State(Resource): _resource_name = 'states' _as_is_fields = ['id', 'href', 'name'] _resource_fields = [('country', 'Country')] @enforce_string_type def __repr__(self): return '<{}: {}>'.format(self.__class__.__name__, self.name)
from __future__ import unicode_literals from ..base import Resource from ...utils import enforce_string_type class State(Resource): _resource_name = 'states' _as_is_fields = ['id', 'href', 'name'] _resource_fields = [ ('country', 'Country'), ('place', 'Place'), ] @enforce_string_type def __repr__(self): return '<{}: {}>'.format(self.__class__.__name__, self.name)
Add Place reference to State model
Add Place reference to State model
Python
mit
gadventures/gapipy
d2fc123454bdf0089043ef3926798f3f79904c60
Lib/test/test_openpty.py
Lib/test/test_openpty.py
# Test to see if openpty works. (But don't worry if it isn't available.) import os, unittest from test.test_support import run_unittest, TestSkipped class OpenptyTest(unittest.TestCase): def test(self): try: master, slave = os.openpty() except AttributeError: raise TestSkipped, "No openpty() available." if not os.isatty(slave): self.fail("Slave-end of pty is not a terminal.") os.write(slave, 'Ping!') self.assertEqual(os.read(master, 1024), 'Ping!') def test_main(): run_unittest(OpenptyTest) if __name__ == '__main__': test_main()
# Test to see if openpty works. (But don't worry if it isn't available.) import os, unittest from test.test_support import run_unittest, TestSkipped if not hasattr(os, "openpty"): raise TestSkipped, "No openpty() available." class OpenptyTest(unittest.TestCase): def test(self): master, slave = os.openpty() if not os.isatty(slave): self.fail("Slave-end of pty is not a terminal.") os.write(slave, 'Ping!') self.assertEqual(os.read(master, 1024), 'Ping!') def test_main(): run_unittest(OpenptyTest) if __name__ == '__main__': test_main()
Move the check for openpty to the beginning.
Move the check for openpty to the beginning.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
cedac36d38ff0bf70abc1c9193948a288e858a01
kitsune/lib/pipeline_compilers.py
kitsune/lib/pipeline_compilers.py
import re from django.conf import settings from django.utils.encoding import smart_bytes from pipeline.compilers import CompilerBase from pipeline.exceptions import CompilerError class BrowserifyCompiler(CompilerBase): output_extension = 'browserified.js' def match_file(self, path): # Allow for cache busting hashes between ".browserify" and ".js" return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None def compile_file(self, infile, outfile, outdated=False, force=False): command = "%s %s %s > %s" % ( getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'), getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''), infile, outfile ) return self.execute_command(command) def execute_command(self, command, content=None, cwd=None): """This is like the one in SubProcessCompiler, except it checks the exit code.""" import subprocess pipe = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if content: content = smart_bytes(content) stdout, stderr = pipe.communicate(content) if self.verbose: print(stderr) if pipe.returncode != 0: raise CompilerError(stderr) return stdout
import re from django.conf import settings from django.utils.encoding import smart_bytes from pipeline.compilers import CompilerBase from pipeline.exceptions import CompilerError class BrowserifyCompiler(CompilerBase): output_extension = 'browserified.js' def match_file(self, path): # Allow for cache busting hashes between ".browserify" and ".js" return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None def compile_file(self, infile, outfile, outdated=False, force=False): pipeline_settings = getattr(settings, 'PIPELINE', {}) command = "%s %s %s > %s" % ( pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'), pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''), infile, outfile ) return self.execute_command(command) def execute_command(self, command, content=None, cwd=None): """This is like the one in SubProcessCompiler, except it checks the exit code.""" import subprocess pipe = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if content: content = smart_bytes(content) stdout, stderr = pipe.communicate(content) if self.verbose: print(stderr) if pipe.returncode != 0: raise CompilerError(stderr) return stdout
Update BrowserifyCompiler for n Pipeline settings.
Update BrowserifyCompiler for n Pipeline settings.
Python
bsd-3-clause
mythmon/kitsune,MikkCZ/kitsune,brittanystoroz/kitsune,anushbmx/kitsune,MikkCZ/kitsune,anushbmx/kitsune,safwanrahman/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,mozilla/kitsune,safwanrahman/kitsune,mythmon/kitsune,anushbmx/kitsune,mythmon/kitsune,safwanrahman/kitsune,mozilla/kitsune,brittanystoroz/kitsune,mythmon/kitsune,mozilla/kitsune,anushbmx/kitsune,MikkCZ/kitsune,mozilla/kitsune,brittanystoroz/kitsune,safwanrahman/kitsune
c1f8d5817b8c94b422c0d454dcc0fa3c00e751b6
activelink/tests/urls.py
activelink/tests/urls.py
from django import VERSION as DJANGO_VERSION from django.http import HttpResponse if DJANGO_VERSION >= (1, 6): from django.conf.urls import patterns, url else: from django.conf.urls.defaults import patterns, url urlpatterns = patterns('', url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'), url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'), url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'), )
from django import VERSION as DJANGO_VERSION from django.http import HttpResponse if DJANGO_VERSION >= (1, 10): from django.conf.urls import url elif DJANGO_VERSION >= (1, 6): from django.conf.urls import patterns, url else: from django.conf.urls.defaults import patterns, url urlpatterns = [ url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'), url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'), url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'), ] if DJANGO_VERSION < (1, 10): urlpatterns = patterns('', *urlpatterns)
Add support for Django 1.11
Add support for Django 1.11
Python
unlicense
j4mie/django-activelink
4b34f2afa13ef880b9832bc725c5f1b6ede4dc0e
back_office/models.py
back_office/models.py
from django.db import models from django.utils.translation import ugettext as _ from Django.contrib.auth.models import User FEMALE = 'F' MALE = 'M' class Teacher(models.Model): """ halaqat teachers informations """ GENDET_CHOICES = ( (MALE, _('Male')), (FEMALE, _('Female')), ) name = models.CharField(max_length=100, verbose_name=_('Name')) gender = models.CharField(max_length=1, verbose_name=_('Gender'), choices=GENDET_CHOICES) civil_id = models.CharField(max_length=12, verbose_name=_('Civil ID')) phone_number = models.CharField(max_length=15, verbose_name=_('Phone Number')) job_title = models.CharField(max_length=15, verbose_name=_('Title')) enabled = models.BooleanField(default=True) user = models.OneToOneField(to=User, related_name='teachers') def enable(self): """ Enable teacher profile :return: """ self.enabled = True self.save() def disable(self): """ Disable teacher profile :return: """ self.enabled = False self.save()
from django.db import models from django.utils.translation import ugettext as _ from Django.contrib.auth.models import User FEMALE = 'F' MALE = 'M' class Teacher(models.Model): """ halaqat teachers informations """ GENDET_CHOICES = ( (MALE, _('Male')), (FEMALE, _('Female')), ) gender = models.CharField(max_length=1, verbose_name=_('Gender'), choices=GENDET_CHOICES) civil_id = models.CharField(max_length=12, verbose_name=_('Civil ID')) phone_number = models.CharField(max_length=15, verbose_name=_('Phone Number')) job_title = models.CharField(max_length=15, verbose_name=_('Title')) enabled = models.BooleanField(default=True) user = models.OneToOneField(to=User, related_name='teachers') def enable(self): """ Enable teacher profile :return: """ self.enabled = True self.save() def disable(self): """ Disable teacher profile :return: """ self.enabled = False self.save()
Remove name field and use the User name fields
Remove name field and use the User name fields
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
c2ca03ba94349340447a316ff21bcb26631e308f
lms/djangoapps/discussion/settings/common.py
lms/djangoapps/discussion/settings/common.py
"""Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, }
"""Common environment variables unique to the discussion plugin.""" def plugin_settings(settings): """Settings for the discussions plugin. """ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB # .. toggle_implementation: DjangoSetting # .. toggle_default: False # .. toggle_description: If True, it adds an option to show/hide the discussions tab. # .. toggle_use_cases: open_edx # .. toggle_creation_date: 2015-06-15 # .. toggle_target_removal_date: None # .. toggle_warnings: None # .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474 settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False settings.DISCUSSION_SETTINGS = { 'MAX_COMMENT_DEPTH': 2, 'COURSE_PUBLISH_TASK_DELAY': 30, }
Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
Python
agpl-3.0
EDUlib/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,edx/edx-platform,angelapper/edx-platform,edx/edx-platform,angelapper/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform
90ca340883077f57ba63127db058a8d244ec6f4c
molecule/ui/tests/conftest.py
molecule/ui/tests/conftest.py
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.utils import ChromeType @pytest.fixture(scope="session") def chromedriver(): try: options = Options() options.headless = True options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument("--disable-gpu") driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options) url = 'http://localhost:9000' driver.get(url + "/gettingstarted") WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in')) #Login to Graylog uid_field = driver.find_element_by_name("username") uid_field.clear() uid_field.send_keys("admin") password_field = driver.find_element_by_name("password") password_field.clear() password_field.send_keys("admin") password_field.send_keys(Keys.RETURN) WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started')) #Run tests yield driver finally: driver.quit()
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions import time from webdriver_manager.chrome import ChromeDriverManager @pytest.fixture(scope="session") def chromedriver(): try: options = Options() options.headless = True options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument("--disable-gpu") driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) url = 'http://localhost:9000' driver.get(url + "/gettingstarted") WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in')) #Login to Graylog uid_field = driver.find_element_by_name("username") uid_field.clear() uid_field.send_keys("admin") password_field = driver.find_element_by_name("password") password_field.clear() password_field.send_keys("admin") password_field.send_keys(Keys.RETURN) WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started')) #Run tests yield driver finally: driver.quit()
Switch UI tests back to google chrome.
Switch UI tests back to google chrome.
Python
apache-2.0
Graylog2/graylog-ansible-role
760506e88d22d86be818017fb6075abe7af2a068
dactyl.py
dactyl.py
from slackbot.bot import respond_to from slackbot.bot import listen_to import re import urllib
from slackbot.bot import respond_to from slackbot.bot import listen_to import re import urllib def url_validator(url): try: code = urllib.urlopen(url).getcode() if code == 200: return True except: return False def test_url(message, url): if url_validator(url[1:len(url)-1]): message.reply('VALID URL') else: message.reply('NOT VALID URL')
Add url_validator function and respond aciton to test url
Add url_validator function and respond aciton to test url
Python
mit
KrzysztofSendor/dactyl
01b67c00b6ab1eea98da9b54737f051a01a726fb
auslib/migrate/versions/009_add_rule_alias.py
auslib/migrate/versions/009_add_rule_alias.py
from sqlalchemy import Column, String, MetaData, Table def upgrade(migrate_engine): metadata = MetaData(bind=migrate_engine) def add_alias(table): alias = Column('alias', String(50)) alias.create(table) add_alias(Table('rules', metadata, autoload=True)) add_alias(Table('rules_history', metadata, autoload=True)) def downgrade(migrate_engine): metadata = MetaData(bind=migrate_engine) Table('rules', metadata, autoload=True).c.alias.drop() Table('rules_history', metadata, autoload=True).c.alias.drop()
from sqlalchemy import Column, String, MetaData, Table def upgrade(migrate_engine): metadata = MetaData(bind=migrate_engine) def add_alias(table): alias = Column('alias', String(50), unique=True) alias.create(table) add_alias(Table('rules', metadata, autoload=True)) add_alias(Table('rules_history', metadata, autoload=True)) def downgrade(migrate_engine): metadata = MetaData(bind=migrate_engine) Table('rules', metadata, autoload=True).c.alias.drop() Table('rules_history', metadata, autoload=True).c.alias.drop()
Create alias column as unique.
Create alias column as unique.
Python
mpl-2.0
nurav/balrog,mozbhearsum/balrog,tieu/balrog,mozbhearsum/balrog,aksareen/balrog,aksareen/balrog,aksareen/balrog,mozbhearsum/balrog,tieu/balrog,nurav/balrog,testbhearsum/balrog,mozbhearsum/balrog,nurav/balrog,testbhearsum/balrog,aksareen/balrog,testbhearsum/balrog,tieu/balrog,nurav/balrog,testbhearsum/balrog,tieu/balrog
1b8efb09ac512622ea3541d950ffc67b0a183178
survey/signals.py
survey/signals.py
import django.dispatch survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
import django.dispatch # providing_args=["instance", "data"] survey_completed = django.dispatch.Signal()
Remove puyrely documental providing-args argument
Remove puyrely documental providing-args argument See https://docs.djangoproject.com/en/4.0/releases/3.1/#id2
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
231657e2bbc81b8299cc91fd24dcd7394f74b4ec
python/dpu_utils/codeutils/identifiersplitting.py
python/dpu_utils/codeutils/identifiersplitting.py
from functools import lru_cache from typing import List import sys REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|" "(?<=[A-Z0-9])(?=[A-Z][a-z])|" "(?<=[0-9])(?=[a-zA-Z])|" "(?<=[A-Za-z])(?=[0-9])|" "(?<=[@$])(?=[a-zA-Z0-9])|" "(?<=[a-zA-Z0-9])(?=[@$])|" "_") if sys.version_info >= (3, 7): import re SPLIT_REGEX = re.compile(REGEX_TEXT) else: import regex SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT) @lru_cache(maxsize=5000) def split_identifier_into_parts(identifier: str) -> List[str]: """ Split a single identifier into parts on snake_case and camelCase """ identifier_parts = list(s for s in SPLIT_REGEX.split(identifier) if len(s)>0) if len(identifier_parts) == 0: return [identifier] return identifier_parts
from functools import lru_cache from typing import List import sys REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|" "(?<=[A-Z0-9])(?=[A-Z][a-z])|" "(?<=[0-9])(?=[a-zA-Z])|" "(?<=[A-Za-z])(?=[0-9])|" "(?<=[@$.'\"])(?=[a-zA-Z0-9])|" "(?<=[a-zA-Z0-9])(?=[@$.'\"])|" "_|\\s+") if sys.version_info >= (3, 7): import re SPLIT_REGEX = re.compile(REGEX_TEXT) else: import regex SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT) @lru_cache(maxsize=5000) def split_identifier_into_parts(identifier: str) -> List[str]: """ Split a single identifier into parts on snake_case and camelCase """ identifier_parts = list(s.lower() for s in SPLIT_REGEX.split(identifier) if len(s)>0) if len(identifier_parts) == 0: return [identifier] return identifier_parts
Revert to some of the previous behavior for characters that shouldn't appear in identifiers.
Revert to some of the previous behavior for characters that shouldn't appear in identifiers.
Python
mit
microsoft/dpu-utils,microsoft/dpu-utils
81460f88ee19fb736dfc3453df2905f0ba4b3974
common/permissions.py
common/permissions.py
from rest_framework.permissions import BasePermission class ObjectHasTokenUser(BasePermission): """ The object's user matches the token's user. """ def has_object_permission(self, request, view, obj): token = request.auth if not token: return False if not hasattr(token, 'scope'): assert False, ('TokenHasReadWriteScope requires the' '`OAuth2Authentication` authentication ' 'class to be used.') if hasattr(obj, 'user'): print 'token.user', token.user print 'obj.user', obj.user return token.user == obj.user
from rest_framework.permissions import BasePermission class ObjectHasTokenUser(BasePermission): """ The object's user matches the token's user. """ def has_object_permission(self, request, view, obj): token = request.auth if not token: return False if not hasattr(token, 'scope'): assert False, ('ObjectHasTokenUser requires the' '`OAuth2Authentication` authentication ' 'class to be used.') if hasattr(obj, 'user'): return token.user == obj.user
Remove debugging code, fix typo
Remove debugging code, fix typo
Python
mit
PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans
65336509829a42b91b000d2e423ed4581ac61c98
app/mpv.py
app/mpv.py
#!/usr/bin/env python # and add mpv.json to ~/.mozilla/native-messaging-hosts import sys import json import struct import subprocess # Read a message from stdin and decode it. def getMessage(): rawLength = sys.stdin.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.read(messageLength) return json.loads(message) # Encode a message for transmission, # given its content. def encodeMessage(messageContent): encodedContent = json.dumps(messageContent) encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} # Send an encoded message to stdout def sendMessage(encodedMessage): sys.stdout.write(encodedMessage['length']) sys.stdout.write(encodedMessage['content']) sys.stdout.flush() while True: mpv_args = getMessage() if (len(mpv_args) > 1): subprocess.call(["mpv", mpv_args])
#!/usr/bin/env python import sys import json import struct import subprocess import shlex # Read a message from stdin and decode it. def getMessage(): rawLength = sys.stdin.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.read(messageLength) return json.loads(message) # Encode a message for transmission, # given its content. def encodeMessage(messageContent): encodedContent = json.dumps(messageContent) encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} # Send an encoded message to stdout def sendMessage(encodedMessage): sys.stdout.write(encodedMessage['length']) sys.stdout.write(encodedMessage['content']) sys.stdout.flush() while True: mpv_args = getMessage() if (len(mpv_args) > 1): args = shlex.split("mpv " + mpv_args) subprocess.call(args) sys.exit(0)
Handle shell args in python scripts
Handle shell args in python scripts
Python
mit
vayan/external-video,vayan/external-video,vayan/external-video,vayan/external-video
d7298374409912c6ace10e2bec323013cdd4d933
scripts/poweron/DRAC.py
scripts/poweron/DRAC.py
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/usr/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/opt/dell/srvadmin/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
Change path to the supplemental pack
CA-40618: Change path to the supplemental pack Signed-off-by: Javier Alvarez-Valle <cf4c8668a0b4c5e013f594a6940d05b3d4d9ddcf@citrix.com>
Python
lgpl-2.1
simonjbeaumont/xcp-rrdd,koushikcgit/xcp-rrdd,djs55/squeezed,koushikcgit/xcp-rrdd,johnelse/xcp-rrdd,johnelse/xcp-rrdd,sharady/xcp-networkd,simonjbeaumont/xcp-rrdd,djs55/xcp-networkd,sharady/xcp-networkd,djs55/xcp-rrdd,djs55/xcp-rrdd,koushikcgit/xcp-rrdd,djs55/xcp-networkd,koushikcgit/xcp-networkd,robhoes/squeezed,koushikcgit/xcp-networkd
83d5cc3b4ffb4759e8e073d04299a55802df09a8
src/ansible/views.py
src/ansible/views.py
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from .models import Playbook def index(request): return "200"
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from .models import Playbook def index(request): return HttpResponse("200")
Fix return to use HttpResponse
Fix return to use HttpResponse
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
88e5ecad9966057203a9cbecaeaecdca3e76b6da
tests/fake_filesystem.py
tests/fake_filesystem.py
import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) def close(self): """ Always hold fake files open. """ pass class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
Define noop close() for FakeFile
Define noop close() for FakeFile
Python
bsd-2-clause
kxxoling/fabric,rodrigc/fabric,qinrong/fabric,elijah513/fabric,bspink/fabric,MjAbuz/fabric,cmattoon/fabric,hrubi/fabric,felix-d/fabric,askulkarni2/fabric,SamuelMarks/fabric,mathiasertl/fabric,tekapo/fabric,StackStorm/fabric,ploxiln/fabric,kmonsoor/fabric,raimon49/fabric,haridsv/fabric,bitprophet/fabric,fernandezcuesta/fabric,itoed/fabric,rane-hs/fabric-py3,sdelements/fabric,likesxuqiang/fabric,bitmonk/fabric,getsentry/fabric,opavader/fabric,jaraco/fabric,xLegoz/fabric,TarasRudnyk/fabric,pgroudas/fabric,akaariai/fabric,rbramwell/fabric,amaniak/fabric,cgvarela/fabric,tolbkni/fabric,pashinin/fabric
f45b3e73b6258c99aed2bff2e7350f1c797ff849
providers/provider.py
providers/provider.py
import copy import json import requests import html5lib from application import APPLICATION as APP # Be compatible with python 2 and 3 try: from urllib import urlencode except ImportError: from urllib.parse import urlencode class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector, timeout=60, cache=True): html = self._http_get(url, timeout=timeout, cache=cache) document = html5lib.parse(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data new_data = copy.copy(data) for item in path.split("."): if item.isdigit(): item = int(item) try: new_data = new_data[item] except (IndexError, KeyError): return {} return new_data def parse_json(self, url, path=None, timeout=60, cache=True): data = self._http_get(url, timeout=timeout, cache=cache) data = json.loads(data) data = self.traverse_json(data, path) return data def urlencode(self, data): return urlencode(data) # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60, cache=True): base = requests if not cache else APP.setting("WEBCACHE") response = base.get(url, timeout=timeout) return response.text
import copy import json from urllib.parse import urlencode import html5lib import requests from application import APPLICATION as APP class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector, timeout=60, cache=True): html = self._http_get(url, timeout=timeout, cache=cache) document = html5lib.parse(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data new_data = copy.copy(data) for item in path.split("."): if item.isdigit(): item = int(item) try: new_data = new_data[item] except (IndexError, KeyError): return {} return new_data def parse_json(self, url, path=None, timeout=60, cache=True): data = self._http_get(url, timeout=timeout, cache=cache) data = json.loads(data) data = self.traverse_json(data, path) return data def urlencode(self, data): return urlencode(data) # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60, cache=True): base = requests if not cache else APP.setting("WEBCACHE") response = base.get(url, timeout=timeout) return response.text
Remove support for Python 2.
Remove support for Python 2.
Python
mit
EmilStenstrom/nephele
cdd32dd3e346f72f823cc5d3f59c79c027db65c8
common.py
common.py
"""Functions common to other modules.""" import json import os import re import time import urllib.request from settings import net def clean(name): """Strip all [^a-zA-Z0-9_] characters and convert to lowercase.""" return re.sub(r"\W", r"", name, flags=re.ASCII).lower() def exists(path): """Check to see if a path exists.""" return True if os.path.exists(path) else False def ls(path): """The contents of a directory.""" return os.listdir(path) def mkdir(path): """Create the given directory path if it doesn't already exist.""" os.makedirs(path, exist_ok=True) return path def open_url(url, task): """Retrieve data from the specified url.""" for attempt in range(0, net.retries): try: return urllib.request.urlopen(url) except OSError: print("Error: {} (retry in {}s)".format(task, net.wait)) time.sleep(net.wait) raise ConnectionError("Halted: Unable to access resource") def urlopen_json(url, task): """Retrieve json data from the specified url.""" for attempt in range(0, net.retries): try: reply = urllib.request.urlopen(url) reply = json.loads(reply.read().decode()) return reply["DATA"]["RECORD"] except: print("Error: {} (retry in {}s)".format(task, net.wait)) time.sleep(net.wait) raise ConnectionError("Halted: Unable to access resource")
"""Functions common to other modules.""" import json import os import re import time import urllib.request from settings import net def clean(name): """Strip all [^a-zA-Z0-9_] characters and convert to lowercase.""" return re.sub(r"\W", r"", name, flags=re.ASCII).lower() def exists(path): """Check to see if a path exists.""" return True if os.path.exists(path) else False def ls(path): """The contents of a directory.""" return os.listdir(path) def mkdir(path): """Create the given directory path if it doesn't already exist.""" os.makedirs(path, exist_ok=True) return path def open_url(url, task): """Retrieve data from the specified url.""" for attempt in range(0, net.retries): try: return urllib.request.urlopen(url) except OSError: print("Error: {} (retry in {}s)".format(task, net.wait)) time.sleep(net.wait) raise ConnectionError("Halted: Unable to access resource") def urlopen_json(url, task="Unknown task"): """Retrieve json data from the specified url.""" for attempt in range(0, net.retries): try: reply = urllib.request.urlopen(url) reply = json.loads(reply.read().decode()) return reply["DATA"]["RECORD"] except: print("Error: {} (retry in {}s)".format(task, net.wait)) time.sleep(net.wait) raise ConnectionError("Halted: Unable to access resource")
Make task an optional argument.
Make task an optional argument.
Python
bsd-2-clause
chingc/DJRivals,chingc/DJRivals
86080d1c06637e1d73784100657fc43bd7326e66
tools/conan/conanfile.py
tools/conan/conanfile.py
from conans import ConanFile, CMake, tools class LibWFUTConan(ConanFile): name = "libwfut" version = "0.2.4" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/libwfut" description = "A client side C++ implementation of WFUT (WorldForge Update Tool)." topics = ("mmorpg", "worldforge") settings = "os", "compiler", "build_type", "arch" options = {"shared": [False, True]} default_options = {"shared": False} generators = "cmake" requires = ["sigc++/2.10.0@worldforge/stable", "zlib/1.2.11", "libcurl/7.66.0@worldforge/stable"] scm = { "type": "git", "url": "https://github.com/worldforge/libwfut.git", "revision": "auto" } def build(self): cmake = CMake(self) cmake.configure(source_folder=".") cmake.build() cmake.install() def package_info(self): self.cpp_info.libs = tools.collect_libs(self) self.cpp_info.includedirs = ["include/wfut-0.2"] def package(self): pass
from conans import ConanFile, CMake, tools class LibWFUTConan(ConanFile): name = "libwfut" version = "0.2.4" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/libwfut" description = "A client side C++ implementation of WFUT (WorldForge Update Tool)." topics = ("mmorpg", "worldforge") settings = "os", "compiler", "build_type", "arch" options = {"shared": [False, True], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} generators = "cmake" requires = ["sigc++/2.10.0@worldforge/stable", "zlib/1.2.11", "libcurl/7.66.0@worldforge/stable"] scm = { "type": "git", "url": "https://github.com/worldforge/libwfut.git", "revision": "auto" } def build(self): cmake = CMake(self) cmake.configure(source_folder=".") cmake.build() cmake.install() def package_info(self): self.cpp_info.libs = tools.collect_libs(self) self.cpp_info.includedirs = ["include/wfut-0.2"] def package(self): pass
Build with PIC by default.
Build with PIC by default.
Python
lgpl-2.1
worldforge/libwfut,worldforge/libwfut,worldforge/libwfut,worldforge/libwfut
bbaf4aa6dbdbb41395b0859260962665b20230ad
__openerp__.py
__openerp__.py
# -*- coding: utf-8 -*- { 'name': 'Chilean VAT Ledger', 'description': ''' Chilean VAT Ledger Management ================================= Creates Sale and Purchase VAT report menus in "accounting/period processing/VAT Ledger" ''', 'version': '0.1', 'author': u'Blanco Martín & Asociados', 'website': 'http://blancomartin.cl', 'depends': [ 'report_aeroo', 'l10n_cl_invoice' ], 'category': 'Reporting subsystems', 'data': [ 'account_vat_report_view.xml', 'report/account_vat_ledger_report.xml', 'security/security.xml', 'security/ir.model.access.csv', ], 'installable': True, 'active': False }
# -*- coding: utf-8 -*- { 'name': 'Chilean VAT Ledger', 'license': 'AGPL-3', 'description': ''' Chilean VAT Ledger Management ================================= Creates Sale and Purchase VAT report menus in "accounting/period processing/VAT Ledger" ''', 'version': '0.1', 'author': u'Blanco Martín & Asociados', 'website': 'http://blancomartin.cl', 'depends': [ 'report_aeroo', 'l10n_cl_invoice' ], 'category': 'Reporting subsystems', 'data': [ 'account_vat_report_view.xml', 'report/account_vat_ledger_report.xml', 'security/security.xml', 'security/ir.model.access.csv', ], 'installable': True, 'active': False }
Set license to AGPL-3 in manifest
Set license to AGPL-3 in manifest
Python
agpl-3.0
odoo-chile/l10n_cl_account_vat_ledger,odoo-chile/l10n_cl_account_vat_ledger
dcd9f381bc7eeaa0ffad72d286bb6dc26ebf37a4
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Sergey Margaritov # Copyright (c) 2013 Sergey Margaritov # # License: MIT # """This module exports the scss-lint plugin linter class.""" import os from SublimeLinter.lint import Linter, util class Scss(Linter): """Provides an interface to the scss-lint executable.""" syntax = ['sass', 'scss'] executable = 'scss-lint' regex = r'^.+?:(?P<line>\d+) (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' tempfile_suffix = 'scss' defaults = { '--include-linter:,': '', '--exclude-linter:,': '' } inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter') comment_re = r'^\s*/[/\*]' config_file = ('--config', '.scss-lint.yml', '~') def cmd(self): if self.get_view_settings().get('bundle-exec', False): return ['bundle', 'exec', self.executable] return [self.executable_path]
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Sergey Margaritov # Copyright (c) 2013 Sergey Margaritov # # License: MIT # """This module exports the scss-lint plugin linter class.""" import os from SublimeLinter.lint import RubyLinter, util class Scss(RubyLinter): """Provides an interface to the scss-lint executable.""" syntax = ('sass', 'scss') executable = 'scss-lint' regex = r'^.+?:(?P<line>\d+) (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' tempfile_suffix = 'scss' defaults = { '--include-linter:,': '', '--exclude-linter:,': '' } inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter') comment_re = r'^\s*/[/\*]' config_file = ('--config', '.scss-lint.yml', '~') def cmd(self): if self.get_view_settings().get('bundle-exec', False): return ('bundle', 'exec', self.executable) return (self.executable_path)
Use RubyLinter instead of Linter so rbenv and rvm are supported
Use RubyLinter instead of Linter so rbenv and rvm are supported
Python
mit
attenzione/SublimeLinter-scss-lint
150e338b7d2793c434d7e2f21aef061f35634476
openspending/test/__init__.py
openspending/test/__init__.py
"""\ OpenSpending test module ======================== Run the OpenSpending test suite by running nosetests in the root of the repository, while in an active virtualenv. See doc/install.rst for more information. """ import os import sys from paste.deploy import appconfig from openspending import mongo from helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] here_dir = os.getcwd() config = appconfig('config:test.ini', relative_to=here_dir) mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown()
"""\ OpenSpending test module ======================== Run the OpenSpending test suite by running nosetests in the root of the repository, while in an active virtualenv. See doc/install.rst for more information. """ import os import sys from pylons import config from openspending import mongo from .helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown()
Use config given on command line
Use config given on command line
Python
agpl-3.0
pudo/spendb,openspending/spendb,openspending/spendb,nathanhilbert/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,johnjohndoe/spendb,USStateDept/FPA_Core,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,openspending/spendb,USStateDept/FPA_Core,spendb/spendb,nathanhilbert/FPA_Core,spendb/spendb,pudo/spendb,spendb/spendb,CivicVision/datahub
37a0cb41a88114ab9edb514e29447756b0c3e92a
tests/test_cli.py
tests/test_cli.py
# -*- coding: utf-8 -*- from click.testing import CliRunner import pytest from cibopath.cli import main from cibopath import __version__ runner = CliRunner() @pytest.fixture(params=['-V', '--version']) def version_cli_flag(request): return request.param def test_cli_group_version_option(version_cli_flag): result = runner.invoke(main, [version_cli_flag]) assert result.exit_code == 0 assert result.output == 'cibopath, version {}\n'.format(__version__)
# -*- coding: utf-8 -*- import pytest from cibopath import __version__ @pytest.fixture(params=['-V', '--version']) def version_cli_flag(request): return request.param def test_cli_group_version_option(cli_runner, version_cli_flag): result = cli_runner([version_cli_flag]) assert result.exit_code == 0 assert result.output == 'cibopath, version {}\n'.format(__version__)
Use cli_runner fixture in test
Use cli_runner fixture in test
Python
bsd-3-clause
hackebrot/cibopath
f814e945d3e62c87c5f86ef5ac37c5feb733b83d
tests/test_ext.py
tests/test_ext.py
from __future__ import absolute_import, unicode_literals import unittest from mopidy import config, ext class ExtensionTest(unittest.TestCase): def setUp(self): # noqa: N802 self.ext = ext.Extension() def test_dist_name_is_none(self): self.assertIsNone(self.ext.dist_name) def test_ext_name_is_none(self): self.assertIsNone(self.ext.ext_name) def test_version_is_none(self): self.assertIsNone(self.ext.version) def test_get_default_config_raises_not_implemented(self): with self.assertRaises(NotImplementedError): self.ext.get_default_config() def test_get_config_schema_returns_extension_schema(self): schema = self.ext.get_config_schema() self.assertIsInstance(schema['enabled'], config.Boolean) def test_validate_environment_does_nothing_by_default(self): self.assertIsNone(self.ext.validate_environment()) def test_setup_raises_not_implemented(self): with self.assertRaises(NotImplementedError): self.ext.setup(None)
from __future__ import absolute_import, unicode_literals import pytest from mopidy import config, ext @pytest.fixture def extension(): return ext.Extension() def test_dist_name_is_none(extension): assert extension.dist_name is None def test_ext_name_is_none(extension): assert extension.ext_name is None def test_version_is_none(extension): assert extension.version is None def test_get_default_config_raises_not_implemented(extension): with pytest.raises(NotImplementedError): extension.get_default_config() def test_get_config_schema_returns_extension_schema(extension): schema = extension.get_config_schema() assert isinstance(schema['enabled'], config.Boolean) def test_validate_environment_does_nothing_by_default(extension): assert extension.validate_environment() is None def test_setup_raises_not_implemented(extension): with pytest.raises(NotImplementedError): extension.setup(None)
Convert ext test to pytests
tests: Convert ext test to pytests
Python
apache-2.0
mokieyue/mopidy,bencevans/mopidy,ZenithDK/mopidy,jodal/mopidy,quartz55/mopidy,pacificIT/mopidy,pacificIT/mopidy,quartz55/mopidy,ali/mopidy,swak/mopidy,tkem/mopidy,bencevans/mopidy,mopidy/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,hkariti/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,ali/mopidy,bacontext/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,dbrgn/mopidy,mopidy/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,bacontext/mopidy,vrs01/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,vrs01/mopidy,dbrgn/mopidy,jcass77/mopidy,glogiotatidis/mopidy,swak/mopidy,bencevans/mopidy,mokieyue/mopidy,adamcik/mopidy,tkem/mopidy,rawdlite/mopidy,bacontext/mopidy,pacificIT/mopidy,ali/mopidy,jcass77/mopidy,rawdlite/mopidy,mopidy/mopidy,vrs01/mopidy,tkem/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,tkem/mopidy,jodal/mopidy,diandiankan/mopidy,jmarsik/mopidy,quartz55/mopidy,ZenithDK/mopidy,jodal/mopidy,ZenithDK/mopidy,jmarsik/mopidy,swak/mopidy,ZenithDK/mopidy,bacontext/mopidy,kingosticks/mopidy,quartz55/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,hkariti/mopidy,ali/mopidy,hkariti/mopidy,adamcik/mopidy,vrs01/mopidy,rawdlite/mopidy,hkariti/mopidy,rawdlite/mopidy,mokieyue/mopidy,adamcik/mopidy,swak/mopidy,kingosticks/mopidy,bencevans/mopidy,jmarsik/mopidy,jcass77/mopidy
27ffcae96c5dce976517035b25a5c72f10e2ec99
tool_spatialdb.py
tool_spatialdb.py
# SpatialDB scons tool # # It builds the library for the SpatialDB C++ class library, # and provides CPP and linker specifications for the header # and libraries. # # SpatialDB depends on SqliteDB, which provides the interface to # sqlite3. It also depends on SpatiaLite. Since SpatiaLite is # is also needed by SQLiteDB, we let the sqlitedb tool provide # the required SpatiaLite plumbing. import os import sys import eol_scons tools = ['sqlitedb','doxygen','prefixoptions'] env = Environment(tools = ['default'] + tools) platform = env['PLATFORM'] thisdir = env.Dir('.').srcnode().abspath # define the tool def spatialdb(env): env.AppendUnique(CPPPATH =[thisdir,]) env.AppendLibrary('spatialdb') env.AppendLibrary('geos') env.AppendLibrary('geos_c') env.AppendLibrary('proj') if (platform != 'posix'): env.AppendLibrary('iconv') env.Replace(CCFLAGS=['-g','-O2']) env.Require(tools) Export('spatialdb') # build the SpatialDB library libsources = Split(""" SpatiaLiteDB.cpp """) headers = Split(""" SpatiaLiteDB.h """) libspatialdb = env.Library('spatialdb', libsources) env.Default(libspatialdb) html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
# SpatialDB scons tool # # It builds the library for the SpatialDB C++ class library, # and provides CPP and linker specifications for the header # and libraries. # # SpatialDB depends on SqliteDB, which provides the interface to # sqlite3. It also depends on SpatiaLite. Since SpatiaLite is # is also needed by SQLiteDB, we let the sqlitedb tool provide # the required SpatiaLite plumbing. import os import sys import eol_scons tools = ['sqlitedb','doxygen','prefixoptions'] env = Environment(tools = ['default'] + tools) platform = env['PLATFORM'] thisdir = env.Dir('.').srcnode().abspath # define the tool def spatialdb(env): env.AppendUnique(CPPPATH =[thisdir,]) env.AppendLibrary('spatialdb') env.AppendLibrary('geos') env.AppendLibrary('geos_c') env.AppendLibrary('proj') if (platform != 'posix'): env.AppendLibrary('iconv') env.Require(tools) Export('spatialdb') # build the SpatialDB library libsources = Split(""" SpatiaLiteDB.cpp """) headers = Split(""" SpatiaLiteDB.h """) libspatialdb = env.Library('spatialdb', libsources) env.Default(libspatialdb) html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
Python
bsd-3-clause
ncareol/spatialdb,ncareol/spatialdb
da59d7481668a7133eebcd12b4d5ecfb655296a6
test/test_blob_filter.py
test/test_blob_filter.py
"""Test the blob filter.""" from pathlib import Path from typing import Sequence, Tuple from unittest.mock import MagicMock import pytest from git.index.typ import BlobFilter, StageType from git.objects import Blob from git.types import PathLike # fmt: off @pytest.mark.parametrize('paths, stage_type, path, expected_result', [ ((Path("foo"),), 0, Path("foo"), True), ((Path("foo"),), 0, Path("foo/bar"), True), ((Path("foo/bar"),), 0, Path("foo"), False), ((Path("foo"), Path("bar")), 0, Path("foo"), True), ]) # fmt: on def test_blob_filter(paths: Sequence[PathLike], stage_type: StageType, path: PathLike, expected_result: bool) -> None: """Test the blob filter.""" blob_filter = BlobFilter(paths) binsha = MagicMock(__len__=lambda self: 20) blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path) stage_blob: Tuple[StageType, Blob] = (stage_type, blob) result = blob_filter(stage_blob) assert result == expected_result
"""Test the blob filter.""" from pathlib import Path from typing import Sequence, Tuple from unittest.mock import MagicMock import pytest from git.index.typ import BlobFilter, StageType from git.objects import Blob from git.types import PathLike # fmt: off @pytest.mark.parametrize('paths, path, expected_result', [ ((Path("foo"),), Path("foo"), True), ((Path("foo"),), Path("foo/bar"), True), ((Path("foo/bar"),), Path("foo"), False), ((Path("foo"), Path("bar")), Path("foo"), True), ]) # fmt: on def test_blob_filter(paths: Sequence[PathLike], path: PathLike, expected_result: bool) -> None: """Test the blob filter.""" blob_filter = BlobFilter(paths) binsha = MagicMock(__len__=lambda self: 20) stage_type: StageType = 0 blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path) stage_blob: Tuple[StageType, Blob] = (stage_type, blob) result = blob_filter(stage_blob) assert result == expected_result
Remove stage type as parameter from blob filter test
Remove stage type as parameter from blob filter test
Python
bsd-3-clause
gitpython-developers/GitPython,gitpython-developers/gitpython,gitpython-developers/GitPython,gitpython-developers/gitpython
431ca4f2d44656ef9f97be50718712c6f3a0fa9b
qtawesome/tests/test_qtawesome.py
qtawesome/tests/test_qtawesome.py
r""" Tests for QtAwesome. """ # Standard library imports import subprocess # Test Library imports import pytest # Local imports import qtawesome as qta from qtawesome.iconic_font import IconicFont def test_segfault_import(): output_number = subprocess.call('python -c "import qtawesome ' '; qtawesome.icon()"', shell=True) assert output_number == 0 def test_unique_font_family_name(qtbot): """ Test that each font used by qtawesome has a unique name. If this test fails, this probably means that you need to rename the family name of some fonts. Please see PR #98 for more details on why it is necessary and on how to do this. Regression test for Issue #107 """ resource = qta._instance() assert isinstance(resource, IconicFont) prefixes = list(resource.fontname.keys()) assert prefixes fontnames = set(resource.fontname.values()) assert fontnames assert len(prefixes) == len(fontnames) if __name__ == "__main__": pytest.main()
r""" Tests for QtAwesome. """ # Standard library imports import subprocess import collections # Test Library imports import pytest # Local imports import qtawesome as qta from qtawesome.iconic_font import IconicFont def test_segfault_import(): output_number = subprocess.call('python -c "import qtawesome ' '; qtawesome.icon()"', shell=True) assert output_number == 0 def test_unique_font_family_name(qtbot): """ Test that each font used by qtawesome has a unique name. If this test fails, this probably means that you need to rename the family name of some fonts. Please see PR #98 for more details on why it is necessary and on how to do this. Regression test for Issue #107 """ resource = qta._instance() assert isinstance(resource, IconicFont) # Check that the fonts were loaded successfully. fontnames = resource.fontname.values() assert fontnames # Check that qtawesome does not load fonts with duplicate family names. duplicates = [fontname for fontname, count in collections.Counter(fontnames).items() if count > 1] assert not duplicates if __name__ == "__main__": pytest.main()
Make the test more comprehensive.
Make the test more comprehensive.
Python
mit
spyder-ide/qtawesome
3d8ec94e61735b84c3b24b44d79fcd57611a93ee
mndeps.py
mndeps.py
#!/usr/bin/env python # XXX: newer mininet version also has MinimalTopo from mininet.topo import ( SingleSwitchTopo, LinearTopo, SingleSwitchReversedTopo ) from mininet.topolib import TreeTopo from mininet.util import buildTopo import psycopg2 TOPOS = { 'linear': LinearTopo, 'reversed': SingleSwitchReversedTopo, 'single': SingleSwitchTopo, 'tree': TreeTopo, 'torus': TorusTopo } def build(opts): return buildTopo(TOPOS, opts)
#!/usr/bin/env python # XXX: newer mininet version also has MinimalTopo from mininet.topo import ( SingleSwitchTopo, LinearTopo, SingleSwitchReversedTopo ) from mininet.topolib import TreeTopo from mininet.util import buildTopo import psycopg2 TOPOS = { 'linear': LinearTopo, 'reversed': SingleSwitchReversedTopo, 'single': SingleSwitchTopo, 'tree': TreeTopo } def build(opts): return buildTopo(TOPOS, opts)
Fix bug after removing torus
Fix bug after removing torus
Python
apache-2.0
ravel-net/ravel,ravel-net/ravel
8ac492be603f958a29bbc6bb5215d79ec469d269
tests/test_init.py
tests/test_init.py
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "USER"} ] BAD_CHECKERS = [ {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
"""Test the checkers""" from nose.tools import ok_, eq_ from preflyt import check CHECKERS = [ {"checker": "env", "name": "PATH"} ] BAD_CHECKERS = [ {"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"} ] def test_everything(): """Test the check method.""" good, results = check(CHECKERS) ok_(good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0]) def test_everything_failure(): """Test the check method.""" good, results = check(BAD_CHECKERS) ok_(not good, results) eq_(len(results), 1) for field_name in ('check', 'success', 'message'): ok_(field_name in results[0])
Update environment test to have cross platform support
Update environment test to have cross platform support
Python
mit
humangeo/preflyt
131fb74b0f399ad3abff5dcc2b09621cac1226e7
config/nox_routing.py
config/nox_routing.py
from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use NOX as our controller command_line = "./nox_core -i ptcp:6633 routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
from experiment_config_lib import ControllerConfig from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig from sts.topology import MeshTopology # Use NOX as our controller command_line = "./nox_core -v -i ptcp:6633 sample_routing" controllers = [ControllerConfig(command_line, cwd="nox_classic/build/src", address="127.0.0.1", port=6633)] topology_class = MeshTopology topology_params = "num_switches=4" dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" # dataplane_trace = "dataplane_traces/ping_pong_fat_tree.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace) #simulation_config = SimulationConfig(controller_configs=controllers, # dataplane_trace=dataplane_trace) # Use a Fuzzer (already the default) control_flow = Fuzzer(simulation_config, input_logger=InputLogger(), check_interval=80, invariant_check=InvariantChecker.check_connectivity)
Update NOX config to use sample_routing
Update NOX config to use sample_routing
Python
apache-2.0
ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts
96e86fb389d67d55bf6b4e0f3f0f318e75b532dd
kirppu/management/commands/accounting_data.py
kirppu/management/commands/accounting_data.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) accounting_receipt(self.stdout)
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument('--lang', type=str, help="Change language, for example: en") parser.add_argument('event', type=str, help="Event slug to dump data for") def handle(self, *args, **options): if "lang" in options: activate(options["lang"]) from kirppu.models import Event event = Event.objects.get(slug=options["event"]) accounting_receipt(self.stdout, event)
Fix accounting data dump command.
Fix accounting data dump command.
Python
mit
jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu
fc076d4b390c8e28fceb9613b04423ad374930e5
config/fuzz_pox_mesh.py
config/fuzz_pox_mesh.py
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose openflow.debug ''' #sts.syncproto.pox_syncer ''' '''forwarding.l2_multi ''' #'''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [ControllerConfig(command_line, cwd="betta")] topology_class = MeshTopology topology_params = "num_switches=2" dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=False) control_flow = Fuzzer(simulation_config, check_interval=80, halt_on_violation=False, input_logger=InputLogger(), invariant_check=InvariantChecker.check_connectivity) #control_flow = Interactive(simulation_config, input_logger=InputLogger())
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose sts.syncproto.pox_syncer ''' '''openflow.discovery forwarding.l2_multi ''' '''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [ControllerConfig(command_line, cwd="pox", sync="tcp:localhost:18899")] topology_class = MeshTopology topology_params = "num_switches=2" dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=True) control_flow = Fuzzer(simulation_config, check_interval=80, halt_on_violation=False, input_logger=InputLogger(), invariant_check=InvariantChecker.check_loops) #control_flow = Interactive(simulation_config, input_logger=InputLogger())
Switch to normal pox instead of betta
Switch to normal pox instead of betta
Python
apache-2.0
jmiserez/sts,jmiserez/sts,ucb-sts/sts,ucb-sts/sts
ca75631f513c433c6024a2f00d045f304703a85d
webapp/tests/test_browser.py
webapp/tests/test_browser.py
import os from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
import os from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from . import DATA_DIR class BrowserTest(TestCase): def test_browser(self): url = reverse('graphite.browser.views.browser') response = self.client.get(url) self.assertContains(response, 'Graphite Browser') def test_header(self): self.assertEqual(User.objects.count(), 0) url = reverse('graphite.browser.views.header') response = self.client.get(url) self.assertContains(response, 'Graphite Browser Header') # Graphite has created a default user self.assertEqual(User.objects.get().username, 'default') @override_settings(INDEX_FILE=os.path.join(DATA_DIR, 'index')) def test_search(self): url = reverse('graphite.browser.views.search') response = self.client.post(url) self.assertEqual(response.content, '') # simple query response = self.client.post(url, {'query': 'collectd'}) self.assertEqual(response.content.split(',')[0], 'collectd.test.df-root.df_complex-free') # No match response = self.client.post(url, {'query': 'other'}) self.assertEqual(response.content, '') # Multiple terms (OR) response = self.client.post(url, {'query': 'midterm shortterm'}) self.assertEqual(response.content.split(','), ['collectd.test.load.load.midterm', 'collectd.test.load.load.shortterm'])
Add tests for making sure a user is dynamically created
Add tests for making sure a user is dynamically created
Python
apache-2.0
EinsamHauer/graphite-web-iow,bpaquet/graphite-web,Skyscanner/graphite-web,disqus/graphite-web,synedge/graphite-web,gwaldo/graphite-web,blacked/graphite-web,cosm0s/graphite-web,brutasse/graphite-web,blacked/graphite-web,bbc/graphite-web,gwaldo/graphite-web,Invoca/graphite-web,atnak/graphite-web,deniszh/graphite-web,dhtech/graphite-web,DanCech/graphite-web,Skyscanner/graphite-web,nkhuyu/graphite-web,jssjr/graphite-web,esnet/graphite-web,cgvarela/graphite-web,JeanFred/graphite-web,nkhuyu/graphite-web,graphite-project/graphite-web,bruce-lyft/graphite-web,bmhatfield/graphite-web,phreakocious/graphite-web,redice/graphite-web,EinsamHauer/graphite-web-iow,zBMNForks/graphite-web,kkdk5535/graphite-web,pu239ppy/graphite-web,krux/graphite-web,Invoca/graphite-web,jssjr/graphite-web,krux/graphite-web,edwardmlyte/graphite-web,Squarespace/graphite-web,EinsamHauer/graphite-web-iow,DanCech/graphite-web,bpaquet/graphite-web,phreakocious/graphite-web,bpaquet/graphite-web,cosm0s/graphite-web,axibase/graphite-web,lyft/graphite-web,atnak/graphite-web,graphite-server/graphite-web,axibase/graphite-web,Skyscanner/graphite-web,Invoca/graphite-web,kkdk5535/graphite-web,axibase/graphite-web,piotr1212/graphite-web,synedge/graphite-web,DanCech/graphite-web,SEJeff/graphite-web,SEJeff/graphite-web,graphite-server/graphite-web,pu239ppy/graphite-web,lfckop/graphite-web,cgvarela/graphite-web,DanCech/graphite-web,johnseekins/graphite-web,brutasse/graphite-web,Aloomaio/graphite-web,markolson/graphite-web,redice/graphite-web,penpen/graphite-web,axibase/graphite-web,cbowman0/graphite-web,bbc/graphite-web,mcoolive/graphite-web,lyft/graphite-web,nkhuyu/graphite-web,section-io/graphite-web,dhtech/graphite-web,ZelunZhang/graphite-web,bmhatfield/graphite-web,bpaquet/graphite-web,atnak/graphite-web,cgvarela/graphite-web,mcoolive/graphite-web,bmhatfield/graphite-web,edwardmlyte/graphite-web,nkhuyu/graphite-web,cosm0s/graphite-web,lyft/graphite-web,phreakocious/graphite-web,Squarespace/graphite-web,bbc/graphite-web,esnet/graphite-web,AICIDNN/graphite-web,dbn/graphite-web,JeanFred/graphite-web,JeanFred/graphite-web,SEJeff/graphite-web,markolson/graphite-web,Invoca/graphite-web,gwaldo/graphite-web,johnseekins/graphite-web,redice/graphite-web,goir/graphite-web,piotr1212/graphite-web,obfuscurity/graphite-web,cgvarela/graphite-web,bruce-lyft/graphite-web,jssjr/graphite-web,drax68/graphite-web,cosm0s/graphite-web,Invoca/graphite-web,mcoolive/graphite-web,g76r/graphite-web,kkdk5535/graphite-web,cybem/graphite-web-iow,cybem/graphite-web-iow,gwaldo/graphite-web,ZelunZhang/graphite-web,dhtech/graphite-web,Squarespace/graphite-web,phreakocious/graphite-web,criteo-forks/graphite-web,bmhatfield/graphite-web,Aloomaio/graphite-web,lfckop/graphite-web,johnseekins/graphite-web,atnak/graphite-web,SEJeff/graphite-web,section-io/graphite-web,edwardmlyte/graphite-web,bruce-lyft/graphite-web,drax68/graphite-web,phreakocious/graphite-web,redice/graphite-web,nkhuyu/graphite-web,deniszh/graphite-web,bbc/graphite-web,redice/graphite-web,Skyscanner/graphite-web,EinsamHauer/graphite-web-iow,JeanFred/graphite-web,johnseekins/graphite-web,goir/graphite-web,blacked/graphite-web,graphite-project/graphite-web,brutasse/graphite-web,graphite-project/graphite-web,zBMNForks/graphite-web,bpaquet/graphite-web,obfuscurity/graphite-web,piotr1212/graphite-web,synedge/graphite-web,criteo-forks/graphite-web,DanCech/graphite-web,deniszh/graphite-web,bpaquet/graphite-web,disqus/graphite-web,markolson/graphite-web,g76r/graphite-web,axibase/graphite-web,edwardmlyte/graphite-web,jssjr/graphite-web,graphite-server/graphite-web,criteo-forks/graphite-web,zBMNForks/graphite-web,dhtech/graphite-web,phreakocious/graphite-web,cybem/graphite-web-iow,AICIDNN/graphite-web,esnet/graphite-web,g76r/graphite-web,synedge/graphite-web,dbn/graphite-web,criteo-forks/graphite-web,Skyscanner/graphite-web,section-io/graphite-web,johnseekins/graphite-web,obfuscurity/graphite-web,JeanFred/graphite-web,DanCech/graphite-web,pu239ppy/graphite-web,lyft/graphite-web,section-io/graphite-web,krux/graphite-web,cosm0s/graphite-web,cbowman0/graphite-web,drax68/graphite-web,lfckop/graphite-web,lyft/graphite-web,goir/graphite-web,Squarespace/graphite-web,Aloomaio/graphite-web,blacked/graphite-web,lfckop/graphite-web,graphite-project/graphite-web,goir/graphite-web,synedge/graphite-web,Invoca/graphite-web,atnak/graphite-web,dbn/graphite-web,zBMNForks/graphite-web,bbc/graphite-web,goir/graphite-web,bmhatfield/graphite-web,g76r/graphite-web,disqus/graphite-web,krux/graphite-web,deniszh/graphite-web,dhtech/graphite-web,atnak/graphite-web,cybem/graphite-web-iow,dbn/graphite-web,disqus/graphite-web,johnseekins/graphite-web,mcoolive/graphite-web,AICIDNN/graphite-web,cgvarela/graphite-web,piotr1212/graphite-web,penpen/graphite-web,synedge/graphite-web,mcoolive/graphite-web,criteo-forks/graphite-web,zBMNForks/graphite-web,bruce-lyft/graphite-web,markolson/graphite-web,ZelunZhang/graphite-web,cbowman0/graphite-web,g76r/graphite-web,goir/graphite-web,penpen/graphite-web,lyft/graphite-web,JeanFred/graphite-web,cybem/graphite-web-iow,lfckop/graphite-web,ZelunZhang/graphite-web,cbowman0/graphite-web,gwaldo/graphite-web,cybem/graphite-web-iow,Squarespace/graphite-web,AICIDNN/graphite-web,SEJeff/graphite-web,kkdk5535/graphite-web,graphite-project/graphite-web,brutasse/graphite-web,piotr1212/graphite-web,cbowman0/graphite-web,krux/graphite-web,AICIDNN/graphite-web,esnet/graphite-web,Squarespace/graphite-web,deniszh/graphite-web,graphite-server/graphite-web,ZelunZhang/graphite-web,Skyscanner/graphite-web,blacked/graphite-web,dbn/graphite-web,kkdk5535/graphite-web,mcoolive/graphite-web,graphite-project/graphite-web,criteo-forks/graphite-web,EinsamHauer/graphite-web-iow,edwardmlyte/graphite-web,disqus/graphite-web,bruce-lyft/graphite-web,g76r/graphite-web,Aloomaio/graphite-web,drax68/graphite-web,pu239ppy/graphite-web,edwardmlyte/graphite-web,dbn/graphite-web,deniszh/graphite-web,drax68/graphite-web,lfckop/graphite-web,penpen/graphite-web,nkhuyu/graphite-web,section-io/graphite-web,pu239ppy/graphite-web,ZelunZhang/graphite-web,piotr1212/graphite-web,penpen/graphite-web,zBMNForks/graphite-web,obfuscurity/graphite-web,bruce-lyft/graphite-web,graphite-server/graphite-web,section-io/graphite-web,bmhatfield/graphite-web,jssjr/graphite-web,kkdk5535/graphite-web,graphite-server/graphite-web,esnet/graphite-web,cosm0s/graphite-web,obfuscurity/graphite-web,axibase/graphite-web,penpen/graphite-web,markolson/graphite-web,jssjr/graphite-web,Aloomaio/graphite-web,Aloomaio/graphite-web,cbowman0/graphite-web,pu239ppy/graphite-web,krux/graphite-web,disqus/graphite-web,brutasse/graphite-web,obfuscurity/graphite-web,redice/graphite-web,EinsamHauer/graphite-web-iow,AICIDNN/graphite-web,blacked/graphite-web,gwaldo/graphite-web,brutasse/graphite-web,cgvarela/graphite-web,drax68/graphite-web
20bd5c16d5850f988e92c39db3ff041c37c83b73
contract_sale_generation/models/abstract_contract.py
contract_sale_generation/models/abstract_contract.py
# Copyright 2017 Pesol (<http://pesol.es>) # Copyright 2017 Angel Moya <angel.moya@pesol.es> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _get_generation_type_selection(self): res = super()._get_generation_type_selection() res.append(("sale", "Sale")) return res
# Copyright 2017 Pesol (<http://pesol.es>) # Copyright 2017 Angel Moya <angel.moya@pesol.es> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
Align method on Odoo conventions
[14.0][IMP] contract_sale_generation: Align method on Odoo conventions
Python
agpl-3.0
OCA/contract,OCA/contract,OCA/contract
6422f6057d43dfb5259028291991f39c5b81b446
spreadflow_core/flow.py
spreadflow_core/flow.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict class Flowmap(dict): def __init__(self): super(Flowmap, self).__init__() self.decorators = [] self.annotations = {} def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from collections import defaultdict, MutableMapping class Flowmap(MutableMapping): def __init__(self): super(Flowmap, self).__init__() self.annotations = {} self.connections = {} self.decorators = [] def __getitem__(self, key): return self.connections[key] def __setitem__(self, key, value): self.connections[key] = value def __delitem__(self, key): del self.connections[key] def __iter__(self): return iter(self.connections) def __len__(self): return len(self.connections) def graph(self): result = defaultdict(set) backlog = set() processed = set() for port_out, port_in in self.iteritems(): result[port_out].add(port_in) backlog.add(port_in) while len(backlog): node = backlog.pop() if node in processed: continue else: processed.add(node) try: arcs = tuple(node.dependencies) except AttributeError: continue for port_out, port_in in arcs: result[port_out].add(port_in) backlog.add(port_out) backlog.add(port_in) return result
Refactor Flowmap into a MutableMapping
Refactor Flowmap into a MutableMapping
Python
mit
spreadflow/spreadflow-core,znerol/spreadflow-core
45810cb89a26a305df0724b0f27f6136744b207f
bookshop/bookshop/urls.py
bookshop/bookshop/urls.py
"""bookshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
"""bookshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from books import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), ]
Add a URL to urlpatterns for home page
Add a URL to urlpatterns for home page
Python
mit
djangogirlstaipei/eshop,djangogirlstaipei/eshop,djangogirlstaipei/eshop,djangogirlstaipei/eshop
5beb443d4c9cf834be03ff33a2fb01605f8feb80
pyof/v0x01/symmetric/hello.py
pyof/v0x01/symmetric/hello.py
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8)
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) elements = BinaryData()
Add optional elements in v0x01 Hello
Add optional elements in v0x01 Hello For spec compliance. Ignore the elements as they're not used. Fix #379
Python
mit
kytos/python-openflow
015d536e591d5af7e93f299e84504fe8a17f76b3
tests.py
tests.py
import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run")
import logging import unittest from StringIO import StringIO class TestArgParsing(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from script import parseargs self.parseargs = parseargs def test_parseargs(self): opts, args = self.parseargs(["foo"]) self.assertEqual(opts.silent, False) self.assertEqual(args, []) class TestMain(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) root = logging.getLogger() buffer = logging.handlers.BufferingHandler(100) root.addHandler(buffer) self.buffer = buffer.buffer self.out = StringIO() self.err = StringIO() def main(self, *args, **kwargs): from script import main _kwargs = { "out": self.out, "err": self.err, } _kwargs.update(kwargs) return main(*args, **_kwargs) def test_main(self): result = self.main(["foo"]) self.assertEqual(result, None) self.assertEqual(self.buffer, []) def test_main_verbose(self): result = self.main(["foo", "-vv"]) self.assertEqual(result, None) self.assertEqual(len(self.buffer), 1) self.assertEqual(self.buffer[0].msg, "Ready to run") self.assertTrue("Ready to run" in self.err.getvalue())
Test that log messages go to stderr.
Test that log messages go to stderr.
Python
isc
whilp/python-script,whilp/python-script
bc6001d6c25bdb5d83830e5a65fe5aea9fc1eb99
ume/cmd.py
ume/cmd.py
# -*- coding: utf-8 -*- import logging as l import argparse from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) else: raise RuntimeError("No such sub-command.")
# -*- coding: utf-8 -*- import logging as l import argparse import os from ume.utils import ( save_mat, dynamic_load, ) def parse_args(): p = argparse.ArgumentParser( description='CLI interface UME') p.add_argument('--config', dest='inifile', default='config.ini') subparsers = p.add_subparsers( dest='subparser_name', help='sub-commands for instant action') f_parser = subparsers.add_parser('feature') f_parser.add_argument('-n', '--name', type=str, required=True) i_parser = subparsers.add_parser('init') subparsers.add_parser('validation') subparsers.add_parser('prediction') return p.parse_args() def run_feature(args): klass = dynamic_load(args.name) result = klass() save_mat(args.name, result) def run_initialize(args): pwd = os.getcwd() os.makedirs(os.path.join(pwd, "data/input")) os.makedirs(os.path.join(pwd, "data/output")) os.makedirs(os.path.join(pwd, "data/working")) os.makedirs(os.path.join(pwd, "note")) os.makedirs(os.path.join(pwd, "trunk")) def main(): l.basicConfig(format='%(asctime)s %(message)s', level=l.INFO) args = parse_args() if args.subparser_name == 'validate': pass elif args.subparser_name == 'predict': pass elif args.subparser_name == 'feature': run_feature(args) elif args.subparser_name == 'init': run_initialize(args) else: raise RuntimeError("No such sub-command.")
Add init function to create directories
Add init function to create directories
Python
mit
smly/ume,smly/ume,smly/ume,smly/ume
1b75fe13249eba8d951735ad422dc512b1e28caf
test/test_all_stores.py
test/test_all_stores.py
import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore
import os import store_fixture import groundstation.store class TestGitStore(store_fixture.StoreTestCase): storeClass = groundstation.store.git_store.GitStore def test_creates_required_dirs(self): for d in groundstation.store.git_store.GitStore.required_dirs: path = os.path.join(self.path, d) self.assertTrue(os.path.exists(path)) self.assertTrue(os.path.isdir(path))
Add testcase for database initialization
Add testcase for database initialization
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
2f9a4029e909f71539f3b7326b867e27386c3378
tests/interface_test.py
tests/interface_test.py
import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
import unittest import aiozmq class ZmqTransportTests(unittest.TestCase): def test_interface(self): tr = aiozmq.ZmqTransport() self.assertRaises(NotImplementedError, tr.write, [b'data']) self.assertRaises(NotImplementedError, tr.abort) self.assertRaises(NotImplementedError, tr.getsockopt, 1) self.assertRaises(NotImplementedError, tr.setsockopt, 1, 2) self.assertRaises(NotImplementedError, tr.set_write_buffer_limits) self.assertRaises(NotImplementedError, tr.get_write_buffer_size) self.assertRaises(NotImplementedError, tr.pause_reading) self.assertRaises(NotImplementedError, tr.resume_reading) self.assertRaises(NotImplementedError, tr.bind, 'endpoint') self.assertRaises(NotImplementedError, tr.unbind, 'endpoint') self.assertRaises(NotImplementedError, tr.bindings) self.assertRaises(NotImplementedError, tr.connect, 'endpoint') self.assertRaises(NotImplementedError, tr.disconnect, 'endpoint') self.assertRaises(NotImplementedError, tr.connections) self.assertRaises(NotImplementedError, tr.subscribe, b'filter') self.assertRaises(NotImplementedError, tr.unsubscribe, b'filter') self.assertRaises(NotImplementedError, tr.subscriptions) class ZmqProtocolTests(unittest.TestCase): def test_interface(self): pr = aiozmq.ZmqProtocol() self.assertIsNone(pr.msg_received((b'data',)))
Add missing tests for interfaces
Add missing tests for interfaces
Python
bsd-2-clause
MetaMemoryT/aiozmq,claws/aiozmq,asteven/aiozmq,aio-libs/aiozmq
5b3d26b6c9256f869d3bc08dfa00bf9b8de58f85
tests/test_cli_parse.py
tests/test_cli_parse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.TemporaryDirectory() as d: out_file = os.path.join(d, 'model_out.hdf5') runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix]) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix) models_equal(model_res, model_reference)
Change from TemporaryDirectory to NamedTemporaryFile
Change from TemporaryDirectory to NamedTemporaryFile
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
62cee7d5a625bb3515eddaddbe940239a41ba31c
rest_framework_msgpack/parsers.py
rest_framework_msgpack/parsers.py
import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc))
import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
Use six.text_type for python3 compat
Use six.text_type for python3 compat
Python
bsd-3-clause
juanriaza/django-rest-framework-msgpack
19bae697bc6e017a97eef77d1425d1ccfbe27ff6
vprof/__main__.py
vprof/__main__.py
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source print('Collecting profile stats...') program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 _PROFILE_MAP = { 'c': profile.CProfile } def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('profilers', metavar='opts', help='Profilers configuration') parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source program_name = args.source[0] if len(args.profilers) > len(set(args.profilers)): print('Profiler configuration is ambiguous. Remove duplicates.') sys.exit(1) for prof_option in args.profilers: if prof_option not in _PROFILE_MAP: print('Unrecognized option: %s' % prof_option) sys.exit(2) print('Collecting profile stats...') prof_option = args.profilers[0] profiler = _PROFILE_MAP[prof_option] program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
Add profilers selection as CLI option.
Add profilers selection as CLI option.
Python
bsd-2-clause
nvdv/vprof,nvdv/vprof,nvdv/vprof
5e7cce09a6e6a847dad1714973fddb53d60c4c3f
yawf_sample/simple/models.py
yawf_sample/simple/models.py
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) @reversion.register class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False)
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) reversion.register(Window)
Fix reversion register in sample app
Fix reversion register in sample app
Python
mit
freevoid/yawf
d970f2e4dc1d040bd352a68f6ebe4d3df93d19f7
web/celSearch/api/scripts/query_wikipedia.py
web/celSearch/api/scripts/query_wikipedia.py
''' Script used to query Wikipedia for summary of object ''' import sys import wikipedia def main(): # Check that we have the right number of arguments if (len(sys.argv) != 2): print 'Incorrect number of arguments; please pass in only one string that contains the subject' return 'Banana' print wikipedia.summary(sys.argv[1]).encode('utf-8') #return wikipedia.summary(sys.argv[1]) if __name__ == '__main__': main()
''' Script used to query Wikipedia for summary of object ''' import sys import wikipedia import nltk def main(): # Check that we have the right number of arguments if (len(sys.argv) != 2): print 'Incorrect number of arguments; please pass in only one string that contains the query' return 'Banana' # Get the noun from the query (uses the first noun it finds for now) print sys.argv[0] tokens = nltk.word_tokenize(sys.argv[1]) tagged = nltk.pos_tag(tokens) # Find first noun in query and provide Wikipedia summary for it for tag in tagged: if tag[1][0] == 'N': print wikipedia.summary(tag[0]).encode('utf-8') return if __name__ == '__main__': main()
Send query from android device to server
Send query from android device to server
Python
apache-2.0
christopher18/Celsearch,christopher18/Celsearch,christopher18/Celsearch
d15f6df74b8fe188a7a80c3491aeec62c35ce415
policy.py
policy.py
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version.replace('.', '_') return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version[:version.rindex('.')] return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
Check for the first part of the version string
Check for the first part of the version string Older CentOS Linux images only used the xxxx part of the full xxxx.yy version string from Atlas.
Python
mit
lpancescu/atlas-lint
c7ba0ecbbe263fbf7378edbc45fcbbefb150a8fb
tests/test_probabilistic_interleave_speed.py
tests/test_probabilistic_interleave_speed.py
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il.Probabilistic([r1, r2]) ranking = method.interleave() print(list(ranking))
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(range(150, 250)) for i in range(1000): method = il.Probabilistic([r1, r2, r3, r4]) ranking = method.interleave() method.evaluate(ranking, [0, 1, 2])
Add tests for measuring the speed of probabilistic interleaving
Add tests for measuring the speed of probabilistic interleaving
Python
mit
mpkato/interleaving
2965891b46e89e0d7222ec16a2327f2bdef86f52
chemex/util.py
chemex/util.py
"""The util module contains a variety of utility functions.""" import configparser import sys def read_cfg_file(filename): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) config.optionxform = str try: out = config.read(str(filename)) if not out and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
"""The util module contains a variety of utility functions.""" import configparser import sys def listfloat(text): return [float(val) for val in text.strip("[]").split(",")] def read_cfg_file(filename=None): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser( comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat ) config.optionxform = str try: result = config.read(str(filename)) if not result and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
Update settings for reading config files
Update settings for reading config files Update the definition of comments, now only allowing the use of "#" for comments. Add a converter function to parse list of floats, such as: list_of_floats = [1.0, 2.0, 3.0]
Python
bsd-3-clause
gbouvignies/chemex
b6e9e37350a4b435df00a54b2ccd9da70a4db788
nogotofail/mitm/util/ip.py
nogotofail/mitm/util/ip.py
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
Fix local interface addr parsing On Fedora 21 the format of ifconfig is a little different. Fixes #17
Python
apache-2.0
google/nogotofail,leasual/nogotofail,mkenne11/nogotofail,joshcooper/nogotofail,digideskio/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,google/nogotofail,mkenne11/nogotofail,digideskio/nogotofail,leasual/nogotofail,mkenne11/nogotofail-pii
79b5227deaf830a9ce51d18387372fe6cf88e51d
monasca_setup/detection/plugins/neutron.py
monasca_setup/detection/plugins/neutron.py
import monasca_setup.detection class Neutron(monasca_setup.detection.ServicePlugin): """Detect Neutron daemons and setup configuration to monitor them. """ def __init__(self, template_dir, overwrite=True, args=None): service_params = { 'args': args, 'template_dir': template_dir, 'overwrite': overwrite, 'service_name': 'networking', 'process_names': ['neutron-server', 'neutron-openvswitch-agent', 'neutron-rootwrap', 'neutron-dhcp-agent', 'neutron-vpn-agent', 'neutron-metadata-agent', 'neutron-metering-agent', 'neutron-l3-agent', 'neutron-ns-metadata-proxy', '/opt/stack/service/neutron/venv/bin/neutron-lbaas-agent', '/opt/stack/service/neutron/venv/bin/neutron-lbaasv2-agent', 'neutron-l2gateway-agent'], 'service_api_url': 'http://localhost:9696', 'search_pattern': '.*v2.0.*' } super(Neutron, self).__init__(service_params) def build_config(self): """Build the config as a Plugins object and return.""" # Skip the http check if neutron-server is not on this box if 'neutron-server' not in self.found_processes: self.service_api_url = None self.search_pattern = None return monasca_setup.detection.ServicePlugin.build_config(self)
import monasca_setup.detection class Neutron(monasca_setup.detection.ServicePlugin): """Detect Neutron daemons and setup configuration to monitor them. """ def __init__(self, template_dir, overwrite=True, args=None): service_params = { 'args': args, 'template_dir': template_dir, 'overwrite': overwrite, 'service_name': 'networking', 'process_names': ['neutron-server', 'neutron-openvswitch-agent', 'neutron-rootwrap', 'neutron-dhcp-agent', 'neutron-vpn-agent', 'neutron-metadata-agent', 'neutron-metering-agent', 'neutron-l3-agent', 'neutron-ns-metadata-proxy', 'bin/neutron-lbaas-agent', 'neutron-lbaasv2-agent', 'neutron-l2gateway-agent'], 'service_api_url': 'http://localhost:9696', 'search_pattern': '.*v2.0.*' } super(Neutron, self).__init__(service_params) def build_config(self): """Build the config as a Plugins object and return.""" # Skip the http check if neutron-server is not on this box if 'neutron-server' not in self.found_processes: self.service_api_url = None self.search_pattern = None return monasca_setup.detection.ServicePlugin.build_config(self)
Remove vendor-specific paths on LBaaS agent executables
Remove vendor-specific paths on LBaaS agent executables The monasca agent uses simple string matching in the process detection plugin. This can result in false positive matches in the case where a process name appears elsehwere in the "ps" output. In particular, "neutron-lbaas-agent" is used for both process and log file names. The initial attempt at solving this used full path names for the LBaaS agents, but these paths were only valid for specific vendor distributions. This patch reverts to using only "neutron-lbaasv2-agent" for the V2 LBaaS agent, and uses "bin/neutron-lbaas-agent" for the V1 agent. While it is possible that a vendor would deliver the neutron-lbaas-agent in a directory other than "bin", they would be diverging from the layout generally assumed by the overall neutron project. Change-Id: I6654d99ea060e26b7cdd5b0bdb1a1c0a2537ba3b
Python
bsd-3-clause
sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent
91f5db6ddf6e26cec27917109689c200498dc85f
statsmodels/formula/try_formula.py
statsmodels/formula/try_formula.py
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() # try passing a formula object, using user-injected code def double_it(x): return 2*x # What is the correct entry point for this? Should users be able to inject # code into default_env or similar? I don't see a way to do this yet using # the approach I have been using, it should be an argument to Desc from charlton.builtins import builtins builtins['double_it'] = double_it formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + ' formula += 'PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
Add example for injecting user transform
ENH: Add example for injecting user transform
Python
bsd-3-clause
bert9bert/statsmodels,YihaoLu/statsmodels,cbmoore/statsmodels,hlin117/statsmodels,bavardage/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,statsmodels/statsmodels,astocko/statsmodels,DonBeo/statsmodels,bzero/statsmodels,Averroes/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,josef-pkt/statsmodels,kiyoto/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,bavardage/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,wdurhamh/statsmodels,phobson/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,jstoxrocky/statsmodels,bert9bert/statsmodels,gef756/statsmodels,astocko/statsmodels,wdurhamh/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,ChadFulton/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,rgommers/statsmodels,yl565/statsmodels,nvoron23/statsmodels,edhuckle/statsmodels,nguyentu1602/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,waynenilsen/statsmodels,wwf5067/statsmodels,wwf5067/statsmodels,edhuckle/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,gef756/statsmodels,phobson/statsmodels,wwf5067/statsmodels,huongttlan/statsmodels,waynenilsen/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,gef756/statsmodels,bashtage/statsmodels,musically-ut/statsmodels,bavardage/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bzero/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,YihaoLu/statsmodels,josef-pkt/statsmodels,saketkc/statsmodels,jseabold/statsmodels,josef-pkt/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,musically-ut/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,statsmodels/statsmodels,bsipocz/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,adammenges/statsmodels,alekz112/statsmodels,detrout/debian-statsmodels,YihaoLu/statsmodels,musically-ut/statsmodels,bert9bert/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,bavardage/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,wwf5067/statsmodels,hainm/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,hlin117/statsmodels,Averroes/statsmodels,phobson/statsmodels,bzero/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,edhuckle/statsmodels,hainm/statsmodels,astocko/statsmodels,jseabold/statsmodels,bashtage/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,astocko/statsmodels,rgommers/statsmodels,hainm/statsmodels,kiyoto/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,jstoxrocky/statsmodels,huongttlan/statsmodels,yarikoptic/pystatsmodels,bashtage/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels,adammenges/statsmodels,rgommers/statsmodels,bavardage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,bzero/statsmodels,yarikoptic/pystatsmodels,YihaoLu/statsmodels,bzero/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels
5e7c99844a0687125e34104cf2c7ee87ca69c0de
mopidy_soundcloud/__init__.py
mopidy_soundcloud/__init__.py
import os from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
import pathlib from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
Use pathlib to read ext.conf
Use pathlib to read ext.conf
Python
mit
mopidy/mopidy-soundcloud
94ec7d4816d2a243b8a2b0a0f2dc8a55a7347122
tests/saltunittest.py
tests/saltunittest.py
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: print("You need to install unittest2 to run the salt tests") sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: raise SystemExit("You need to install unittest2 to run the salt tests") else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
Make an error go to stderr and remove net 1 LOC
Make an error go to stderr and remove net 1 LOC
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
b6737b91938d527872eff1d645a205cacf94e15d
tests/test_gobject.py
tests/test_gobject.py
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') self.assertEquals(obj.__grefcount__, 1) class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') class TestReferenceCounting(unittest.TestCase): def testRegularObject(self): obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(gobject.GObject) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
Add a test to check for regular object reference count
Add a test to check for regular object reference count https://bugzilla.gnome.org/show_bug.cgi?id=639949
Python
lgpl-2.1
alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,davibe/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,choeger/pygobject-cmake,davidmalcolm/pygobject,davibe/pygobject,pexip/pygobject,Distrotech/pygobject,alexef/pygobject,sfeltman/pygobject,jdahlin/pygobject,GNOME/pygobject,GNOME/pygobject,thiblahute/pygobject,sfeltman/pygobject,thiblahute/pygobject,GNOME/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,nzjrs/pygobject,Distrotech/pygobject,nzjrs/pygobject,jdahlin/pygobject,MathieuDuponchelle/pygobject,davibe/pygobject,pexip/pygobject,alexef/pygobject,pexip/pygobject,sfeltman/pygobject,choeger/pygobject-cmake,thiblahute/pygobject,davidmalcolm/pygobject,nzjrs/pygobject,davibe/pygobject
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37
tests/test_helpers.py
tests/test_helpers.py
# -*- encoding: utf-8 -*- # # Copyright 2013 Jay Pipes # # 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 testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout')
# -*- encoding: utf-8 -*- # # Copyright 2013 Jay Pipes # # 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 testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') def test_return_function(self): fn = helpers.import_function('os.path.join') self.assertEqual(callable(fn), True)
Add test to ensure talons.helpers.import_function returns a callable
Add test to ensure talons.helpers.import_function returns a callable
Python
apache-2.0
talons/talons,jaypipes/talons
73dfb1fc4ff62705f37b1128e0684e88be416d8f
src/webmention/models.py
src/webmention/models.py
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return '<a href="https://huggingface.co/datasets/mikcnt/MyOwnCommitPack/viewer/default/{href}">{href}</a>'.format(href=self.source) source_for_admin.allow_tags = True source_for_admin.short_description = "source" def response_to_for_admin(self): return '<a href="https://huggingface.co/datasets/mikcnt/MyOwnCommitPack/viewer/default/{href}">{href}</a>'.format(href=self.response_to) response_to_for_admin.allow_tags = True response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return format_html('<a href="https://huggingface.co/datasets/mikcnt/MyOwnCommitPack/viewer/default/{href}">{href}</a>'.format(href=self.source)) source_for_admin.short_description = "source" def response_to_for_admin(self): return format_html('<a href="https://huggingface.co/datasets/mikcnt/MyOwnCommitPack/viewer/default/{href}">{href}</a>'.format(href=self.response_to)) response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
Update deprecated allow_tags to format_html
Update deprecated allow_tags to format_html
Python
mit
easy-as-python/django-webmention
e612a742caeedf5398522365c984a39c505e7872
warehouse/exceptions.py
warehouse/exceptions.py
class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
Add the standard __future__ imports
Add the standard __future__ imports
Python
bsd-2-clause
davidfischer/warehouse
34c427200c6ab50fb64fa0d6116366a8fa9186a3
netman/core/objects/bond.py
netman/core/objects/bond.py
# Copyright 2015 Internap. # # 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 netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or []
# Copyright 2015 Internap. # # 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 warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] @property def interface(self): warnings.warn('Deprecated: Use directly the members of Bond instead.', category=DeprecationWarning) return self
Support deprecated use of the interface property of Bond.
Support deprecated use of the interface property of Bond.
Python
apache-2.0
idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman
ab06e871a6c820845da2d4d60bb6b1874350cf16
circuits/web/__init__.py
circuits/web/__init__.py
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from loggers import Logger from core import Controller from sessions import Sessions from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from utils import url from loggers import Logger from sessions import Sessions from core import expose, Controller from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
Add url and expose to this namesapce
circuits.web: Add url and expose to this namesapce
Python
mit
eriol/circuits,eriol/circuits,nizox/circuits,treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits
04c92e1fe7efa38f7d99d501286d3b7e627e73ca
scripts/slave/chromium/dart_buildbot_run.py
scripts/slave/chromium/dart_buildbot_run.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') # Temporary until 1.6 ships on stable. if builder_name.endswith('-be') or builder_name.endswith("-dev"): script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' chromium_utils.RunCommand([sys.executable, script]) # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') # Temporary until 1.6 ships on stable. if builder_name.endswith('-be') or builder_name.endswith("-dev"): script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' result = chromium_utils.RunCommand([sys.executable, script]) if result: print 'Running annotated steps % failed' % script return 1 # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
Use exitcode of running the annotated steps script
Use exitcode of running the annotated steps script If there is an error in the annotated steps we will still have a green bot!!!! Example: http://chromegw.corp.google.com/i/client.dart/builders/dartium-lucid64-full-be/builds/3566/steps/annotated_steps/logs/stdio TBR=whesse Review URL: https://codereview.chromium.org/450923002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@288225 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
fa7aecae90026037c9f5ce2ffef37184ee83f679
nova/objects/__init__.py
nova/objects/__init__.py
# Copyright 2013 IBM Corp. # # 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.
# Copyright 2013 IBM Corp. # # 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. def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.instance')
Use Instance Objects for Start/Stop
Use Instance Objects for Start/Stop This patch makes the start and stop operations use the Instance object instead of passing SQLA-derived dicts over RPC. Until something more sophisticated is needed (and developed), it also adds a nova.object.register_all() function which just triggers imports of all the object models so that they are registered. When adding a new object type, that register function should be updated appropriately. Related to bp/unified-object-model Change-Id: I3c8d9cba07d34097a279502062906de802d19d1f
Python
apache-2.0
citrix-openstack-build/oslo.versionedobjects,openstack/oslo.versionedobjects
186a2c3f235264c3c71396efcbb8a33924758db9
scrape.py
scrape.py
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run('email', 'password')
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run(usertoken,bot=False)
Update to use token instead of email+pass
Update to use token instead of email+pass
Python
mit
suclearnub/discordgrapher
3ddad0538430499182c583a0a7f877884038c0a5
Lib/test/test_symtable.py
Lib/test/test_symtable.py
from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time
from test import test_support import symtable import unittest ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time class SymtableTest(unittest.TestCase): def test_invalid_args(self): self.assertRaises(TypeError, symtable.symtable, "42") self.assertRaises(ValueError, symtable.symtable, "42", "?", "") def test_eval(self): symbols = symtable.symtable("42", "?", "eval") def test_single(self): symbols = symtable.symtable("42", "?", "single") def test_exec(self): symbols = symtable.symtable("def f(x): return x", "?", "exec") def test_main(): test_support.run_unittest(SymtableTest) if __name__ == '__main__': test_main()
Use unittest and make sure a few other cases don't crash
Use unittest and make sure a few other cases don't crash
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f
OMDB_api_scrape.py
OMDB_api_scrape.py
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # JSON and saves a copy for later import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile)
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # xml and saves a copy for later import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
Convert OMDB scrapper to grab xml
Convert OMDB scrapper to grab xml
Python
mit
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
8ac20f5bec2d94e71b92e48568d18fd74be4e5d4
fabfile.py
fabfile.py
from fabric.api import task, local @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx")
from fabric.api import task, local, execute @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) execute(syncMezzo) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") @task def syncMezzo(): """ Copy current module version to mezzo project """ local("rm -rf /opt/mezzo/pgup") local("mkdir /opt/mezzo/pgup") local("cp -R etc pgup /opt/mezzo/pgup") local("cp LICENSE MANIFEST.in README.md setup.py /opt/mezzo/pgup")
Add fab task for syncing pgup with mezzo
Add fab task for syncing pgup with mezzo
Python
mit
stepan-perlov/pgup
c3c26c15895a192fba22482306182950c0ccd57c
python/simple-linked-list/simple_linked_list.py
python/simple-linked-list/simple_linked_list.py
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self.size = 0 for value in values: self.push(value) def __len__(self): return self.size def head(self): pass def push(self, value): node = Node(value) if self.head is None: self.head = node self.size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): pass
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self._size = 0 self._head = None for value in values: self.push(value) def __len__(self): return self._size def head(self): if self._head is None: raise EmptyListException("Head is empty") def push(self, value): node = Node(value) if self._head is None: self._head = node self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): def __init__(self, message): self.message = message
Mark instance variables private with leading _
Mark instance variables private with leading _
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
fa609681c2732e655cde9075182af918983ccc1f
photutils/utils/_misc.py
photutils/utils/_misc.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides tools to return the installed astropy and photutils versions. """ from datetime import datetime, timezone def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides tools to return the installed astropy and photutils versions. """ from datetime import datetime, timezone import sys def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {'Python': sys.version.split()[0]} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage', 'sklearn', 'matplotlib', 'gwcs', 'bottleneck') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
Add all optional dependencies to version info dict
Add all optional dependencies to version info dict
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
a346eb2b19f3a0b72dc6565e9d0c4fabf3c5784a
migrations/versions/0014_add_template_version.py
migrations/versions/0014_add_template_version.py
"""empty message Revision ID: 0014_add_template_version Revises: 0013_add_loadtest_client Create Date: 2016-05-11 16:00:51.478012 """ # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
"""empty message Revision ID: 0014_add_template_version Revises: 0013_add_loadtest_client Create Date: 2016-05-11 16:00:51.478012 """ # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) # fix template_history where created_by_id is not set. query = "update templates_history set created_by_id = " \ " (select created_by_id from templates " \ " where templates.id = templates_history.id " \ " and templates.version = templates_history.version) " \ "where templates_history.created_by_id is null" op.execute(query) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
Add a update query to fix templates_history where the created_by_id is missing.
Add a update query to fix templates_history where the created_by_id is missing.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
df000e724ce1f307a478fcf4790404183df13610
_setup_database.py
_setup_database.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) # migrating players from json file to database migrate_players(simulation=True)
Include player data migration in setup
Include player data migration in setup
Python
mit
leaffan/pynhldb
c0d9a94899af84e8a075cfc7cfb054a934470e3a
static_precompiler/tests/test_templatetags.py
static_precompiler/tests/test_templatetags.py
import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.loader.get_template_from_string( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
Fix tests for Django 1.8
Fix tests for Django 1.8
Python
mit
liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler
eaa4de2ecbcf29c9e56ebf2fa69099055e469fbc
tests/test_conversion.py
tests/test_conversion.py
from asciisciit import conversions as conv import numpy as np def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
import itertools from asciisciit import conversions as conv import numpy as np import pytest @pytest.mark.parametrize("invert,equalize,lut,lookup_func", itertools.product((True, False), (True, False), ("simple", "binary"), (None, conv.apply_lut_pil))) def test_pil_to_ascii(invert, equalize, lut, lookup_func): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 img = conv.numpy_to_pil(img) text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func) assert(len(text) == expected_len) @pytest.mark.parametrize("invert,equalize,lut", itertools.product((True, False), (True, False), ("simple", "binary"))) def test_numpy_to_ascii(invert, equalize, lut): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut) assert(len(text) == expected_len) def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
Add tests to minimally exercise basic conversion functionality
Add tests to minimally exercise basic conversion functionality
Python
mit
derricw/asciisciit
a0420b066e0a5064ebe0944a16348debf107a9a4
speech.py
speech.py
"""Export long monologues for Nao. Functions: introduction -- Make Nao introduce itself. """ import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
"""Export long monologues for Nao. Functions: introduction -- Make Nao introduce itself. """ import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("I'm Leyva and I will teach you how to program in a programming\ language called python", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
Make Nao say its name and the programming language
Make Nao say its name and the programming language
Python
mit
AliGhahraei/nao-classroom
40122e169e6a887caa6371a0ff3029c35ce265d5
third_party/node/node.py
third_party/node/node.py
#!/usr/bin/env vpython # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
#!/usr/bin/env vpython # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output, universal_newlines=True) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
Fix line ending printing on Python 3
Fix line ending printing on Python 3 To reflect the changes in https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py R=993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org Bug: none Change-Id: I25ba29042f537bfef57fba93115be2c194649864 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2914883 Commit-Queue: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Commit-Queue: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org> Auto-Submit: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Reviewed-by: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org>
Python
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
91b0bcad27f12c29681235079960ee272275e0bd
src/main/python/dlfa/solvers/__init__.py
src/main/python/dlfa/solvers/__init__.py
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, }
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, 'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver, }
Add MCMemoryNetwork as a usable solver
Add MCMemoryNetwork as a usable solver
Python
apache-2.0
allenai/deep_qa,matt-gardner/deep_qa,DeNeutoy/deep_qa,allenai/deep_qa,DeNeutoy/deep_qa,matt-gardner/deep_qa
0fd6a6e3281bc49addd1131ae30b1985b9da30f9
tests/benchmark/plugins/clear_buffer_cache.py
tests/benchmark/plugins/clear_buffer_cache.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): cmd = "sysctl -w vm.drop_caches=3 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): # Drop the page cache (drop_caches=1). We'll leave the inodes and dentries # since that is not what we are testing and it causes excessive performance # variability. cmd = "sysctl -w vm.drop_caches=1 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
Update clear buffer cache plugin to only flush page cache.
Update clear buffer cache plugin to only flush page cache. More detail: http://linux-mm.org/Drop_Caches Change-Id: I7fa675ccdc81f375d88e9cfab330fca3bc983ec8 Reviewed-on: http://gerrit.ent.cloudera.com:8080/1157 Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com> Reviewed-by: Lenni Kuff <724b7df200764f5dc1b723c05ee6c6adabd11bb1@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Python
apache-2.0
brightchen/Impala,rampage644/impala-cut,brightchen/Impala,XiaominZhang/Impala,caseyching/Impala,cgvarela/Impala,ImpalaToGo/ImpalaToGo,caseyching/Impala,tempbottle/Impala,cchanning/Impala,scalingdata/Impala,tempbottle/Impala,AtScaleInc/Impala,scalingdata/Impala,gistic/PublicSpatialImpala,rampage644/impala-cut,bowlofstew/Impala,rampage644/impala-cut,lirui-intel/Impala,cchanning/Impala,rdblue/Impala,henryr/Impala,XiaominZhang/Impala,grundprinzip/Impala,kapilrastogi/Impala,scalingdata/Impala,tempbottle/Impala,cloudera/recordservice,ImpalaToGo/ImpalaToGo,mapr/impala,henryr/Impala,lirui-intel/Impala,cgvarela/Impala,kapilrastogi/Impala,lnliuxing/Impala,gistic/PublicSpatialImpala,cchanning/Impala,bowlofstew/Impala,tempbottle/Impala,brightchen/Impala,rdblue/Impala,lirui-intel/Impala,caseyching/Impala,mapr/impala,tempbottle/Impala,rdblue/Impala,brightchen/Impala,cloudera/recordservice,cchanning/Impala,rdblue/Impala,cgvarela/Impala,lnliuxing/Impala,AtScaleInc/Impala,mapr/impala,mapr/impala,bratatidas9/Impala-1,XiaominZhang/Impala,ImpalaToGo/ImpalaToGo,brightchen/Impala,tempbottle/Impala,ImpalaToGo/ImpalaToGo,andybab/Impala,gerashegalov/Impala,brightchen/Impala,ibmsoe/ImpalaPPC,cgvarela/Impala,cchanning/Impala,kapilrastogi/Impala,gerashegalov/Impala,scalingdata/Impala,XiaominZhang/Impala,bratatidas9/Impala-1,gerashegalov/Impala,bowlofstew/Impala,caseyching/Impala,placrosse/ImpalaToGo,lirui-intel/Impala,grundprinzip/Impala,cloudera/recordservice,bratatidas9/Impala-1,theyaa/Impala,lirui-intel/Impala,bratatidas9/Impala-1,henryr/Impala,lnliuxing/Impala,placrosse/ImpalaToGo,henryr/Impala,grundprinzip/Impala,kapilrastogi/Impala,rampage644/impala-cut,kapilrastogi/Impala,placrosse/ImpalaToGo,grundprinzip/Impala,ibmsoe/ImpalaPPC,caseyching/Impala,bowlofstew/Impala,placrosse/ImpalaToGo,gerashegalov/Impala,cchanning/Impala,XiaominZhang/Impala,bratatidas9/Impala-1,kapilrastogi/Impala,kapilrastogi/Impala,lirui-intel/Impala,cloudera/recordservice,lnliuxing/Impala,caseyching/Impala,rdblue/Impala,grundprinzip/Impala,cloudera/recordservice,theyaa/Impala,rampage644/impala-cut,bratatidas9/Impala-1,ImpalaToGo/ImpalaToGo,gistic/PublicSpatialImpala,andybab/Impala,henryr/Impala,theyaa/Impala,theyaa/Impala,grundprinzip/Impala,bowlofstew/Impala,lirui-intel/Impala,lnliuxing/Impala,tempbottle/Impala,cgvarela/Impala,ibmsoe/ImpalaPPC,andybab/Impala,cloudera/recordservice,AtScaleInc/Impala,AtScaleInc/Impala,scalingdata/Impala,ibmsoe/ImpalaPPC,gerashegalov/Impala,ImpalaToGo/ImpalaToGo,theyaa/Impala,rampage644/impala-cut,ibmsoe/ImpalaPPC,scalingdata/Impala,gistic/PublicSpatialImpala,gerashegalov/Impala,rdblue/Impala,ibmsoe/ImpalaPPC,lnliuxing/Impala,mapr/impala,bowlofstew/Impala,AtScaleInc/Impala,andybab/Impala,cgvarela/Impala,gistic/PublicSpatialImpala,henryr/Impala,brightchen/Impala,placrosse/ImpalaToGo,XiaominZhang/Impala,andybab/Impala,cloudera/recordservice,rdblue/Impala,lnliuxing/Impala,bratatidas9/Impala-1,XiaominZhang/Impala,AtScaleInc/Impala,placrosse/ImpalaToGo,bowlofstew/Impala,theyaa/Impala,theyaa/Impala,cchanning/Impala,gerashegalov/Impala,caseyching/Impala,cgvarela/Impala,gistic/PublicSpatialImpala,ibmsoe/ImpalaPPC,andybab/Impala
b94458b5dc184798580ade159ace700a46ab5877
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert isinstance(notch, str) assert isinstance(wiring, str) assert len(wiring) == len(string.ascii_uppercase) self.notch = notch self.wiring = wiring class Enigma: def __init__(self): pass def cipher(self, message): pass
Initialize rotors with notches and wiring data
Initialize rotors with notches and wiring data
Python
mit
ranisalt/enigma
e650c319b109ca554c2d66f2d9446ef62440cc0f
anna/model/utils.py
anna/model/utils.py
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell = tf.nn.rnn_cell.DropoutWrapper( cell=cell, input_keep_prob=keep_prop, ) if residual: cell = tf.nn.rnn_cell.ResidualWrapper(cell) return cell
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.estimator.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell = tf.nn.rnn_cell.DropoutWrapper( cell=cell, input_keep_prob=keep_prop, ) if residual: cell = tf.nn.rnn_cell.ResidualWrapper(cell) return cell
Fix bug in RNN dropout
Fix bug in RNN dropout
Python
mit
jpbottaro/anna
7add1c5a43c6bef29613167ca430ad7ff0e26670
src/ocspdash/web/blueprints/ui.py
src/ocspdash/web/blueprints/ui.py
# -*- coding: utf-8 -*- import base64 import json from nacl.encoding import URLSafeBase64Encoder import nacl.exceptions import nacl.signing from flask import Blueprint, abort, current_app, render_template, request from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): """Show the submit view.""" location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: return abort(403, f'Not activated: {location}') key = location.pubkey try: verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError as e: return abort(403, f'Bad Signature: {e}') decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) current_app.manager.insert_payload(decoded_payload) return '', 204
# -*- coding: utf-8 -*- # import nacl.exceptions # import nacl.signing from flask import Blueprint, current_app, render_template # from nacl.encoding import URLSafeBase64Encoder # from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) # @ui.route('/submit', methods=['POST']) # def submit(): # """Show the submit view.""" # location_id = int(request.headers['authorization']) # # location = current_app.manager.get_location_by_id(location_id) # # if not location.activated: # return abort(403, f'Not activated: {location}') # # key = location.pubkey # # try: # verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) # payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) # # except nacl.exceptions.BadSignatureError as e: # return abort(403, f'Bad Signature: {e}') # # decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) # current_app.manager.insert_payload(decoded_payload) # # return '', 204
Remove /submit endpoint from UI blueprint for now
Remove /submit endpoint from UI blueprint for now
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
d4356b7aa879a345939c1885742efc3deceeb08f
lib/aquilon/__init__.py
lib/aquilon/__init__.py
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2013 Contributor # # 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.
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This is a namespace package try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Make aquilon a namespace package
Make aquilon a namespace package In the future we may want to import the protocols as "from aquilon.protocols import blah", and that needs both the broker and the protocols to be marked as namespace packages. Change-Id: Ib3b712e727b0dd176c231a396bec4e7168a0039e Reviewed-by: Dave Reeve <6a84ee3ae0690d4584b99406fb3076392171f50e@morganstanley.com>
Python
apache-2.0
guillaume-philippon/aquilon,quattor/aquilon,quattor/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,quattor/aquilon