diff --git a/pool/shard001/Python/0012539_ntp.py b/pool/shard001/Python/0012539_ntp.py new file mode 100644 index 0000000000000000000000000000000000000000..639b292ae3ed4c620637401c75ce5079b1d15635 --- /dev/null +++ b/pool/shard001/Python/0012539_ntp.py @@ -0,0 +1,51 @@ +### This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. + +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. + +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin + +class Ntp(Plugin): + """NTP related information + """ + + plugin_name = "ntp" + + packages = ('ntp',) + + def setup(self): + self.add_copy_specs([ + "/etc/ntp.conf", + "/etc/ntp/step-tickers", + "/etc/ntp/ntpservers" + ]) + self.add_cmd_output("ntptime") + + +class RedHatNtp(Ntp, RedHatPlugin): + """NTP related information for RedHat based distributions + """ + + def setup(self): + super(RedHatNtp, self).setup() + self.add_copy_spec("/etc/sysconfig/ntpd") + self.add_cmd_output("ntpstat") + + +class DebianNtp(Ntp, DebianPlugin, UbuntuPlugin): + """NTP related information for Debian based distributions + """ + + def setup(self): + super(DebianNtp, self).setup() + self.add_copy_spec('/etc/default/ntp') + diff --git a/pool/shard001/Python/0012540_filters.py b/pool/shard001/Python/0012540_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..03e547d02a39da73390b3c4d62eb6d89ffff2988 --- /dev/null +++ b/pool/shard001/Python/0012540_filters.py @@ -0,0 +1,89 @@ +# Copyright 2012 - 2013 Zarafa B.V. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License, version 3, +# as published by the Free Software Foundation with the following additional +# term according to sec. 7: +# +# According to sec. 7 of the GNU Affero General Public License, version +# 3, the terms of the AGPL are supplemented with the following terms: +# +# "Zarafa" is a registered trademark of Zarafa B.V. The licensing of +# the Program under the AGPL does not imply a trademark license. +# Therefore any rights, title and interest in our trademarks remain +# entirely with us. +# +# However, if you propagate an unmodified version of the Program you are +# allowed to use the term "Zarafa" to indicate that you distribute the +# Program. Furthermore you may use our trademarks where it is necessary +# to indicate the intended purpose of a product or service provided you +# use it in accordance with honest practices in industrial or commercial +# matters. If you want to propagate modified versions of the Program +# under the name "Zarafa" or "Zarafa Server", you may only do so if you +# have a written permission by Zarafa B.V. (to acquire a permission +# please contact Zarafa at trademark@zarafa.com). +# +# The interactive user interface of the software displays an attribution +# notice containing the term "Zarafa" and/or the logo of Zarafa. +# Interactive user interfaces of unmodified and modified versions must +# display Appropriate Legal Notices according to sec. 5 of the GNU +# Affero General Public License, version 3, when you propagate +# unmodified or modified versions of the Program. In accordance with +# sec. 7 b) of the GNU Affero General Public License, version 3, these +# Appropriate Legal Notices must retain the logo of Zarafa or display +# the words "Initial Development by Zarafa" if the display of the logo +# is not reasonably feasible for technical reasons. The use of the logo +# of Zarafa in Legal Notices is allowed for unmodified and modified +# versions of the software. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + + +from datetime import datetime +import collections + +from pumpkin.filters import _make_op # NOQA +from pumpkin.filters import contains # NOQA +from pumpkin.filters import endswith # NOQA +from pumpkin.filters import eq # NOQA +from pumpkin.filters import opand # NOQA +from pumpkin.filters import opnot # NOQA +from pumpkin.filters import opor # NOQA +from pumpkin.filters import present # NOQA +from pumpkin.filters import startswith # NOQA +from pumpkin.filters import unicode2str + +from extfields import GeneralizedTimeField + + +SearchParams = collections.namedtuple('SearchParams', 'basedn filter') + +_time_field = None +def get_time_field(): + global _time_field + if not _time_field: + _time_field = GeneralizedTimeField(None) + return _time_field + + +@unicode2str +def gte(attr, value): + if isinstance(value, datetime): + time_field = get_time_field() + value = time_field.encode2str(value)[0] + + return '(%s>=%s)' % (attr, value) + +@unicode2str +def lte(attr, value): + if isinstance(value, datetime): + time_field = get_time_field() + value = time_field.encode2str(value)[0] + + return '(%s<=%s)' % (attr, value) diff --git a/pool/shard001/Python/0012541_threading.py b/pool/shard001/Python/0012541_threading.py new file mode 100644 index 0000000000000000000000000000000000000000..863b60119ff146c4c27445b6d3a5a787cd45a460 --- /dev/null +++ b/pool/shard001/Python/0012541_threading.py @@ -0,0 +1,22 @@ +from filament import patcher as _fil_patcher +from filament import _util as _fil_util +import _filament.timer as _fil_timer +from _filament.locking import * + +__filament__ = {'patch':'threading'} + +threading = _fil_patcher.get_original('threading') + +class Timer(_fil_timer.Timer): + __doc__ = threading.Timer.__doc__ + + def __init__(self, interval, function, args=None, kwargs=None): + if args is None: + args = () + if kwargs: + super(Timer, self).__init__(interval, function, *args, **kwargs) + else: + super(Timer, self).__init__(interval, function, *args) + + +_fil_util.copy_globals(threading, globals()) diff --git a/pool/shard001/Python/0012547_product_catalog_rep_qty.py b/pool/shard001/Python/0012547_product_catalog_rep_qty.py new file mode 100644 index 0000000000000000000000000000000000000000..b500815a514d87b034345b200784b0cbadbeb570 --- /dev/null +++ b/pool/shard001/Python/0012547_product_catalog_rep_qty.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Copyright (C) 2013 Bortolatto Ivan. ( ivan.bortolatto(at)didotech.com ) +# Copyright (C) 2013 Didotech Inc. () +# All Rights Reserved +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import time +from report import report_sxw +import pooler +import pprint + +from osv import osv, fields +import decimal_precision as dp + +pp = pprint.PrettyPrinter(indent=4) + +#try: +# from cStringIO import StringIO +# _hush_pyflakes = [ StringIO ] +#except ImportError: +# from StringIO import StringIO + + +class product_product(osv.osv): + _name = 'product.product' + _inherit = 'product.product' + + def _product_price2(self, cr, uid, ids, name, arg, context=None): + res = {} + if context is None: + context = {} + quantity = context.get('quantity') or 1.0 + pricelist = context.get('pricelist2', False) + if pricelist: + for id in ids: + try: + price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], id, quantity, context=context)[pricelist] + except: + price = 0.0 + res[id] = price + for id in ids: + res.setdefault(id, 0.0) + return res + + _columns = { + 'price2': fields.function(_product_price2, method=True, type='float', string='Pricelist', digits_compute=dp.get_precision('Sale Price')), + } + +product_product() + + +class product_catalog_rep_qty(report_sxw.rml_parse): + + def __init__(self, cr, uid, name, context): + super(product_catalog_rep_qty, self).__init__(cr, uid, name, context=context) + self.month = False + self.year = False + + self.localcontext.update({ + 'time': time, + 'get_categories': self.get_categories, + 'get_product': self.get_products, + 'get_pricelist_name': self.get_pricelist_name, + }) + + def setCat(self, cats): + lst = [] + for cat in self.pool['product.category'].browse(self.cr, self.uid, cats): + if cat.id not in lst: + lst.append(cat.id) + for child_id in cat.child_id: + child_ids = self.setCat([child_id.id]) + lst.extend(child_ids) + return lst + + def get_pricelist_name(self, form, pricelist_id): + pricelist_data = self.pool['product.pricelist'].browse(self.cr, self.uid, form[pricelist_id][0]) + return '%s (%s)' % (pricelist_data.name, pricelist_data.currency_id.name) + + def get_products(self, c): + prod_tmpIDs = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', c), ]) + prod_qty_ids = self.pool.get('product.product').search(self.cr, self.uid, [ + ('product_tmpl_id', 'in', prod_tmpIDs), + ('sale_ok', '=', True), + ], order='name') + prod_ids = [] + prod_qty_dicts = self.pool.get('product.product').read(self.cr, self.uid, prod_qty_ids, ['virtual_available']) + for prod_qty_dict in prod_qty_dicts: + if prod_qty_dict['virtual_available'] > 0: + prod_ids = prod_ids + [prod_qty_dict['id']] + price_context = {} + if self.pricelist_id not in ('', False, [], None): + price_context['pricelist'] = self.pricelist_id[0] + if self.pricelist_id2 not in ('', False, [], None): + price_context['pricelist2'] = self.pricelist_id2[0] + prods = self.pool.get('product.product').browse(self.cr, self.uid, prod_ids, context=price_context) + return prods + + def get_categories(self, form): + category = form.get('category_id', False) + self.pricelist_id = form.get('pricelist_id', False) + self.pricelist_id2 = form.get('pricelist_id2', False) + lst = [] + if not category: + return lst + lst = self.setCat([category]) + cat_ids = self.pool.get('product.category').search(self.cr, self.uid, [('id', 'in', lst)]) + + tmpCat_ids = [] + for cat in cat_ids: + prod_ids = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', cat)]) + if len(prod_ids): + tmpCat_ids.append(cat) + cats = self.pool.get('product.category').browse(self.cr, self.uid, tmpCat_ids) + return_value = [] + for catg in cats: + prod = self.get_products(catg.id) + if prod not in ('', False, [], None): + return_value = return_value + [catg] + return return_value + + def _getProducts(self, category, lang): + prod_tmpIDs = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', category)]) + prod_ids = self.pool.get('product.product').search(self.cr, self.uid, [('product_tmpl_id', 'in', prod_tmpIDs)]) + prods = self.pool.get('product.product').browse(self.cr, self.uid, prod_ids, context={'lang': lang}) + return prods + + def get_pricelist(self, a): + result = [] + pooler.get_pool(self.cr.dbname).get('product.pricelist') + self.pricelist = a.get('pricelist_id', False) + return result + +report_sxw.report_sxw('report.product.catalog.qty', 'product.product', 'addons/product_catalog_available/report/product_catalog_rep_qty.rml', parser=product_catalog_rep_qty, header=0) +report_sxw.report_sxw('report.product.catalog.qty2', 'product.product', 'addons/product_catalog_available/report/product_catalog_rep_qty2.rml', parser=product_catalog_rep_qty, header=0) + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard001/Python/0012548_popupmenu.py b/pool/shard001/Python/0012548_popupmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..8772c6c8b6690a8cfb9e1f7e9e3f47eb7ae12d1d --- /dev/null +++ b/pool/shard001/Python/0012548_popupmenu.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- + +# Copyright (C) 2011 Chris Dekter +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import time, logging +from gi.repository import Gtk, Gdk + +from autokey.configmanager import * +from autokey.model import Folder # TODO remove later + +_logger = logging.getLogger("phrase-menu") + +class PopupMenu(Gtk.Menu): + """ + A popup menu that allows the user to select a phrase. + """ + + def __init__(self, service, folders=[], items=[], onDesktop=True, title=None): + Gtk.Menu.__init__(self) + #self.set_take_focus(ConfigManager.SETTINGS[MENU_TAKES_FOCUS]) + self.__i = 1 + self.service = service + + if ConfigManager.SETTINGS[SORT_BY_USAGE_COUNT]: + _logger.debug("Sorting phrase menu by usage count") + folders.sort(key=lambda obj: obj.usageCount, reverse=True) + items.sort(key=lambda obj: obj.usageCount, reverse=True) + else: + _logger.debug("Sorting phrase menu by item name/title") + folders.sort(key=lambda obj: str(obj)) + items.sort(key=lambda obj: str(obj)) + + if ConfigManager.SETTINGS[TRIGGER_BY_INITIAL]: + _logger.debug("Triggering menu item by first initial") + self.triggerInitial = 1 + else: + _logger.debug("Triggering menu item by position in list") + self.triggerInitial = 0 + + if len(folders) == 1 and len(items) == 0 and onDesktop: + # Only one folder - create menu with just its folders and items + for folder in folders[0].folders: + menuItem = Gtk.MenuItem(label=self.__getMnemonic(folder.title, onDesktop)) + menuItem.set_submenu(PopupMenu(service, folder.folders, folder.items, onDesktop)) + menuItem.set_use_underline(True) + self.append(menuItem) + + if len(folders[0].folders) > 0: + self.append(Gtk.SeparatorMenuItem()) + + self.__addItemsToSelf(folders[0].items, service, onDesktop) + + else: + # Create phrase folder section + for folder in folders: + menuItem = Gtk.MenuItem(label=self.__getMnemonic(folder.title, onDesktop)) + menuItem.set_submenu(PopupMenu(service, folder.folders, folder.items, False)) + menuItem.set_use_underline(True) + self.append(menuItem) + + if len(folders) > 0: + self.append(Gtk.SeparatorMenuItem()) + + self.__addItemsToSelf(items, service, onDesktop) + + self.show_all() + + def __getMnemonic(self, desc, onDesktop): + if 1 < 10 and '_' not in desc and onDesktop: + if self.triggerInitial: + ret = "%s" % (desc) + else: + ret = "_%d - %s" % (self.__i, desc) + self.__i += 1 + return ret + else: + return desc + + def show_on_desktop(self): + Gdk.threads_enter() + time.sleep(0.2) + self.popup(None, None, None, None, 1, 0) + Gdk.threads_leave() + + def remove_from_desktop(self): + Gdk.threads_enter() + self.popdown() + Gdk.threads_leave() + + def __addItemsToSelf(self, items, service, onDesktop): + # Create phrase section + if ConfigManager.SETTINGS[SORT_BY_USAGE_COUNT]: + items.sort(key=lambda obj: obj.usageCount, reverse=True) + else: + items.sort(key=lambda obj: str(obj)) + + i = 1 + for item in items: + #if onDesktop: + # menuItem = Gtk.MenuItem(item.get_description(service.lastStackState), False) + #else: + menuItem = Gtk.MenuItem(label=self.__getMnemonic(item.description, onDesktop)) + menuItem.connect("activate", self.__itemSelected, item) + menuItem.set_use_underline(True) + self.append(menuItem) + + def __itemSelected(self, widget, item): + self.service.item_selected(item) + +# Testing stuff - remove later ---- + +class MockPhrase: + + def __init__(self, description): + self.description = description + + +class MockExpansionService: + + def phrase_selected(self, event, phrase): + print phrase.description + + +if __name__ == "__main__": + Gdk.threads_init() + + myFolder = PhraseFolder("Some phrases") + myFolder.add_phrase(MockPhrase("phrase 1")) + myFolder.add_phrase(MockPhrase("phrase 2")) + myFolder.add_phrase(MockPhrase("phrase 3")) + + myPhrases = [] + myPhrases.append(MockPhrase("phrase 1")) + myPhrases.append(MockPhrase("phrase 2")) + myPhrases.append(MockPhrase("phrase 3")) + + menu = PhraseMenu(MockExpansionService(), [myFolder], myPhrases) + menu.show_on_desktop() + + Gtk.main() diff --git a/pool/shard001/Python/0012551_source_mapper.py b/pool/shard001/Python/0012551_source_mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4342be3b5f89483d8f0926cbde2cd5a4dc3c5f --- /dev/null +++ b/pool/shard001/Python/0012551_source_mapper.py @@ -0,0 +1,171 @@ +# coding=utf-8 +# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +import os +from collections import defaultdict + +from pants.base.build_environment import get_buildroot +from pants.source.payload_fields import DeferredSourcesField + + +class SourceMapper(object): + """A utility for making a mapping of source files to targets that own them.""" + + def target_addresses_for_source(self, source): + raise NotImplementedError + + +class SpecSourceMapper(SourceMapper): + """ + Uses sources specs to identify an owner target of a source. + + Note: it doesn't check if a file exists. + """ + + def __init__(self, address_mapper, build_graph, stop_after_match=False): + """ + :param AddressMapper address_mapper: An address mapper that can be used to populate the + `build_graph` with targets source mappings are needed for. + :param BuildGraph build_graph: The build graph to map sources from. + :param bool stop_after_match: If `True` a search will not traverse into parent directories once + an owner is identified. + """ + self._stop_after_match = stop_after_match + self._build_graph = build_graph + self._address_mapper = address_mapper + + def target_addresses_for_source(self, source): + result = [] + + root = get_buildroot() + path = source + + # a top-level source has empty dirname, so do/while instead of straight while loop. + while path: + path = os.path.dirname(path) + candidate = self._address_mapper.get_build_file(relpath=path, must_exist=False) + if candidate.file_exists(): + result.extend(list(self._find_targets_for_source(source, candidate.family()))) + if self._stop_after_match and len(result) > 0: + break + + return result + + def _find_targets_for_source(self, source, build_files): + for build_file in build_files: + for address in self._address_mapper.addresses_in_spec_path(build_file.spec_path): + self._build_graph.inject_address_closure(address) + target = self._build_graph.get_target(address) + sources = target.payload.get_field('sources') + if sources and not isinstance(sources, DeferredSourcesField) and sources.matches(source): + yield address + if address.build_file.relpath == source: + yield address + if target.has_resources: + for resource in target.resources: + """ + :type resource: pants.build_graph.resources.Resources + """ + if resource.payload.sources.matches(source): + yield address + + +class LazySourceMapper(SourceMapper): + """ + This attempts to avoid loading more than needed by lazily searching for and loading BUILD files + adjacent to or in parent directories (up to the buildroot) of a source to construct a (partial) + mapping of sources to owning targets. + + If in stop-after-match mode, a search will not traverse into parent directories once an owner + is identified. THIS MAY FAIL TO FIND ADDITIONAL OWNERS in parent directories, or only find them + when other sources are also mapped first, which cause those owners to be loaded. Some repositories + may be able to use this to avoid expensive walks, but others may need to prefer correctness. + + A LazySourceMapper reuses computed mappings and only searches a given path once as + populating the BuildGraph is expensive, so in general there should only be one instance of it. + """ + + def __init__(self, address_mapper, build_graph, stop_after_match=False): + """Initialize LazySourceMapper. + + :param AddressMapper address_mapper: An address mapper that can be used to populate the + `build_graph` with targets source mappings are needed for. + :param BuildGraph build_graph: The build graph to map sources from. + :param bool stop_after_match: If `True` a search will not traverse into parent directories once + an owner is identified. + """ + self._stop_after_match = stop_after_match + self._build_graph = build_graph + self._address_mapper = address_mapper + self._source_to_address = defaultdict(set) + self._mapped_paths = set() + self._searched_sources = set() + + def _find_owners(self, source): + """Searches for BUILD files adjacent or above a source in the file hierarchy. + - Walks up the directory tree until it reaches a previously searched path. + - Stops after looking in the buildroot. + + If self._stop_after_match is set, stops searching once a source is mapped, even if the parent + has yet to be searched. See class docstring for discussion. + + :param str source: The source at which to start the search. + """ + # Bail instantly if a source has already been searched + if source in self._searched_sources: + return + self._searched_sources.add(source) + + root = get_buildroot() + path = os.path.dirname(source) + + # a top-level source has empty dirname, so do/while instead of straight while loop. + walking = True + while walking: + # It is possible + if path not in self._mapped_paths: + candidate = self._address_mapper.get_build_file(relpath=path, must_exist=False) + if candidate.file_exists(): + self._map_sources_from_family(candidate.family()) + self._mapped_paths.add(path) + elif not self._stop_after_match: + # If not in stop-after-match mode, once a path is seen visited, all parents can be assumed. + return + + # See class docstring + if self._stop_after_match and source in self._source_to_address: + return + + walking = bool(path) + path = os.path.dirname(path) + + def _map_sources_from_family(self, build_files): + """Populate mapping of source to owning addresses with targets from given BUILD files. + + :param iterable build_files: a family of BUILD files from which to map sources. + """ + for build_file in build_files: + for address in self._address_mapper.addresses_in_spec_path(build_file.spec_path): + self._build_graph.inject_address_closure(address) + target = self._build_graph.get_target(address) + if target.has_resources: + for resource in target.resources: + for item in resource.sources_relative_to_buildroot(): + self._source_to_address[item].add(target.address) + + for target_source in target.sources_relative_to_buildroot(): + self._source_to_address[target_source].add(target.address) + if not target.is_synthetic: + self._source_to_address[target.address.build_file.relpath].add(target.address) + + def target_addresses_for_source(self, source): + """Attempt to find targets which own a source by searching up directory structure to buildroot. + + :param string source: The source to look up. + """ + self._find_owners(source) + return self._source_to_address[source] diff --git a/pool/shard001/Python/0012552_managers.py b/pool/shard001/Python/0012552_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2daeb90dac88d0dba541915a117a405a8b7c90 --- /dev/null +++ b/pool/shard001/Python/0012552_managers.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- + +# This module contains all the Proxy manager classes for use with the MIT +# Core Concept Catalog (MC3) Handcar service. + +from dlkit.abstract_osid.proxy import managers as abc_proxy_managers +from ..osid import managers as osid_managers +from .. import profile +from ..primitives import Id, DisplayText, Type +from ..type.objects import TypeList +from ..osid.osid_errors import NullArgument, OperationFailed, Unimplemented + + +class ProxyProfile(abc_proxy_managers.ProxyProfile, osid_managers.OsidProfile): + """The ``ProxyProfile`` describes the interoperability among proxy services.""" + + def supports_proxy(self): + """Tests if a proxy session is supported. + + :return: ``true`` if proxy is supported ``,`` ``false`` otherwise + :rtype: ``boolean`` + + *compliance: mandatory -- This method must be implemented.* + + """ + return 'supports_proxy' in profile.SUPPORTS + + def get_proxy_record_types(self): + """Gets the supported ``Proxy`` record interface types. + + :return: a list containing the supported ``Proxy`` record types + :rtype: ``osid.type.TypeList`` + + *compliance: mandatory -- This method must be implemented.* + + """ + from ..type.objects import TypeList + return TypeList([]) + + proxy_record_types = property(fget=get_proxy_record_types) + + def supports_proxy_record_type(self, proxy_record_type): + """Tests if the given ``Proxy`` record interface type is supported. + + :param proxy_record_type: a ``Type`` indicating a ``Proxy`` record type + :type proxy_record_type: ``osid.type.Type`` + :return: ``true`` if the given type is supported, ``false`` otherwise + :rtype: ``boolean`` + :raise: ``NullArgument`` -- ``proxy_record_type`` is ``null`` + + *compliance: mandatory -- This method must be implemented.* + + """ + return proxy_record_type in self.get_proxy_record_types() + + def get_proxy_condition_record_types(self): + """Gets the supported ``ProxyCondition`` record interface types. + + :return: a list containing the supported ``ProxyCondition`` record types + :rtype: ``osid.type.TypeList`` + + + *compliance: mandatory -- This method must be implemented.* + + """ + return TypeList(profile.PROXY_CONDITION_RECORD_TYPES) + + proxy_condition_record_types = property(fget=get_proxy_condition_record_types) + + def supports_proxy_condition_record_type(self, proxy_condition_record_type): + """Tests if the given ``ProxyCondition`` record interface type is supported. + + :param proxy_condition_record_type: a ``Type`` indicating a ``ProxyCondition`` record type + :type proxy_condition_record_type: ``osid.type.Type`` + :return: ``true`` if the given type is supported, ``false`` otherwise + :rtype: ``boolean`` + :raise: ``NullArgument`` -- ``proxy_condition_record_type`` is ``null`` + + *compliance: mandatory -- This method must be implemented.* + + """ + return proxy_condition_record_type in self.get_proxy_condition_record_types() + + +class ProxyManager(abc_proxy_managers.ProxyManager, osid_managers.OsidManager, ProxyProfile): + """The proxy manager provides access to proxy sessions and provides interoperability tests for various aspects of this service. + + The sessions included in this manager are: + + * ``ProxySession:`` a session to acquire proxy interfaces + """ + + def get_proxy_session(self): + """Gets a ``ProxySession`` which is responsible for acquiring authentication credentials on behalf of a service client. + + :return: a proxy session for this service + :rtype: ``osid.proxy.ProxySession`` + :raise: ``OperationFailed`` -- unable to complete request + :raise: ``Unimplemented`` -- ``supports_proxy()`` is ``false`` + + *compliance: optional -- This method must be implemented if ``supports_proxy()`` is ``true``.* + + """ + if not self.supports_proxy(): + raise Unimplemented() + try: + from . import sessions + except ImportError: + raise # OperationFailed() + try: + session = sessions.ProxySession() + except AttributeError: + raise # OperationFailed() + return session + + proxy_session = property(fget=get_proxy_session) + + +class ProxyProxyManager(abc_proxy_managers.ProxyProxyManager, osid_managers.OsidProxyManager, ProxyProfile): + """The proxy proxy manager provides access to proxy sessions and provides interoperability tests for various aspects of this service. + + Methods in this manager support the passing of a ``Proxy``. The + sessions included in this manager are: + + * ``ProxySession:`` a session to acquire proxies + """ + + def get_proxy_session(self, proxy): + """Gets the ``OsidSession`` associated with the ``ProxySession`` using the supplied ``Proxy``. + + :param proxy: proxy + :type proxy: ``osid.proxy.Proxy`` + :return: a ``ProxySession`` + :rtype: ``osid.proxy.ProxySession`` + :raise: ``NullArgument`` -- ``proxy`` is ``null`` + :raise: ``OperationFailed`` -- unable to complete request + :raise: ``Unimplemented`` -- ``supports_proxy()`` is ``false`` + + *compliance: optional -- This method must be implemented if ``supports_proxy()`` is ``true``.* + + """ + raise Unimplemented() diff --git a/pool/shard001/Python/0012554_notifications.py b/pool/shard001/Python/0012554_notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..dface20ec8d89a1508b2105b13460bdc3eab4d13 --- /dev/null +++ b/pool/shard001/Python/0012554_notifications.py @@ -0,0 +1,138 @@ +# Copyright 2014 Mirantis Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from oslo.config import cfg +import oslo.messaging + +from ceilometer import plugin +from ceilometer import sample + +OPTS = [ + cfg.StrOpt('keystone_control_exchange', + default='keystone', + help="Exchange name for Keystone notifications."), +] + + +cfg.CONF.register_opts(OPTS) + +SERVICE = 'identity' + + +class _Base(plugin.NotificationBase): + """Convert identity notification into Samples.""" + + resource_type = None + resource_name = None + + @staticmethod + def get_targets(conf): + """Return a sequence of oslo.messaging.Target + + Sequence defining the exchange and topics to be connected for this + plugin. + """ + return [oslo.messaging.Target(topic=topic, + exchange=conf.keystone_control_exchange) + for topic in conf.notification_topics] + + +class IdentityCRUD(_Base): + def process_notification(self, message): + yield sample.Sample.from_notification( + name=message['event_type'], + type=sample.TYPE_DELTA, + unit=self.resource_type, + volume=1, + resource_id=message['payload']['resource_info'], + user_id=None, + project_id=None, + message=message) + + +class User(IdentityCRUD): + + resource_type = 'user' + resource_name = '%s.%s' % (SERVICE, resource_type) + + @property + def event_types(self): + return ['%s.*' % self.resource_name] + + +class Group(IdentityCRUD): + + resource_type = 'group' + resource_name = '%s.%s' % (SERVICE, resource_type) + + @property + def event_types(self): + return ['%s.*' % self.resource_name] + + +class Project(IdentityCRUD): + + resource_type = 'project' + resource_name = '%s.%s' % (SERVICE, resource_type) + + @property + def event_types(self): + return ['%s.*' % self.resource_name] + + +class Role(IdentityCRUD): + + resource_type = 'role' + resource_name = '%s.%s' % (SERVICE, resource_type) + + @property + def event_types(self): + return ['%s.*' % self.resource_name] + + +class Trust(IdentityCRUD): + + resource_type = 'OS-TRUST:trust' + resource_name = '%s.%s' % (SERVICE, resource_type) + + @property + def event_types(self): + return [ + '%s.created' % self.resource_name, + '%s.deleted' % self.resource_name, + ] + + +class Authenticate(_Base): + """Convert identity authentication notifications into Samples.""" + + resource_type = 'authenticate' + event_name = '%s.%s' % (SERVICE, resource_type) + + def process_notification(self, message): + outcome = message['payload']['outcome'] + meter_name = '%s.%s.%s' % (SERVICE, self.resource_type, outcome) + + yield sample.Sample.from_notification( + name=meter_name, + type=sample.TYPE_DELTA, + unit='user', + volume=1, + resource_id=message['payload']['initiator']['id'], + user_id=message['payload']['initiator']['id'], + project_id=None, + message=message) + + @property + def event_types(self): + return [self.event_name] diff --git a/pool/shard001/Python/0012559_tests.py b/pool/shard001/Python/0012559_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6f78641730c55d19fea9fa5646b4ecfc039675 --- /dev/null +++ b/pool/shard001/Python/0012559_tests.py @@ -0,0 +1,111 @@ +from django.conf import settings +from django.db import connection, DEFAULT_DB_ALIAS +from django.test import TestCase, skipUnlessDBFeature +from django.utils import functional + +from models import Reporter, Article + +# +# The introspection module is optional, so methods tested here might raise +# NotImplementedError. This is perfectly acceptable behavior for the backend +# in question, but the tests need to handle this without failing. Ideally we'd +# skip these tests, but until #4788 is done we'll just ignore them. +# +# The easiest way to accomplish this is to decorate every test case with a +# wrapper that ignores the exception. +# +# The metaclass is just for fun. +# + +def ignore_not_implemented(func): + def _inner(*args, **kwargs): + try: + return func(*args, **kwargs) + except NotImplementedError: + return None + functional.update_wrapper(_inner, func) + return _inner + +class IgnoreNotimplementedError(type): + def __new__(cls, name, bases, attrs): + for k,v in attrs.items(): + if k.startswith('test'): + attrs[k] = ignore_not_implemented(v) + return type.__new__(cls, name, bases, attrs) + +class IntrospectionTests(TestCase): + __metaclass__ = IgnoreNotimplementedError + + def test_table_names(self): + tl = connection.introspection.table_names() + self.assert_(Reporter._meta.db_table in tl, + "'%s' isn't in table_list()." % Reporter._meta.db_table) + self.assert_(Article._meta.db_table in tl, + "'%s' isn't in table_list()." % Article._meta.db_table) + + def test_django_table_names(self): + cursor = connection.cursor() + cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);'); + tl = connection.introspection.django_table_names() + cursor.execute("DROP TABLE django_ixn_test_table;") + self.assert_('django_ixn_testcase_table' not in tl, + "django_table_names() returned a non-Django table") + + def test_installed_models(self): + tables = [Article._meta.db_table, Reporter._meta.db_table] + models = connection.introspection.installed_models(tables) + self.assertEqual(models, set([Article, Reporter])) + + def test_sequence_list(self): + sequences = connection.introspection.sequence_list() + expected = {'table': Reporter._meta.db_table, 'column': 'id'} + self.assert_(expected in sequences, + 'Reporter sequence not found in sequence_list()') + + def test_get_table_description_names(self): + cursor = connection.cursor() + desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) + self.assertEqual([r[0] for r in desc], + [f.column for f in Reporter._meta.fields]) + + def test_get_table_description_types(self): + cursor = connection.cursor() + desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) + self.assertEqual( + [datatype(r[1], r) for r in desc], + ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField'] + ) + + # Regression test for #9991 - 'real' types in postgres + @skipUnlessDBFeature('has_real_datatype') + def test_postgresql_real_type(self): + cursor = connection.cursor() + cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);") + desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table') + cursor.execute('DROP TABLE django_ixn_real_test_table;') + self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField') + + def test_get_relations(self): + cursor = connection.cursor() + relations = connection.introspection.get_relations(cursor, Article._meta.db_table) + + # Older versions of MySQL don't have the chops to report on this stuff, + # so just skip it if no relations come back. If they do, though, we + # should test that the response is correct. + if relations: + # That's {field_index: (field_index_other_table, other_table)} + self.assertEqual(relations, {3: (0, Reporter._meta.db_table)}) + + def test_get_indexes(self): + cursor = connection.cursor() + indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table) + self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False}) + + +def datatype(dbtype, description): + """Helper to convert a data type into a string.""" + dt = connection.introspection.get_field_type(dbtype, description) + if type(dt) is tuple: + return dt[0] + else: + return dt diff --git a/pool/shard001/Python/0012562_message_parser.py b/pool/shard001/Python/0012562_message_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..256230d2672870a6d4d38408a7e27531c849fdf3 --- /dev/null +++ b/pool/shard001/Python/0012562_message_parser.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python +# +# Copyright 2007 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +"""Describe ProtoRPC Messages in JSON Schema. + +Add protorpc.message subclasses to MessageTypeToJsonSchema and get a JSON +Schema description of all the messages. +""" + + +import re + +from protorpc import message_types +from protorpc import messages + +__all__ = ['MessageTypeToJsonSchema'] + + +class MessageTypeToJsonSchema(object): + """Describe ProtoRPC messages in JSON Schema. + + Add protorpc.message subclasses to MessageTypeToJsonSchema and get a JSON + Schema description of all the messages. MessageTypeToJsonSchema handles + all the types of fields that can appear in a message. + """ + + + + + + + + __FIELD_TO_SCHEMA_TYPE_MAP = { + messages.IntegerField: {messages.Variant.INT32: ('integer', 'int32'), + messages.Variant.INT64: ('string', 'int64'), + messages.Variant.UINT32: ('integer', 'uint32'), + messages.Variant.UINT64: ('string', 'uint64'), + messages.Variant.SINT32: ('integer', 'int32'), + messages.Variant.SINT64: ('string', 'int64'), + None: ('integer', 'int64')}, + messages.FloatField: {messages.Variant.FLOAT: ('number', 'float'), + messages.Variant.DOUBLE: ('number', 'double'), + None: ('number', 'float')}, + messages.BooleanField: ('boolean', None), + messages.BytesField: ('string', 'byte'), + message_types.DateTimeField: ('string', 'date-time'), + messages.StringField: ('string', None), + messages.MessageField: ('object', None), + messages.EnumField: ('string', None), + } + + __DEFAULT_SCHEMA_TYPE = ('string', None) + + def __init__(self): + + self.__schemas = {} + + + self.__normalized_names = {} + + def add_message(self, message_type): + """Add a new message. + + Args: + message_type: protorpc.message.Message class to be parsed. + + Returns: + string, The JSON Schema id. + + Raises: + KeyError if the Schema id for this message_type would collide with the + Schema id of a different message_type that was already added. + """ + name = self.__normalized_name(message_type) + if name not in self.__schemas: + + self.__schemas[name] = None + schema = self.__message_to_schema(message_type) + self.__schemas[name] = schema + return name + + def ref_for_message_type(self, message_type): + """Returns the JSON Schema id for the given message. + + Args: + message_type: protorpc.message.Message class to be parsed. + + Returns: + string, The JSON Schema id. + + Raises: + KeyError: if the message hasn't been parsed via add_message(). + """ + name = self.__normalized_name(message_type) + if name not in self.__schemas: + raise KeyError('Message has not been parsed: %s', name) + return name + + def schemas(self): + """Returns the JSON Schema of all the messages. + + Returns: + object: JSON Schema description of all messages. + """ + return self.__schemas.copy() + + def __normalized_name(self, message_type): + """Normalized schema name. + + Generate a normalized schema name, taking the class name and stripping out + everything but alphanumerics, and camel casing the remaining words. + A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]* + + Args: + message_type: protorpc.message.Message class being parsed. + + Returns: + A string, the normalized schema name. + + Raises: + KeyError if a collision is found between normalized names. + """ + + + name = message_type.definition_name() + + split_name = re.split(r'[^0-9a-zA-Z]', name) + normalized = ''.join( + part[0].upper() + part[1:] for part in split_name if part) + + previous = self.__normalized_names.get(normalized) + if previous: + if previous != name: + raise KeyError('Both %s and %s normalize to the same schema name: %s' % + (name, previous, normalized)) + else: + self.__normalized_names[normalized] = name + + return normalized + + def __message_to_schema(self, message_type): + """Parse a single message into JSON Schema. + + Will recursively descend the message structure + and also parse other messages references via MessageFields. + + Args: + message_type: protorpc.messages.Message class to parse. + + Returns: + An object representation of the schema. + """ + name = self.__normalized_name(message_type) + schema = { + 'id': name, + 'type': 'object', + } + if message_type.__doc__: + schema['description'] = message_type.__doc__ + properties = {} + for field in message_type.all_fields(): + descriptor = {} + + + + type_info = {} + + if type(field) == messages.MessageField: + field_type = field.type().__class__ + type_info['$ref'] = self.add_message(field_type) + if field_type.__doc__: + descriptor['description'] = field_type.__doc__ + else: + schema_type = self.__FIELD_TO_SCHEMA_TYPE_MAP.get( + type(field), self.__DEFAULT_SCHEMA_TYPE) + + + if isinstance(schema_type, dict): + variant_map = schema_type + variant = getattr(field, 'variant', None) + if variant in variant_map: + schema_type = variant_map[variant] + else: + + schema_type = variant_map[None] + type_info['type'] = schema_type[0] + if schema_type[1]: + type_info['format'] = schema_type[1] + + if type(field) == messages.EnumField: + sorted_enums = sorted([enum_info for enum_info in field.type], + key=lambda enum_info: enum_info.number) + type_info['enum'] = [enum_info.name for enum_info in sorted_enums] + + if field.required: + descriptor['required'] = True + + if field.default: + if type(field) == messages.EnumField: + descriptor['default'] = str(field.default) + else: + descriptor['default'] = field.default + + if field.repeated: + descriptor['items'] = type_info + descriptor['type'] = 'array' + else: + descriptor.update(type_info) + + properties[field.name] = descriptor + + schema['properties'] = properties + + return schema diff --git a/pool/shard001/Python/0012567_config.py b/pool/shard001/Python/0012567_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4d43e1d1b2c6ad168f24c23b1a25a8e5f86c3717 --- /dev/null +++ b/pool/shard001/Python/0012567_config.py @@ -0,0 +1,76 @@ +# Copyright 2015 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This file contains all of the configuration values for the application. +Update this file with the values for your specific Google Cloud project. +You can create and manage projects at https://console.developers.google.com +""" + +import os + +# The secret key is used by Flask to encrypt session cookies. +SECRET_KEY = 'secret' + +# There are three different ways to store the data in the application. +# You can choose 'datastore', 'cloudsql', or 'mongodb'. Be sure to +# configure the respective settings for the one you choose below. +# You do not have to configure the other data backends. If unsure, choose +# 'datastore' as it does not require any additional configuration. +DATA_BACKEND = 'datastore' + +# Google Cloud Project ID. This can be found on the 'Overview' page at +# https://console.developers.google.com +PROJECT_ID = 'your-project-id' + +# CloudSQL & SQLAlchemy configuration +# Replace the following values the respective values of your Cloud SQL +# instance. +CLOUDSQL_USER = 'root' +CLOUDSQL_PASSWORD = 'your-cloudsql-password' +CLOUDSQL_DATABASE = 'bookshelf' +# Set this value to the Cloud SQL connection name, e.g. +# "project:region:cloudsql-instance". +# You must also update the value in app.yaml. +CLOUDSQL_CONNECTION_NAME = 'your-cloudsql-connection-name' + +# The CloudSQL proxy is used locally to connect to the cloudsql instance. +# To start the proxy, use: +# +# $ cloud_sql_proxy -instances=your-connection-name=tcp:3306 +# +# Alternatively, you could use a local MySQL instance for testing. +LOCAL_SQLALCHEMY_DATABASE_URI = ( + 'mysql+pymysql://{user}:{password}@localhost/{database}').format( + user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, + database=CLOUDSQL_DATABASE) + +# When running on App Engine a unix socket is used to connect to the cloudsql +# instance. +LIVE_SQLALCHEMY_DATABASE_URI = ( + 'mysql+pymysql://{user}:{password}@localhost/{database}' + '?unix_socket=/cloudsql/{connection_name}').format( + user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD, + database=CLOUDSQL_DATABASE, connection_name=CLOUDSQL_CONNECTION_NAME) + +if os.environ.get('GAE_APPENGINE_HOSTNAME'): + SQLALCHEMY_DATABASE_URI = LIVE_SQLALCHEMY_DATABASE_URI +else: + SQLALCHEMY_DATABASE_URI = LOCAL_SQLALCHEMY_DATABASE_URI + +# Mongo configuration +# If using mongolab, the connection URI is available from the mongolab control +# panel. If self-hosting on compute engine, replace the values below. +MONGO_URI = \ + 'mongodb://user:password@host:27017/database' diff --git a/pool/shard001/Python/0012570_admin.py b/pool/shard001/Python/0012570_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..891ab055b2f99b33e07bb1645b02605755604e55 --- /dev/null +++ b/pool/shard001/Python/0012570_admin.py @@ -0,0 +1,98 @@ +import flask +from flask import request +from app import app, db +from themes import ThemeManager +from app.models import User, Post, Category +from app.forms import LoginForm, PostForm, CategoryForm +from app.manager import ModelManager + +Theme = ThemeManager.get_theme(app.config['THEME']) + +@app.route('/admin/') +def admin_index(): + user = User.get_current_user() + if user is None: + return flask.redirect(flask.url_for('admin_login')) + try: + page = int(request.args.get('page', 1)) + except ValueError: + page = 1 + + return flask.render_template(Theme.get_template(page='admin_index'), + manager=ModelManager, + page=page) + + +@app.route('/admin/login/', methods=['GET', 'POST']) +def admin_login(): + user = User.get_current_user() + if user is not None: + return flask.redirect(flask.url_for('admin_index')) + + login_form = LoginForm() + + if request.method == 'POST' and login_form.validate_on_submit(): + # Actually check if we have such a user in the db + existing_user, error = User.authenticate(login_form.email.data, + login_form.password.data) + + if existing_user: + existing_user.login() + return flask.redirect(flask.url_for('admin_index')) + + login_form.email.errors.append('Invalid username or password') + + return flask.render_template(Theme.get_template(page='admin_login'), + manager=ModelManager, form=login_form) + + +@app.route('/admin/logout/', methods=['GET', 'POST']) +def admin_logout(): + User.logout() + return flask.redirect(flask.url_for('admin_login')) + + +@app.route('/admin/categories', methods=['GET', 'POST']) +def admin_categories(): + category_form = CategoryForm() + + if request.method == 'POST' and category_form.validate_on_submit(): + category = Category(name=request.form['category_name']) + + db.session.add(category) + db.session.commit() + db.session.flush() + flask.flash('Your category has been created', 'success') + + return flask.render_template(Theme.get_template(page='admin_categories'), + manager=ModelManager, form=category_form) + + +@app.route('/admin/post/add/', methods=['GET', 'POST']) +def admin_add_post(): + form = PostForm() + + if request.method == 'POST' and form.validate_on_submit(): + post = Post(title=request.form['title'], + content=request.form['content'], + summary=request.form['summary']) + + post.author_id = ModelManager.current_user().id + post.category_id = form.category.data + + post.before_save() + + db.session.add(post) + db.session.commit() + db.session.flush() + flask.flash('Your post has been created', 'success') + + return flask.render_template(Theme.get_template(page='admin_add_post'), + manager=ModelManager, + post_form=form) + +@app.route('/admin/post//', methods=['GET', 'POST']) +def admin_detail_post(id): + return flask.render_template(Theme.get_template(page='admin_detail_post'), + manager=ModelManager, + post_id=id) diff --git a/pool/shard001/Python/0012576_objects.py b/pool/shard001/Python/0012576_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a03c29ac6fe03e031c6a05cdd083b34dacbfa7 --- /dev/null +++ b/pool/shard001/Python/0012576_objects.py @@ -0,0 +1,143 @@ +from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError +from queries import Queries +from object import Object + + +class Objects(Queries): + def __repr__(self): + return self._execute_query() + + def __unicode__(self): + return self._execute_query() + + def __str__(self): + return str(self._execute_query()) + + def __len__(self): + return len(self._execute_query()) + + def __getitem__(self, item): + return self._execute_query()[item] + + def __bool__(self): + return self._execute_query() + + def __nonzero__(self): + return bool(self._execute_query()) + + def __contains__(self, item): + return item in self._execute_query() + + def __iter__(self): + for item in self._execute_query(): + yield item + + def __getattr__(self, item): + structure = self._storage_read()['structure'] + if item in structure: + return self._execute_query().__getattribute__(item) + else: + raise AttributeError('Object has no attribute \'%s\'' % item) + + def __setattr__(self, key, value): + if key == 'id': + raise AttributeError('\'id\' is non-editable field') + else: + return super(Objects, self).__setattr__(key, value) + + def create(self, **kwargs): + """ + Create row in the storage (method return's created object) + :param kwargs: + :return: + """ + storage = self._storage_read() + kwargs['id'] = storage['last_id'] + 1 + row = list() + + for k, v in kwargs.items(): + if k not in storage['structure']: + structure = str(', '.join(storage['structure'][1:])) + raise FieldError('The column "%s" is absent in storage structure! ' + 'You have: %s' % (k, structure)) + + for field in storage['structure']: + if field not in kwargs.keys(): + raise FieldError('Field "%s" is missed!' % field) + else: + row.append(kwargs[field]) + + storage = self._storage_read() + storage['data'].append(row) + storage['last_id'] += 1 + + self._storage_write(storage) + return Object(self.request, self.session_name, *row) + + def clear(self): + self._storage_clear() + + def get(self, **kwargs): + """ + Get row from storage by fields values + :param kwargs: + :return: + """ + self.filter(**kwargs) + result = self._execute_query() + if len(result) == 0: + raise ObjectDoesNotExist + elif len(result) > 1: + raise MultipleObjectsReturned('Change your get-query or use filter.') + + return result[0] + + def all(self): + """ + Get all rows from storage + :return: + """ + self._add_query('all') + return self + + def filter(self, **rules): + """ + Get filtered rows from storage by fields values + :param rules: + :return: + """ + self._add_query('filter', rules) + return self + + def exclude(self, **rules): + """ + Get filtered rows from storage by exclude fields values + :param rules: + :return: + """ + self._add_query('exclude', rules) + return self + + def order_by(self, *rules): + """ + Query response ordering + :return: + """ + self._add_query('order_by', rules) + return self + + def count(self): + """ + Get rows count + :return: + """ + self._add_query('count') + return self + + def exists(self): + """ + Check element existing + :return: + """ + self._add_query('exists') + return self diff --git a/pool/shard001/Python/0012577_test_dbapi_compliance.py b/pool/shard001/Python/0012577_test_dbapi_compliance.py new file mode 100644 index 0000000000000000000000000000000000000000..13ef7889f67dc761317028c78a13ffd5a349a848 --- /dev/null +++ b/pool/shard001/Python/0012577_test_dbapi_compliance.py @@ -0,0 +1,98 @@ +# Copyright 2013 Cloudera Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""" +This test module simply wraps _dbapi20_tests.py, which ensure that our +PEP 249 implementation is compliant. +""" + + +from __future__ import absolute_import, print_function + +import pytest + +import impala.dbapi +from impala.tests.util import ImpylaTestEnv +from impala.util import ( + _random_id, force_drop_impala_database, force_drop_hive_database) +# must import the module, rather than the class, per comment in module +from impala.tests import _dbapi20_tests + + +ENV = ImpylaTestEnv() +tmp_db = _random_id('tmp_impyla_dbapi_') +hive = ENV.auth_mech == 'PLAIN' + + +@pytest.mark.connect +class ImpalaDBAPI20Test(_dbapi20_tests.DatabaseAPI20Test): + driver = impala.dbapi + connect_kw_args = {'host': ENV.host, + 'port': ENV.port, + 'auth_mechanism': ENV.auth_mech, + 'database': tmp_db} + + ddl1 = 'create table {0}booze (name string)'.format( + _dbapi20_tests.DatabaseAPI20Test.table_prefix) + ddl2 = 'create table {0}barflys (name string)'.format( + _dbapi20_tests.DatabaseAPI20Test.table_prefix) + + @classmethod + def setUpClass(cls): + con = cls.driver.connect(host=ENV.host, port=ENV.port, + auth_mechanism=ENV.auth_mech) + cur = con.cursor() + cur.execute('CREATE DATABASE {0}'.format(tmp_db)) + cur.close() + con.close() + + @classmethod + def tearDownClass(cls): + con = cls.driver.connect(host=ENV.host, port=ENV.port, + auth_mechanism=ENV.auth_mech) + cur = con.cursor() + if hive: + force_drop_hive_database(cur, tmp_db) + else: + force_drop_impala_database(cur, tmp_db) + cur.close() + con.close() + + def test_nextset(self): + pass + + def test_setoutputsize(self): + pass + + # The following tests fail against Hive. We override them so we can skip on + # Hive, and otherwise execute the superclass version. + + HIVE_STRING_ESCAPE_ERROR = 'HIVE-11723' + + @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR) + def test_execute(self): + super(ImpalaDBAPI20Test, self).test_execute() + + @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR) + def test_executemany(self): + super(ImpalaDBAPI20Test, self).test_executemany() + + @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR) + def test_setinputsizes(self): + super(ImpalaDBAPI20Test, self).test_setinputsizes() + + @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR) + def test_setoutputsize_basic(self): + super(ImpalaDBAPI20Test, self).test_setoutputsize_basic() diff --git a/pool/shard001/Python/0012583_0002_set_site_domain_and_name.py b/pool/shard001/Python/0012583_0002_set_site_domain_and_name.py new file mode 100644 index 0000000000000000000000000000000000000000..6eadbecb65869da454c09532cfe9f12bf4572de2 --- /dev/null +++ b/pool/shard001/Python/0012583_0002_set_site_domain_and_name.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.conf import settings +from django.db import models, migrations + + +def update_site_forward(apps, schema_editor): + """Set site domain and name.""" + Site = apps.get_model("sites", "Site") + Site.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + "domain": "appagoo.com", + "name": "Appagoo" + } + ) + + +def update_site_backward(apps, schema_editor): + """Revert site domain and name to default.""" + Site = apps.get_model("sites", "Site") + Site.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + "domain": "example.com", + "name": "example.com" + } + ) + + +class Migration(migrations.Migration): + + dependencies = [ + ('sites', '0001_initial'), + ] + + operations = [ + migrations.RunPython(update_site_forward, update_site_backward), + ] \ No newline at end of file diff --git a/pool/shard001/Python/0012590_bugcve.py b/pool/shard001/Python/0012590_bugcve.py new file mode 100644 index 0000000000000000000000000000000000000000..26070d9b404ec3f662b830c91e17422e9f92a71d --- /dev/null +++ b/pool/shard001/Python/0012590_bugcve.py @@ -0,0 +1,28 @@ +# Copyright 2009 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +__metaclass__ = type +__all__ = ['BugCve'] + +from sqlobject import ForeignKey +from zope.interface import implements + +from lp.bugs.interfaces.bugcve import IBugCve +from lp.services.database.sqlbase import SQLBase + + +class BugCve(SQLBase): + """A table linking bugs and CVE entries.""" + + implements(IBugCve) + + _table = 'BugCve' + + # db field names + bug = ForeignKey(dbName='bug', foreignKey='Bug', notNull=True) + cve = ForeignKey(dbName='cve', foreignKey='Cve', notNull=True) + + @property + def target(self): + """See IBugLink.""" + return self.cve diff --git a/pool/shard001/Python/0012597_main.py b/pool/shard001/Python/0012597_main.py new file mode 100644 index 0000000000000000000000000000000000000000..32a8dab63e1acb47e6d7808c100f8b6813d8d71b --- /dev/null +++ b/pool/shard001/Python/0012597_main.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import collections +import os +import StringIO + +import jinja2 +import webapp2 +from PIL import Image + +from google.appengine.api import memcache +from google.appengine.api import users +from google.appengine.ext import ndb + +import meme + + +TODO = None + +JINJA_ENV = jinja2.Environment( + loader=jinja2.FileSystemLoader( + os.path.join(os.path.dirname(__file__), 'templates')), + extensions=['jinja2.ext.autoescape']) + +MEME_TEMPLATES = collections.OrderedDict([ + ('happyboy', 'happyboy.jpeg'), + ('rapperboy', 'rapperboy.jpeg'), + ('realappengine', 'realappengine.jpeg'), + ('shrugging', 'shrugging.jpeg'), + ('bathing', 'bathing.jpeg'), +]) + +DEFAULT_TEMPLATE = 'happyboy.jpeg' + +IMAGE_DIR = 'images' + +MEME_FONTS = collections.OrderedDict([ + ('mikachan', 'mikachan.ttf'), + ('FreeSerif', 'FreeSerif.ttf'), +]) + +DEFAULT_FONT = 'FreeSerif.ttf' + +FONT_DIR = 'fonts' + +THUMBNAIL_SIZE = (400, 400) + +PAGE_SIZE = 40 + +MEMCACHE_RECENT_KEY = 'recent' + + +def get_login_logout_context(target_url): + """Returns nickname, link url and link text for the common_header.html.""" + user = users.get_current_user() + if user: + nickname = user.nickname() + link_text = 'Logout' + link_url = users.create_logout_url(target_url) + else: + nickname = 'Anonymous user' + link_text = 'Login' + link_url = users.create_login_url(target_url) + return nickname, link_url, link_text + + +class MainHandler(webapp2.RequestHandler): + """A handler for showing an HTML form.""" + + def get(self): + """Render an HTML form for creating Memes.""" + template = JINJA_ENV.get_template('index.html') + nickname, link_url, link_text = get_login_logout_context( + self.request.uri) + context = { + 'templates': MEME_TEMPLATES, + 'fonts': MEME_FONTS, + 'nickname': nickname, + 'link_text': link_text, + 'link_url': link_url + } + self.response.out.write(template.render(context)) + + +class ImageHandler(webapp2.RequestHandler): + """A handler for rendering and saving Memes.""" + + def render_meme(self): + """Renders an image with given HTTP parameters. + + Returns: + A rendered Image object. + """ + meme_template = self.request.get('meme_template') + image = Image.open(os.path.join(IMAGE_DIR, + MEME_TEMPLATES.get(meme_template, DEFAULT_TEMPLATE))) + meme_font = self.request.get('meme_font') + font_file = os.path.join(FONT_DIR, + MEME_FONTS.get(meme_font, DEFAULT_FONT)) + upper_text = self.request.get('upper_text') + upper_text_align = self.request.get('upper_text_align', meme.MIDDLE) + middle_text = self.request.get('middle_text') + middle_text_align = self.request.get('middle_text_align', meme.MIDDLE) + lower_text = self.request.get('lower_text') + lower_text_align = self.request.get('lower_text_align', meme.MIDDLE) + if upper_text: + meme.draw_text(image, meme.TOP, upper_text_align, upper_text, + font_file=font_file) + if middle_text: + meme.draw_text(image, meme.MIDDLE, middle_text_align, middle_text, + font_file=font_file) + if lower_text: + meme.draw_text(image, meme.BOTTOM, lower_text_align, lower_text, + font_file=font_file) + return image + + def get(self): + """A handler for rendering a preview image.""" + image = self.render_meme() + self.response.headers['Content-Type'] = 'image/jpg' + image.save(self.response.out, 'JPEG') + + def post(self): + """A handler for save the meme.""" + image = self.render_meme() + new_meme = meme.Meme() + user = users.get_current_user() + if user: + new_meme.owner = user + output = StringIO.StringIO() + thumbnail_output = StringIO.StringIO() + image.save(output, "JPEG") + image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) + image.save(thumbnail_output, "JPEG") + new_meme.image = output.getvalue() + new_meme.thumbnail = thumbnail_output.getvalue() + output.close() + thumbnail_output.close() + new_meme.put() + # step-3 + # It is important to delete the cache here for recent query. + # Otherwise, the 'Recent' page will keep serving an old list. + memcache.delete(MEMCACHE_RECENT_KEY) + self.redirect("/meme/{}".format(new_meme.key.id()), abort=True) + + +class MemeHandler(webapp2.RequestHandler): + """A handler for rendering an HTML page of a particular meme.""" + + def get(self, meme_id): + """Renders an HTML page of a Meme with a given id. + + Raises a 404 error when entity not found. + + Args: + meme_id: id of Meme entity extracted from the URL path. + """ + target = meme.Meme.get_by_id(long(meme_id)) + if target is None: + self.abort(404) + nickname, link_url, link_text = get_login_logout_context( + self.request.uri) + template = JINJA_ENV.get_template('meme.html') + if target.owner: + owner_nickname = target.owner.nickname() + else: + owner_nickname = 'Anonymous user' + context = { + 'nickname': nickname, + 'link_url': link_url, + 'link_text': link_text, + 'meme_owner': owner_nickname, + 'meme_id': target.key.id(), + 'meme_created_date': target.created_at, + } + self.response.write(template.render(context)) + + +class MemeImageHandler(webapp2.RequestHandler): + """A handler for serving an image of a particular meme.""" + + def get(self, mode, meme_id): + """Serves an image of a particular meme. + + Raises a 404 error when entity not found. + + Args: + mode: 'image' or 'thumbnail', extracted from the URL path. + meme_id: id of Meme entity extracted from the URL path. + """ + target = meme.Meme.get_by_id(long(meme_id)) + if target is None: + self.abort(404) + self.response.headers['Content-Type'] = 'image/jpeg' + if mode == 'image': + self.response.write(target.image) + else: + self.response.write(target.thumbnail) + + +class MemeListingHandler(webapp2.RequestHandler): + """A handler for listing recent memes.""" + + def get(self, mode): + """Display a list of memes according to given conditions. + + The condition is given by the URL. Currently only 'recent' and + 'mine' are implemented. + """ + if mode == 'recent': + meme_keys = memcache.get(MEMCACHE_RECENT_KEY) + if meme_keys is not None: + memes = ndb.get_multi(meme_keys) + else: + # step-3 + # Complete the query object. We want meme.Meme + # objects ordered by the created_at in a descending + # order. + query = meme.Meme.query().order(-meme.Meme.created_at) + memes = query.fetch(PAGE_SIZE) + memcache.set(MEMCACHE_RECENT_KEY, [m.key for m in memes]) + title = 'Recent memes' + elif mode == 'mine': + user = users.get_current_user() + if user is None: + self.redirect(users.create_login_url(self.request.uri), + abort=True) + query = meme.Meme.query(meme.Meme.owner==user)\ + .order(-meme.Meme.created_at) + title = 'Your memes' + memes = query.fetch(PAGE_SIZE) + nickname, link_url, link_text = get_login_logout_context( + self.request.uri) + template = JINJA_ENV.get_template('list_meme.html') + context = { + 'title': title, + 'nickname': nickname, + 'link_url': link_url, + 'link_text': link_text, + 'memes': memes, + } + self.response.write(template.render(context)) + + +APPLICATION = webapp2.WSGIApplication([ + ('/', MainHandler), + ('/preview', ImageHandler), + ('/create_meme', ImageHandler), + ('/meme/(\d+)', MemeHandler), + ('/(image|thumbnail)/(\d+)', MemeImageHandler), + ('/(recent|mine)', MemeListingHandler), +], debug=True) diff --git a/pool/shard001/Python/0012600_0001_initial.py b/pool/shard001/Python/0012600_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..ee716583ad892f953f7cd413c0c08807edf9e512 --- /dev/null +++ b/pool/shard001/Python/0012600_0001_initial.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2017-11-09 17:54 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('core', '0011_text_format'), + ] + + operations = [ + migrations.CreateModel( + name='Achievement', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('description', models.TextField(blank=True)), + ('points', models.PositiveIntegerField()), + ('icon_path', models.CharField(max_length=255)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('amount', models.IntegerField(blank=True, default=None, null=True)), + ('author', models.CharField(blank=True, default=None, max_length=255, null=True)), + ('origin', models.CharField(blank=True, default=None, max_length=255, null=True)), + ('contest', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Contest')), + ('problem', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Problem')), + ], + options={ + 'db_table': 'achievements', + 'get_latest_by': 'created_at', + }, + ), + migrations.CreateModel( + name='UserAchievement', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('earned_at', models.DateTimeField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('achievement', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='achievements.Achievement')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'db_table': 'user_achievements', + 'get_latest_by': 'created_at', + }, + ), + ] diff --git a/pool/shard001/Python/0012607_wsgi.py b/pool/shard001/Python/0012607_wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..f52dba1a884f4d5b27c4392bde59a9bf2ce3a953 --- /dev/null +++ b/pool/shard001/Python/0012607_wsgi.py @@ -0,0 +1,28 @@ +import os,sys +virtenv = os.path.expanduser('~') + '/virtenv/' +virtualenv = os.path.join(virtenv, 'bin/activate_this.py') +try: + exec(open(virtualenv).read(), dict(__file__=virtualenv)) +except IOError: + pass + +sys.path.append(os.path.expanduser('~')) +sys.path.append(os.path.expanduser('~') + '/ROOT/') + +from werkzeug.serving import run_simple +from werkzeug.wsgi import DispatcherMiddleware + +from quokka import create_app, create_api + +application = DispatcherMiddleware(create_app(), { + '/api': create_api() +}) + +if __name__ == "__main__": + run_simple( + '0.0.0.0', + 5000, + application, + use_reloader=True, + use_debugger=True + ) diff --git a/pool/shard001/Python/0012608_init__.py b/pool/shard001/Python/0012608_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f3624167ab657a86a60b454dfe07c8063f65214 --- /dev/null +++ b/pool/shard001/Python/0012608_init__.py @@ -0,0 +1,178 @@ +############################################################################## +# +# Copyright (c) 2001, 2002 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +"""Unique id utility. + +This utility assigns unique integer ids to objects and allows lookups +by object and by id. + +This functionality can be used in cataloging. + +$Id: __init__.py 69786 2006-08-26 18:06:12Z philikon $ +""" +import random +from BTrees import IOBTree, OIBTree +from ZODB.interfaces import IConnection +from persistent import Persistent + +from zope.event import notify +from zope.interface import implements +from zope.security.proxy import removeSecurityProxy +from zope.location.interfaces import ILocation +from zope.component import adapter, getAllUtilitiesRegisteredFor + +from zope.app.container.interfaces import IObjectRemovedEvent +from zope.app.container.interfaces import IObjectAddedEvent +from zope.app.container.contained import Contained +from zope.app.keyreference.interfaces import IKeyReference, NotYet + +from zope.app.intid.interfaces import IIntIds +from zope.app.intid.interfaces import IntIdRemovedEvent +from zope.app.intid.interfaces import IntIdAddedEvent + +class IntIds(Persistent, Contained): + """This utility provides a two way mapping between objects and + integer ids. + + IKeyReferences to objects are stored in the indexes. + """ + implements(IIntIds) + + _v_nextid = None + + _randrange = random.randrange + + def __init__(self): + self.ids = OIBTree.OIBTree() + self.refs = IOBTree.IOBTree() + + def __len__(self): + return len(self.ids) + + def items(self): + return list(self.refs.items()) + + def __iter__(self): + return self.refs.iterkeys() + + def getObject(self, id): + return self.refs[id]() + + def queryObject(self, id, default=None): + r = self.refs.get(id) + if r is not None: + return r() + return default + + def getId(self, ob): + try: + key = IKeyReference(ob) + except (NotYet, TypeError): + raise KeyError(ob) + + try: + return self.ids[key] + except KeyError: + raise KeyError(ob) + + def queryId(self, ob, default=None): + try: + return self.getId(ob) + except KeyError: + return default + + def _generateId(self): + """Generate an id which is not yet taken. + + This tries to allocate sequential ids so they fall into the + same BTree bucket, and randomizes if it stumbles upon a + used one. + """ + while True: + if self._v_nextid is None: + self._v_nextid = self._randrange(0, 2**31) + uid = self._v_nextid + self._v_nextid += 1 + if uid not in self.refs: + return uid + self._v_nextid = None + + def register(self, ob): + # Note that we'll still need to keep this proxy removal. + ob = removeSecurityProxy(ob) + key = IKeyReference(ob) + + if key in self.ids: + return self.ids[key] + uid = self._generateId() + self.refs[uid] = key + self.ids[key] = uid + return uid + + def unregister(self, ob): + # Note that we'll still need to keep this proxy removal. + ob = removeSecurityProxy(ob) + key = IKeyReference(ob, None) + if key is None: + return + + uid = self.ids[key] + del self.refs[uid] + del self.ids[key] + + +@adapter(ILocation, IObjectRemovedEvent) +def removeIntIdSubscriber(ob, event): + """A subscriber to ObjectRemovedEvent + + Removes the unique ids registered for the object in all the unique + id utilities. + """ + utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) + if utilities: + key = IKeyReference(ob, None) + # Register only objects that adapt to key reference + if key is not None: + # Notify the catalogs that this object is about to be removed. + notify(IntIdRemovedEvent(ob, event)) + for utility in utilities: + try: + utility.unregister(key) + except KeyError: + pass + +@adapter(ILocation, IObjectAddedEvent) +def addIntIdSubscriber(ob, event): + """A subscriber to ObjectAddedEvent + + Registers the object added in all unique id utilities and fires + an event for the catalogs. + """ + utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) + if utilities: # assert that there are any utilites + key = IKeyReference(ob, None) + # Register only objects that adapt to key reference + if key is not None: + for utility in utilities: + utility.register(key) + # Notify the catalogs that this object was added. + notify(IntIdAddedEvent(ob, event)) + +# BBB +UniqueIdUtility = IntIds +import zope.app.keyreference.persistent +ReferenceToPersistent = ( + zope.app.keyreference.persistent.KeyReferenceToPersistent) +import sys +sys.modules['zope.app.uniqueid'] = sys.modules['zope.app.intid'] +del sys diff --git a/pool/shard001/Python/0012611_arguments.py b/pool/shard001/Python/0012611_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..192a3f70286d83eca798cf487253d3b285d2afe3 --- /dev/null +++ b/pool/shard001/Python/0012611_arguments.py @@ -0,0 +1,13 @@ +import sys + +if len(sys.argv) > 1: + + print('The following arguments were provided: {}'.format(*sys.argv[1:])) + + for c, arg in enumerate(sys.argv[1:]): + + description = input('Please give the description of input {0} with value {1}: '.format(c, arg)) + print('input number {0}, with value {1} is a {2} '.format(str(c), arg, description)) +else: + print('No argument was given to me, byebye now.') + diff --git a/pool/shard001/Python/0012613_test_offload.py b/pool/shard001/Python/0012613_test_offload.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5a5b3c6dc377ac6e150bc6415c3db06ce2983e --- /dev/null +++ b/pool/shard001/Python/0012613_test_offload.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 + +import unittest + +from framework import VppTestCase, VppTestRunner +from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath + + +class TestOffload(VppTestCase): + """ Offload Unit Test Cases """ + + @classmethod + def setUpClass(cls): + super(TestOffload, cls).setUpClass() + + @classmethod + def tearDownClass(cls): + super(TestOffload, cls).tearDownClass() + + def setUp(self): + super(TestOffload, self).setUp() + + def tearDown(self): + super(TestOffload, self).tearDown() + + def test_offload_unittest(self): + """ Checksum Offload Test """ + cmds = ["loop create", + "set int ip address loop0 11.22.33.1/24", + "set int state loop0 up", + "loop create", + "set int ip address loop1 11.22.34.1/24", + "set int state loop1 up", + "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44", + "packet-generator new {\n" + " name s0\n" + " limit 100\n" + " size 128-128\n" + " interface loop0\n" + " tx-interface loop1\n" + " node loop1-output\n" + " buffer-flags ip4 offload\n" + " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n" + " data {\n" + " IP4: 1.2.3 -> dead.0000.0001\n" + " UDP: 11.22.33.44 -> 11.22.34.44\n" + " ttl 2 checksum 13\n" + " UDP: 1234 -> 2345\n" + " checksum 11\n" + " incrementing 114\n" + " }\n" + "}", + "trace add pg-input 1", + "pa en", + "show error"] + + for cmd in cmds: + r = self.vapi.cli_return_response(cmd) + if r.retval != 0: + if hasattr(r, 'reply'): + self.logger.info(cmd + " FAIL reply " + r.reply) + else: + self.logger.info(cmd + " FAIL retval " + str(r.retval)) + + r = self.vapi.cli_return_response("show trace") + self.assertTrue(r.retval == 0) + self.assertTrue(hasattr(r, 'reply')) + rv = r.reply + look_here = rv.find('ethernet-input') + self.assertFalse(look_here == -1) + bad_checksum_index = rv[look_here:].find('should be') + self.assertTrue(bad_checksum_index == -1) + +if __name__ == '__main__': + unittest.main(testRunner=VppTestRunner) diff --git a/pool/shard001/Python/0012614_SetJobLimit.py b/pool/shard001/Python/0012614_SetJobLimit.py new file mode 100644 index 0000000000000000000000000000000000000000..746d728365c6fa20aa947f2473094a385429e3fb --- /dev/null +++ b/pool/shard001/Python/0012614_SetJobLimit.py @@ -0,0 +1,37 @@ +############################################################### +# Imports +############################################################### +from Deadline.Events import * +from Deadline.Scripting import * + + +############################################################### +# This is the function called by Deadline to get an instance of the Draft event listener. +############################################################### +def GetDeadlineEventListener(): + return SetJobLimitListener() + + +def CleanupDeadlineEventListener(eventListener): + eventListener.Cleanup() + + +############################################################### +# The event listener class. +############################################################### +class SetJobLimitListener (DeadlineEventListener): + def __init__(self): + self.OnJobSubmittedCallback += self.OnJobSubmitted + + def Cleanup(self): + del self.OnJobSubmittedCallback + + def OnJobSubmitted(self, job): + limitNames = self.GetConfigEntry("JobLimits").split(',') + + for limitName in job.JobLimitGroups: + if limitName.lower() not in limitNames: + limitNames.append(limitName) + + job.SetJobLimitGroups(limitNames) + RepositoryUtils.SaveJob(job) diff --git a/pool/shard001/Python/0012615_lib.py b/pool/shard001/Python/0012615_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..149cb593b92f2a8e1b45242610f07d97cc74d631 --- /dev/null +++ b/pool/shard001/Python/0012615_lib.py @@ -0,0 +1,26 @@ +import array +from itertools import zip_longest + +def grouper(iterable, n, fillvalue=None): + '''Collect data into fixed-length chunks or blocks + + grouper([1,2,3,4,5], 2, 0) --> [1,2] [3,4] [5,0] + ''' + args = [iter(iterable)] * n + return zip_longest(*args, fillvalue=fillvalue) + +def arrayify(source_list): + dest_array = array.array('I') + dests_array = array.array('I') + j = 0 + for i in range(len(source_list)): + items = source_list[i] + dest_array.append(j) + dests_array.append(len(items)) + dests_array.extend(items) + j += 1 + len(items) + return (dest_array, dests_array) + +def make_inverse(mapping): return dict((y,x) for (x,y) in mapping.items()) +def make_array_inverse(arraylist): return dict((x,n) for (n,x) in enumerate(arraylist)) + diff --git a/pool/shard001/Python/0012627_torrent.py b/pool/shard001/Python/0012627_torrent.py new file mode 100644 index 0000000000000000000000000000000000000000..f6ee3602e5b97239d9363877a17dcf73d57ca738 --- /dev/null +++ b/pool/shard001/Python/0012627_torrent.py @@ -0,0 +1,169 @@ +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details +# http://www.gnu.org/licenses/gpl-3.0.txt + +from . import _mixin as mixin +from .. import CmdError +from ... import objects +from ...completion import candidates +from ..base import torrent as base +from ._table import TERMSIZE, print_table + +from ...logging import make_logger # isort:skip +log = make_logger(__name__) + + +class AddTorrentsCmd(base.AddTorrentsCmdbase, + mixin.make_request): + provides = {'cli'} + + @classmethod + def completion_candidates_posargs(cls, args): + """Complete positional arguments""" + # Use current working directory as base + return candidates.fs_path(args.curarg.before_cursor, + base='.', + glob=r'*.torrent') + + +class TorrentDetailsCmd(base.TorrentDetailsCmdbase, + mixin.make_request, mixin.select_torrents): + provides = {'cli'} + + async def display_details(self, torrent_id): + from ...views.details import SECTIONS + needed_keys = set(('name',)) + for _section in SECTIONS: + for _item in _section['items']: + needed_keys.update(_item.needed_keys) + + response = await self.make_request( + objects.srvapi.torrent.torrents((torrent_id,), keys=needed_keys), + quiet=True) + if not response.torrents: + raise CmdError() + else: + torrent = response.torrents[0] + + if TERMSIZE.columns is None: + self._machine_readable(torrent) + else: + self._human_readable(torrent) + + def _human_readable(self, torrent): + from ...views.details import SECTIONS + + label_width = max(len(item.label) + for section in SECTIONS + for item in section['items']) + + for i,section in enumerate(SECTIONS): + if i != 0: + print() # Newline between sections + print('\033[1m' + section['title'].upper() + '\033[0m') + for item in section['items']: + print(' %s: %s' % (item.label.rjust(label_width), item.human_readable(torrent))) + + def _machine_readable(self, torrent): + from ...views.details import SECTIONS + for section in SECTIONS: + for item in section['items']: + print('%s\t%s' % (item.label.lower(), item.machine_readable(torrent))) + + +class ListTorrentsCmd(base.ListTorrentsCmdbase, + mixin.make_request, mixin.select_torrents, + mixin.only_supported_columns): + provides = {'cli'} + + async def make_torrent_list(self, tfilter, sort, columns): + from ...views.torrent import COLUMNS as TORRENT_COLUMNS + + # Remove columns that aren't supported by CLI interface (e.g. 'marked') + columns = self.only_supported_columns(columns, TORRENT_COLUMNS) + + # Get needed keys + if tfilter is None: + keys = set(sort.needed_keys) + else: + keys = set(sort.needed_keys + tfilter.needed_keys) + + # Get wanted torrents and sort them + for colname in columns: + keys.update(TORRENT_COLUMNS[colname].needed_keys) + response = await self.make_request( + objects.srvapi.torrent.torrents(tfilter, keys=keys), + quiet=True) + torrents = sort.apply(response.torrents) + + # Show table of found torrents + if torrents: + print_table(torrents, columns, TORRENT_COLUMNS) + else: + raise CmdError() + + +class TorrentMagnetURICmd(base.TorrentMagnetURICmdbase, + mixin.select_torrents): + provides = {'cli'} + + def display_uris(self, uris): + for uri in uris: + print(uri) + + +class MoveTorrentsCmd(base.MoveTorrentsCmdbase, + mixin.make_request, mixin.select_torrents): + provides = {'cli'} + + @classmethod + async def completion_candidates_posargs(cls, args): + """Complete positional arguments""" + if args.curarg_index == 1: + log.debug('Getting torrent filter candidates from %r', candidates.torrent_filter) + return await candidates.torrent_filter(args.curarg) + elif args.curarg_index == 2: + return candidates.fs_path(args.curarg.before_cursor, + base=objects.cfg['srv.path.complete'], + directories_only=True) + + +class RemoveTorrentsCmd(base.RemoveTorrentsCmdbase, + mixin.make_request, mixin.select_torrents, mixin.ask_yes_no): + provides = {'cli'} + + async def show_list_of_hits(self, tfilter): + import sys + if sys.stdout.isatty(): + cmd = 'ls --sort name %s' % tfilter + await objects.cmdmgr.run_async(cmd) + + def remove_list_of_hits(self): + pass + + +class RenameCmd(base.RenameCmdbase, + mixin.make_request, mixin.select_torrents, mixin.select_files): + provides = {'cli'} + + +class StartTorrentsCmd(base.StartTorrentsCmdbase, + mixin.make_request, mixin.select_torrents): + provides = {'cli'} + + +class StopTorrentsCmd(base.StopTorrentsCmdbase, + mixin.make_request, mixin.select_torrents): + provides = {'cli'} + + +class VerifyTorrentsCmd(base.VerifyTorrentsCmdbase, + mixin.make_request, mixin.select_torrents): + provides = {'cli'} diff --git a/pool/shard001/Python/0012628_border_overaly.py b/pool/shard001/Python/0012628_border_overaly.py new file mode 100644 index 0000000000000000000000000000000000000000..67cd15af9988999db11f1c31fccadf89162e8f94 --- /dev/null +++ b/pool/shard001/Python/0012628_border_overaly.py @@ -0,0 +1,41 @@ +# =============================================================================== +# Copyright 2011 Jake Ross +# +# 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. +# =============================================================================== + + +# ============= enthought library imports ======================= +from __future__ import absolute_import +from chaco.api import AbstractOverlay + + +# ============= standard library imports ======================== + +# ============= local library imports ========================== + + +class BorderOverlay(AbstractOverlay): + def overlay(self, component, gc, view_bounds=None, mode="normal"): + """ """ + # print component.outer_bounds, component.outer_position + gc.set_stroke_color((0, 1, 0)) + x, y = component.outer_position + w, h = component.outer_bounds + gc.rect(x - 3, y - 3, w + 6, h + 6) + + gc.stroke_path() + + +# ============= views =================================== +# ============= EOF ==================================== diff --git a/pool/shard001/Python/0012635_users.py b/pool/shard001/Python/0012635_users.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d6d70e4b902b396285811fb41b8da45dfc70e3 --- /dev/null +++ b/pool/shard001/Python/0012635_users.py @@ -0,0 +1,172 @@ +# Views related to Users, Auth & UserProfiles +# +# This file is part of thesubnetwork +# (parts of the file based on my.gpodder.org) +# +# thesubnetwork is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# thesubnetwork is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +# License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with thesubnetwork. If not, see . +# + +from django.shortcuts import render_to_response +from django.http import HttpResponseRedirect +from django.contrib.auth import authenticate, login +from django.contrib.auth.models import User +from django.contrib.auth.decorators import login_required +from django.template.defaultfilters import slugify +from django.template import RequestContext +from thesubnetwork.users.models import UserProfile +from thesubnetwork.web.forms import RestorePasswordForm +from django.contrib.sites.models import Site +from django.conf import settings +from thesubnetwork.decorators import manual_gc, allowed_methods +from django.utils.translation import ugettext as _ +from registration.models import RegistrationProfile +import string +import random + + +from thesubnetwork.web.forms import ResendActivationForm + +def login_user(request): + # Do not show login page for already-logged-in users + if request.user.is_authenticated(): + return HttpResponseRedirect("/") + + if 'user' not in request.POST or 'pwd' not in request.POST: + if request.GET.get('restore_password', False): + form = RestorePasswordForm() + else: + form = None + + return render_to_response('login.html', { + 'url': Site.objects.get_current(), + 'next': request.GET.get('next', ''), + 'restore_password_form': form, + }, context_instance=RequestContext(request)) + + username = request.POST['user'] + password = request.POST['pwd'] + user = authenticate(username=username, password=password) + + if user is None: + return render_to_response('login.html', { + 'error_message': _('Wrong username or password.'), + 'next': request.POST.get('next', ''), + }, context_instance=RequestContext(request)) + + if not user.is_active: + + p = UserProfile.objects.get_or_create(user=user) + + if p.deleted: + return render_to_response('login.html', { + 'error_message': _('You have deleted your account, but you can register again') + }, context_instance=RequestContext(request)) + + else: + return render_to_response('login.html', { + 'error_message': _('Please activate your account first.'), + 'activation_needed': True, + }, context_instance=RequestContext(request)) + + login(request, user) + + if 'next' in request.POST and request.POST['next'] and request.POST['next'] != '/login/': + return HttpResponseRedirect(request.POST['next']) + + return HttpResponseRedirect("/") + +def get_user(username, email): + if username: + return User.objects.get(username=username) + elif email: + return User.objects.get(email=email) + else: + raise User.DoesNotExist('neither username nor email provided') + +@allowed_methods(['POST']) +def restore_password(request): + form = RestorePasswordForm(request.POST) + if not form.is_valid(): + return HttpResponseRedirect('/login/') + + try: + user = get_user(form.cleaned_data['username'], form.cleaned_data['email']) + + except User.DoesNotExist: + error_message = _('User does not exist.') + return render_to_response('password_reset_failed.html', { + 'error_message': error_message + }, context_instance=RequestContext(request)) + + site = Site.objects.get_current() + pwd = "".join(random.sample(string.letters + string.digits, 8)) + subject = _('Reset password for your account on %s') % site + message = _('Here is your new password for your account %(username)s on %(site)s: %(password)s') % {'username': user.username, 'site': site, 'password': pwd} + user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) + user.set_password(pwd) + user.save() + return render_to_response('password_reset.html', context_instance=RequestContext(request)) + + +@manual_gc +@allowed_methods(['GET', 'POST']) +def resend_activation(request): + + if request.method == 'GET': + form = ResendActivationForm() + return render_to_response('registration/resend_activation.html', { + 'form': form, + }, context_instance=RequestContext(request)) + + site = Site.objects.get_current() + form = ResendActivationForm(request.POST) + + try: + if not form.is_valid(): + raise ValueError(_('Invalid Username entered')) + + try: + user = get_user(form.cleaned_data['username'], form.cleaned_data['email']) + except User.DoesNotExist: + raise ValueError(_('User does not exist.')) + + p = UserProfile.objects.get_or_create(user=user) + if p.deleted: + raise ValueError(_('You have deleted your account, but you can regster again.')) + + try: + profile = RegistrationProfile.objects.get(user=user) + except RegistrationProfile.DoesNotExist: + profile = RegistrationProfile.objects.create_profile(user) + + if profile.activation_key == RegistrationProfile.ACTIVATED: + user.is_active = True + user.save() + raise ValueError(_('Your account already has been activated. Go ahead and log in.')) + + elif profile.activation_key_expired(): + raise ValueError(_('Your activation key has expired. Please try another username, or retry with the same one tomorrow.')) + + except ValueError, e: + return render_to_response('registration/resend_activation.html', { + 'form': form, + 'error_message' : e + }, context_instance=RequestContext(request)) + + + + profile.send_activation_email(site) + + return render_to_response('registration/resent_activation.html', context_instance=RequestContext(request)) + diff --git a/pool/shard001/Python/0012645_main.py b/pool/shard001/Python/0012645_main.py new file mode 100644 index 0000000000000000000000000000000000000000..c875707e4acde48e42c9c10ac8bcf2f3b655d459 --- /dev/null +++ b/pool/shard001/Python/0012645_main.py @@ -0,0 +1,68 @@ +# Copyright 2021 Google LLC +# +# 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. + +"""Prediction server that uses a trained policy to give predicted actions.""" +import os + +from fastapi import FastAPI +from fastapi import Request + +import tensorflow as tf +import tf_agents + + +app = FastAPI() +_model = tf.compat.v2.saved_model.load(os.environ["AIP_STORAGE_URI"]) + + +@app.get(os.environ["AIP_HEALTH_ROUTE"], status_code=200) +def health(): + """Handles server health check requests. + + Returns: + An empty dict. + """ + return {} + + +@app.post(os.environ["AIP_PREDICT_ROUTE"]) +async def predict(request: Request): + """Handles prediction requests. + + Unpacks observations in prediction requests and queries the trained policy for + predicted actions. + + Args: + request: Incoming prediction requests that contain observations. + + Returns: + A dict with the key `predictions` mapping to a list of predicted actions + corresponding to each observation in the prediction request. + """ + body = await request.json() + instances = body["instances"] + + predictions = [] + for index, instance in enumerate(instances): + # Unpack request body and reconstruct TimeStep. Rewards default to 0. + batch_size = len(instance["observation"]) + time_step = tf_agents.trajectories.restart( + observation=instance["observation"], + batch_size=tf.convert_to_tensor([batch_size])) + policy_step = _model.action(time_step) + + predictions.append( + {f"PolicyStep {index}": policy_step.action.numpy().tolist()}) + + return {"predictions": predictions} diff --git a/pool/shard001/Python/0012647_genicon.py b/pool/shard001/Python/0012647_genicon.py new file mode 100644 index 0000000000000000000000000000000000000000..543735240fea9542c7931c4a99dd978e85b8fa63 --- /dev/null +++ b/pool/shard001/Python/0012647_genicon.py @@ -0,0 +1,31 @@ +#!@PYTHON@ +import os +import sys +import tempfile + +base = os.path.splitext (os.path.split (sys.argv[1])[1])[0] +input = os.path.abspath (sys.argv[1]) +output = os.path.abspath (sys.argv[2]) +program_name= os.path.split (sys.argv[0])[1] + +dir = tempfile.mktemp (program_name) +os.mkdir (dir, 0777) +os.chdir(dir) + +def system (c): + print c + if os.system (c): + raise 'barf' + +outputs = [] +for sz in [48,32,16] : + + for depth in [24,8]: + out = '%(base)s-%(sz)d-%(depth)d.png' % locals() + system ('convert -depth %(depth)d -sample %(sz)d %(input)s %(out)s' % + locals ()) + outputs.append (out) + +system('icotool --output %s --create %s' % (output, ' '.join (outputs))) +system('rm -rf %(dir)s' % locals()) + diff --git a/pool/shard001/Python/0012651_tinypng.py b/pool/shard001/Python/0012651_tinypng.py new file mode 100644 index 0000000000000000000000000000000000000000..2a114c0a05b590b65e4853c80f9375a0afeb6ec4 --- /dev/null +++ b/pool/shard001/Python/0012651_tinypng.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +from os.path import dirname +from urllib.request import Request, urlopen +from base64 import b64encode +import sys + +key = "3lHn_dVjmmU_PqoGiQblVCyvtiXbWCQB" +input = sys.argv[1] +output = sys.argv[1] + "-tiny.png" + +request = Request("https://api.tinypng.com/shrink", open(input, "rb").read()) + +cafile = None +# Uncomment below if you have trouble validating our SSL certificate. +# Download cacert.pem from: http://curl.haxx.se/ca/cacert.pem +# cafile = dirname(__file__) + "/cacert.pem" + +auth = b64encode(bytes("api:" + key, "ascii")).decode("ascii") +request.add_header("Authorization", "Basic %s" % auth) + +response = urlopen(request, cafile = cafile) +if response.status == 201: + # Compression was successful, retrieve output from Location header. + result = urlopen(response.getheader("Location"), cafile = cafile).read() + open(output, "wb").write(result) +else: + # Something went wrong! You can parse the JSON body for details. + print("Compression failed") + diff --git a/pool/shard001/Python/0012652_retry_http.py b/pool/shard001/Python/0012652_retry_http.py new file mode 100644 index 0000000000000000000000000000000000000000..7d8fd4385360a0ce977e30809efff4513aedd97e --- /dev/null +++ b/pool/shard001/Python/0012652_retry_http.py @@ -0,0 +1,97 @@ +# Copyright 2014-2015 Zuercher Hochschule fuer Angewandte Wissenschaften +# 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. + +__author__ = 'andy' + +import requests +from retrying import retry + +from config import CONFIG +from log import LOG + + +WAIT = CONFIG.get('cloud_controller', 'wait_time', 2000) +ATTEMPTS = CONFIG.get('cloud_controller', 'max_attempts', 5) + + +def retry_if_http_error(exception): + """ + Defines which type of exceptions allow for a retry of the request + + :param exception: the raised exception + :return: True if retrying the request is possible + """ + error = False + if isinstance(exception, requests.HTTPError): + if exception.response.status_code == 503: + LOG.info('Requesting retry: response code: ' + str(exception.response.status_code)) + LOG.error('Exception: ' + exception.__repr__()) + error = True + elif isinstance(exception, requests.ConnectionError): + LOG.info('Requesting retry: ConnectionError') + LOG.error('Exception: ' + exception.__repr__()) + error = True + return error + + +@retry(retry_on_exception=retry_if_http_error, wait_fixed=WAIT, stop_max_attempt_number=ATTEMPTS) +def http_retriable_request(verb, url, headers={}, authenticate=False, params={}): + """ + Sends an HTTP request, with automatic retrying in case of HTTP Errors 500 or ConnectionErrors + _http_retriable_request('POST', 'http://cc.cloudcomplab.ch:8888/app/', headers={'Content-Type': 'text/occi', [...]} + , authenticate=True) + :param verb: [POST|PUT|GET|DELETE] HTTP keyword + :param url: The URL to use. + :param headers: Headers of the request + :param kwargs: May contain authenticate=True parameter, which is used to make requests requiring authentication, + e.g. CC requests + :return: result of the request + """ + LOG.debug(verb + ' on ' + url + ' with headers ' + headers.__repr__()) + + auth = () + if authenticate: + user = CONFIG.get('cloud_controller', 'user') + pwd = CONFIG.get('cloud_controller', 'pwd') + auth = (user, pwd) + + if verb in ['POST', 'DELETE', 'GET', 'PUT']: + try: + r = None + if verb == 'POST': + if authenticate: + r = requests.post(url, headers=headers, auth=auth, params=params) + else: + r = requests.post(url, headers=headers, params=params) + elif verb == 'DELETE': + if authenticate: + r = requests.delete(url, headers=headers, auth=auth, params=params) + else: + r = requests.delete(url, headers=headers, params=params) + elif verb == 'GET': + if authenticate: + r = requests.get(url, headers=headers, auth=auth, params=params) + else: + r = requests.get(url, headers=headers, params=params) + elif verb == 'PUT': + if authenticate: + r = requests.put(url, headers=headers, auth=auth, params=params) + else: + r = requests.put(url, headers=headers, params=params) + r.raise_for_status() + return r + except requests.HTTPError as err: + LOG.error('HTTP Error: should do something more here!' + err.message) + raise err \ No newline at end of file diff --git a/pool/shard001/Python/0012654_parse_timings.py b/pool/shard001/Python/0012654_parse_timings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2661c4762360009d8dd1d26b58e96a2fcc877e --- /dev/null +++ b/pool/shard001/Python/0012654_parse_timings.py @@ -0,0 +1,69 @@ +import sys +import os +import math + +def createTableHeader(methods): + #print "\\begin{table}[ht!]" + #print "\\caption{XXX}" + #print "\\label{tab:runtimes}" + #print "\\centering" + print "\\begin{tabular}{l c r r r }" + print "\\toprule" + print "File & {} \\\\ ".format( " & ".join(methods) ) + print "\\midrule" + +def convertToTime(sec): + if sec == None: + t1_s = "XXX" + else: + h = int(sec) / 3600 + t1_s = "{}h".format(h) if h > 0 else "" + m = (int(sec) - h * 3600) / 60 + t1_s += "{}m".format(m) if m > 0 else "00" + sec = int(math.ceil(sec - h * 3600 - m * 60)) + t1_s += "{}s".format(sec) + return t1_s + +def createTableRow(file, t1, t2, t3): + t1_s = convertToTime(t1) + t2_s = convertToTime(t2) + t3_s = convertToTime(t3) + print "{} & {} & {} & {} \\\\".format(file, t1_s, t2_s, t3_s) + +def createTableFooter(): + print "\\bottomrule" + print "\\end{tabular}" + print "\\end{table}" + +def parseLogForTime(log_path): + if not os.path.isfile(log_path): + # print "Can't find log", log_path + return None + with open(log_path, "r") as f: + for line in f: + if "Elapsed (wall clock)" in line: + t = line.strip().split()[-1] + time_parts = t.split(":") + sec = 0 + for p in time_parts[:-1]: + sec = sec * 60 + int(p) * 60 + sec += float(time_parts[-1]) + return sec + return None + +FILES=["SRR445718", "SRR1294122", "P_aeruginosa_PAO1", "K562_cytosol_LID8465_TopHat_v2", "NA12878_S1"] +methods=["Referee","Deez","Quip -r"] +DIR = sys.argv[1] +createTableHeader(methods) +for file in FILES: + ref_log = DIR + "/" + file + ".comp.log" + deez_log = DIR + "/" + file + ".dz_comp.log" + quip_log = DIR + "/" + file + ".quip.log" + + ref_time = parseLogForTime(ref_log) + deez_time = parseLogForTime(deez_log) + quip_time = parseLogForTime(quip_log) + + createTableRow(file, ref_time, deez_time, quip_time) + +createTableFooter() diff --git a/pool/shard001/Python/0012655_init__.py b/pool/shard001/Python/0012655_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb250218098eac30f84d98d343007d6cfde95f57 --- /dev/null +++ b/pool/shard001/Python/0012655_init__.py @@ -0,0 +1,91 @@ +from .availability_zones import AvailabilityZonesV2 +from .extensions import ExtensionsV2, ExtensionV2 +from .extra_specs import ExtraSpecsFlavorV2 +from .dns import DNSDomainsV2, DNSDomainEntryV2 +from .flavors import FlavorV2, FlavorsV2, FlavorsDetailV2 +from .floating_ips import OSFloatingIpsV2 +from .keypairs import KeypairsV2, KeypairV2 +from .limits import LimitsV2 +from .quota_sets import OSQuotaSetsV2 +from .servers import ServerV2, ServersV2, ServersDetailV2, ServerActionV2 +from .server_ips import ServerIpsV2, ServerIpsNetworkV2 +from .security_groups import OSSecurityGroupsV2 +from .usage import UsageV2 +from .volumes import OSVolumeAttachmentsV2 +from .networks import OSNetworksV2, OSNetworkV2 +from .instance_actions import InstanceActionsV2, InstanceActionV2 +from .index import IndexV2 + +from jumpgate.image.drivers.sl import ImageV1, ImagesV2 + +from jumpgate.common.sl import add_hooks + + +def setup_routes(app, disp): + # V3 Routes + # None currently supported + + # V2 Routes + disp.set_handler('index', IndexV2(app)) + disp.set_handler('v2_index', IndexV2(app)) + + flavor = FlavorV2(app) + flavors = FlavorsV2(app) + flavors_detail = FlavorsDetailV2(app) + + disp.set_handler('v2_availability_zone', AvailabilityZonesV2()) + disp.set_handler('v2_availability_zone_detail', AvailabilityZonesV2()) + + disp.set_handler('v2_extensions', ExtensionsV2()) + disp.set_handler('v2_extension', ExtensionV2()) + + disp.set_handler('v2_os_extra_specs_flavor', ExtraSpecsFlavorV2()) + + disp.set_handler('v2_flavor', flavor) + disp.set_handler('v2_flavors', flavors) + disp.set_handler('v2_flavors_detail', flavors_detail) + + disp.set_handler('v2_os_floating_ip_dns', DNSDomainsV2()) + disp.set_handler('v2_os_floating_ip_dns_domain_entry', DNSDomainEntryV2()) + + disp.set_handler('v2_limits', LimitsV2()) + + disp.set_handler('v2_os_floating_ips', OSFloatingIpsV2()) + + disp.set_handler('v2_os_tenant_networks', OSNetworksV2()) + disp.set_handler('v2_os_tenant_network', OSNetworkV2()) + disp.set_handler('v2_os_networks', OSNetworksV2()) + disp.set_handler('v2_os_network', OSNetworkV2()) + + disp.set_handler('v2_os_keypair', KeypairV2()) + disp.set_handler('v2_os_keypairs', KeypairsV2()) + + disp.set_handler('v2_os_quota_sets', OSQuotaSetsV2()) + disp.set_handler('v2_os_tenant_quota_sets', OSQuotaSetsV2()) + + disp.set_handler('v2_os_server_security_groups', OSSecurityGroupsV2()) + disp.set_handler('v2_os_security_groups', OSSecurityGroupsV2()) + + disp.set_handler('v2_os_volume_attachments', OSVolumeAttachmentsV2()) + + disp.set_handler('v2_server', ServerV2(app)) + disp.set_handler('v2_servers', ServersV2(app)) + disp.set_handler('v2_servers_detail', ServersDetailV2(app)) + disp.set_handler('v2_server_action', ServerActionV2(app)) + disp.set_handler('v2_os_instance_actions', InstanceActionsV2()) + disp.set_handler('v2_os_instance_action', InstanceActionV2()) + + disp.set_handler('v2_server_ips', ServerIpsV2()) + disp.set_handler('v2_server_ips_network', ServerIpsNetworkV2()) + + disp.set_handler('v2_tenant_flavor', flavor) + disp.set_handler('v2_tenant_flavors', flavors) + disp.set_handler('v2_tenant_flavors_detail', flavors_detail) + + disp.set_handler('v2_tenant_usage', UsageV2()) + + disp.set_handler('v2_image', ImageV1(app)) + disp.set_handler('v2_images', ImagesV2(app)) + disp.set_handler('v2_images_detail', ImagesV2(app)) + + add_hooks(app) diff --git a/pool/shard001/Python/0012658_query_results.py b/pool/shard001/Python/0012658_query_results.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0e09e4bb8c96b273a487a5c2bd49ddd106f803 --- /dev/null +++ b/pool/shard001/Python/0012658_query_results.py @@ -0,0 +1,167 @@ +import json +import logging +import numbers +import re +import sqlite3 + +from dateutil import parser + +from redash import models +from redash.permissions import has_access, not_view_only +from redash.query_runner import (TYPE_BOOLEAN, TYPE_DATETIME, TYPE_FLOAT, + TYPE_INTEGER, TYPE_STRING, BaseQueryRunner, + register) +from redash.utils import JSONEncoder + +logger = logging.getLogger(__name__) + + +class PermissionError(Exception): + pass + + +def _guess_type(value): + if value == '' or value is None: + return TYPE_STRING + + if isinstance(value, numbers.Integral): + return TYPE_INTEGER + + if isinstance(value, float): + return TYPE_FLOAT + + if unicode(value).lower() in ('true', 'false'): + return TYPE_BOOLEAN + + try: + parser.parse(value) + return TYPE_DATETIME + except (ValueError, OverflowError): + pass + + return TYPE_STRING + + +def extract_query_ids(query): + queries = re.findall(r'(?:join|from)\s+query_(\d+)', query, re.IGNORECASE) + return [int(q) for q in queries] + + +def _load_query(user, query_id): + query = models.Query.get_by_id(query_id) + + if user.org_id != query.org_id: + raise PermissionError("Query id {} not found.".format(query.id)) + + if not has_access(query.data_source.groups, user, not_view_only): + raise PermissionError(u"You are not allowed to execute queries on {} data source (used for query id {}).".format( + query.data_source.name, query.id)) + + return query + + +def create_tables_from_query_ids(user, connection, query_ids): + for query_id in set(query_ids): + query = _load_query(user, query_id) + + results, error = query.data_source.query_runner.run_query( + query.query_text, user) + + if error: + raise Exception( + "Failed loading results for query id {}.".format(query.id)) + + results = json.loads(results) + table_name = 'query_{query_id}'.format(query_id=query_id) + create_table(connection, table_name, results) + + +def fix_column_name(name): + return name.replace(':', '_').replace('.', '_').replace(' ', '_') + + +def create_table(connection, table_name, query_results): + columns = [column['name'] + for column in query_results['columns']] + safe_columns = [fix_column_name(column) for column in columns] + + column_list = ", ".join(safe_columns) + create_table = u"CREATE TABLE {table_name} ({column_list})".format( + table_name=table_name, column_list=column_list) + logger.debug("CREATE TABLE query: %s", create_table) + connection.execute(create_table) + + insert_template = u"insert into {table_name} ({column_list}) values ({place_holders})".format( + table_name=table_name, + column_list=column_list, + place_holders=','.join(['?'] * len(columns))) + + for row in query_results['rows']: + values = [row.get(column) for column in columns] + connection.execute(insert_template, values) + + +class Results(BaseQueryRunner): + noop_query = 'SELECT 1' + + @classmethod + def configuration_schema(cls): + return { + "type": "object", + "properties": { + } + } + + @classmethod + def annotate_query(cls): + return False + + @classmethod + def name(cls): + return "Query Results (Beta)" + + def run_query(self, query, user): + connection = sqlite3.connect(':memory:') + + query_ids = extract_query_ids(query) + create_tables_from_query_ids(user, connection, query_ids) + + cursor = connection.cursor() + + try: + cursor.execute(query) + + if cursor.description is not None: + columns = self.fetch_columns( + [(i[0], None) for i in cursor.description]) + + rows = [] + column_names = [c['name'] for c in columns] + + for i, row in enumerate(cursor): + for j, col in enumerate(row): + guess = _guess_type(col) + + if columns[j]['type'] is None: + columns[j]['type'] = guess + elif columns[j]['type'] != guess: + columns[j]['type'] = TYPE_STRING + + rows.append(dict(zip(column_names, row))) + + data = {'columns': columns, 'rows': rows} + error = None + json_data = json.dumps(data, cls=JSONEncoder) + else: + error = 'Query completed but it returned no data.' + json_data = None + except KeyboardInterrupt: + connection.cancel() + error = "Query cancelled by user." + json_data = None + finally: + connection.close() + return json_data, error + + +register(Results) diff --git a/pool/shard001/Python/0012665_requests.py b/pool/shard001/Python/0012665_requests.py new file mode 100644 index 0000000000000000000000000000000000000000..0e655d2775984599527bbbff3928d37beaa01186 --- /dev/null +++ b/pool/shard001/Python/0012665_requests.py @@ -0,0 +1,111 @@ +import enum +import datetime + + +@enum.unique +class Status(enum.IntEnum): + PENDING = 0 + INVALID = enum.auto() + FRESH = enum.auto() + DONE = enum.auto() + + +# TODO: +# - filter results by status +# - create a result for every submitted request +# - handle results assignment for requests that have pending results - delete pending results that become obsolete + +class Request(object): + def __init__(self, person_id, request_id=None): + self.person_id = person_id + self.id = request_id + + def __hash__(self): + return hash((self.id, self.person_id)) + + +class IWantRequest(Request): + def __init__(self, person_id, activity, deadline, + activity_start, activity_duration_seconds): + super().__init__(person_id) + self.activity = activity + + self.deadline = deadline + self.activity_start = activity_start + self.activity_duration = activity_duration_seconds + + self.resolved_by = None + + def __hash__(self): + return hash((super().__hash__(), + self.activity, self.deadline, + self.activity_start, self.activity_duration)) + + def __eq__(self, rhs): + result = True + # If two requests differ just by having different resolved_by + # result ID, they are still the same requests. + if ( + False + or self.id != rhs.id + or self.person_id != rhs.person_id + or self.activity != rhs.activity + or self.deadline != rhs.deadline + or self.activity_start != rhs.activity_start + or self.activity_duration != rhs.activity_duration + ): + result = False + return result + + @property + def activity_end(self): + return self.activity_start + datetime.timedelta(seconds=self.activity_duration) + + def is_active_now(self): + return self.is_active_by(datetime.datetime.today()) + + def is_active_by(self, by_the_time): + return by_the_time < self.deadline + + def overlaps_with(self, other_request): + overlaps = (self.activity_end > other_request.activity_start + and self.activity_start < other_request.activity_end) + return overlaps + + # TODO: Find a more descriptive name + def conflicts_with(self, other_request): + overlaps = self.overlaps_with(other_request) + conflicts = (self is not other_request + and self.person_id == other_request.person_id + and overlaps) + return conflicts + + +class CancellationRequest(Request): + def __init__(self, person_id, cancelling_request_id): + super().__init__(person_id) + self.cancelling_request_id = cancelling_request_id + + +class Result(object): + def __init__(self, uid, requests_ids: set, deadline: datetime.datetime): + self.id = uid + self.requests_ids = requests_ids + self.deadline = deadline + self.status = Status.PENDING + + def __hash__(self): + return hash((super().__hash__(), + self.id, frozenset(self.requests_ids), + self.deadline)) + + def __eq__(self, rhs): + result = True + if ( + False + or self.id != rhs.id + or self.requests_ids != rhs.requests_ids + or self.deadline != rhs.deadline + ): + result = False + return result diff --git a/pool/shard001/Python/0012671_faucet_event.py b/pool/shard001/Python/0012671_faucet_event.py new file mode 100644 index 0000000000000000000000000000000000000000..0072073782140d65a8a07ed275617dfcb43b7e94 --- /dev/null +++ b/pool/shard001/Python/0012671_faucet_event.py @@ -0,0 +1,139 @@ +"""FAUCET event notification.""" + +# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. +# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. +# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. +# Copyright (C) 2015--2019 The Contributors +# +# 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 json +import os +import socket +import time +from contextlib import contextmanager + +import eventlet + +from os_ken.lib import hub +from os_ken.lib.hub import StreamServer + + +class NonBlockLock: + """Non blocking lock that can be used as a context manager.""" + + def __init__(self): + self._lock = eventlet.semaphore.Semaphore() + + @contextmanager + def acquire_nonblock(self): + """Attempt to acquire a lock.""" + result = self._lock.acquire(blocking=False) + yield result + if result: + self.release() + + def release(self): + """Release lock when done.""" + self._lock.release() + + +class FaucetEventNotifier: + """Event notification, via Unix domain socket.""" + + def __init__(self, socket_path, metrics, logger): + self.logger = logger + self.socket_path = self.check_path(socket_path) + self.metrics = metrics + self.event_id = 0 + self.thread = None + self.lock = NonBlockLock() + self.event_q = eventlet.queue.Queue(120) + + def start(self): + """Start socket server.""" + if self.socket_path: + stream_server = StreamServer((self.socket_path, None), self._loop).serve_forever + self.thread = hub.spawn(stream_server) + self.thread.name = 'event' + return self.thread + + def _loop(self, sock, _addr): + """Serve events.""" + with self.lock.acquire_nonblock() as result: + if not result: + self.logger.info('multiple event clients not supported') + else: + self.logger.info('event client connected') + while True: + event = self.event_q.get() + event_bytes = bytes( + '\n'.join((json.dumps(event, default=str), '')).encode('UTF-8')) + try: + sock.sendall(event_bytes) + except (socket.error, IOError) as err: + self.logger.info('event client disconnected: %s', err) + break + try: + sock.close() + except (socket.error, IOError): + pass + + def get_event(self): + assert self.thread is None, 'not allowed with async _loop' + return None if self.event_q.empty() else self.event_q.get() + + def notify(self, dp_id, dp_name, event_dict): + """Notify of an event.""" + assert isinstance(event_dict, dict) + self.event_id += 1 + event = { + 'version': 1, + 'time': time.time(), + 'dp_id': dp_id, + 'dp_name': dp_name, + 'event_id': self.event_id, + } + for header_key in list(event): + assert header_key not in event_dict + event.update(event_dict) + self.metrics.faucet_event_id.set(event['event_id']) + if self.event_q.full(): + self.event_q.get() + self.event_q.put(event) + + def check_path(self, socket_path): + """Check that socket_path is valid.""" + if not socket_path: + return None + socket_path = os.path.abspath(socket_path) + socket_dir = os.path.dirname(socket_path) + # Create parent directories that don't exist. + if not os.path.exists(socket_dir): + try: + os.makedirs(socket_dir) + except (PermissionError) as err: # pytype: disable=name-error + self.logger.error('Unable to create event socket directory: %s', err) + return None + # Check directory permissions. + if not os.access(socket_dir, os.R_OK | os.W_OK | os.X_OK): + self.logger.error('Incorrect permissions set on socket directory %s', socket_dir) + return None + # Remove stale socket file. + if os.path.exists(socket_path): + try: + os.remove(socket_path) + except (PermissionError) as err: # pytype: disable=name-error + self.logger.error('Unable to remove old socket: %s', err) + return None + return socket_path diff --git a/pool/shard001/Python/0012672_pyunit_colname_set_basic.py b/pool/shard001/Python/0012672_pyunit_colname_set_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1402a0e6c6e52859617ae615af01103abbe927 --- /dev/null +++ b/pool/shard001/Python/0012672_pyunit_colname_set_basic.py @@ -0,0 +1,22 @@ +import sys +sys.path.insert(1, "../../") +import h2o + +def colname_set_basic(ip,port): + + + + print "Uploading iris data..." + + no_headers = h2o.upload_file(h2o.locate("smalldata/iris/iris.csv")) + headers_and = h2o.upload_file(h2o.locate("smalldata/iris/iris_header.csv")) + + print no_headers.names() + print headers_and.names() + + no_headers.setNames(headers_and.names()) + assert no_headers.names() == headers_and.names(), "Expected the same column names but got {0} and {1}".\ + format(no_headers.names(), headers_and.names()) + +if __name__ == "__main__": + h2o.run_test(sys.argv, colname_set_basic) diff --git a/pool/shard001/Python/0012674_test_example2.py b/pool/shard001/Python/0012674_test_example2.py new file mode 100644 index 0000000000000000000000000000000000000000..26c6032e81529d70d5bf3f74fe4f3ff813549493 --- /dev/null +++ b/pool/shard001/Python/0012674_test_example2.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +import os +import subprocess +from unittest import TestCase +from boutiques import __file__ as bfile +import boutiques as bosh + + +class TestExample2(TestCase): + + def get_examples_dir(self): + return os.path.join(os.path.dirname(bfile), + "schema", "examples") + + def test_example2_no_exec(self): + example2_dir = os.path.join(self.get_examples_dir(), "example2") + ret = bosh.execute("simulate", + os.path.join(example2_dir, + "example2.json"), + "-i", + os.path.join(example2_dir, + "invocation.json")) + assert(ret.stdout != "" + and ret.stderr == "" + and ret.exit_code == 0 + and ret.error_message == "") + + def test_example2_exec(self): + example2_dir = os.path.join(self.get_examples_dir(), "example2") + ret = bosh.execute("launch", + os.path.join(example2_dir, "example2.json"), + os.path.join(example2_dir, "invocation.json")) + print(ret) + assert(ret.stdout == "" + and ret.stderr == "" + and ret.exit_code == 0 + and ret.error_message == "") + + ret = bosh.execute("launch", + os.path.join(example2_dir, "example2.json"), + "-x", + os.path.join(example2_dir, "invocation.json")) + print(ret) + assert(ret.stdout == "" + and ret.stderr == "" + and ret.exit_code == 0 + and ret.error_message == "") + + def test_example2_no_exec_random(self): + example2_dir = os.path.join(self.get_examples_dir(), "example2") + self.assertFalse(bosh.execute("simulate", + os.path.join(example2_dir, + "example2.json")).exit_code) diff --git a/pool/shard001/Python/0012676_ping.py b/pool/shard001/Python/0012676_ping.py new file mode 100644 index 0000000000000000000000000000000000000000..36fbfe9ca9c1bde9fd75ba2948324b18333d6bbe --- /dev/null +++ b/pool/shard001/Python/0012676_ping.py @@ -0,0 +1,16 @@ +def read_file(ipfile): + with open(ipfile, 'r') as fd: + lines = fd.readlines() + ips = [] + for line in lines: + ips.append(line.strip()) + return ips + +def ping(): + return '' + +def main(): + print 'derp' + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0012678_models.py b/pool/shard001/Python/0012678_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a82afe77d9b7c3f1b2dc62633c8d24c5de5162a --- /dev/null +++ b/pool/shard001/Python/0012678_models.py @@ -0,0 +1,79 @@ +from django.db import models + + +class Game(models.Model): + BOARD_GAME = 'B' + RPG = 'R' + TYPE_CHOICES = ((BOARD_GAME, 'Board game'), (RPG, 'Role-playing game')) + geek_id = models.IntegerField(null=True) + name = models.CharField(max_length=255) + type = models.CharField(max_length=1, choices=TYPE_CHOICES, + default=BOARD_GAME) + + def geek_url(self): + if not self.geek_id: + return None + if self.type == self.RPG: + return "https://rpggeek.com/rpgitem/" + str(self.geek_id) + else: + return "https://boardgamegeek.com/boardgame/" + str(self.geek_id) + + + def __str__(self): + return self.name + + +class Variant(models.Model): + game = models.ForeignKey(Game, on_delete=models.DO_NOTHING) + description = models.CharField(max_length=255) + + def __str__(self): + return str((self.game, self.description)) + + +class Faction(models.Model): + game = models.ForeignKey(Game, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=255) + + def __str__(self): + return str((self.game, self.name)) + + +class Play(models.Model): + game = models.ForeignKey(Game, on_delete=models.DO_NOTHING) + minutes = models.IntegerField(null=True, blank=True) + date = models.DateField(null=True, blank=True) + virtual = models.BooleanField(default=False) + variant = models.ForeignKey(Variant, null=True, blank=True, + on_delete=models.DO_NOTHING) + comments = models.CharField(null=True, blank=True, max_length=255) + + def __str__(self): + return str((self.id, self.game, self.date)) + + +class Player(models.Model): + MALE = 'M' + FEMALE = 'F' + OTHER = 'O' + GENDER_CHOICES = ( + (MALE, 'Male'), + (FEMALE, 'Female'), + (OTHER, 'Other')) + name = models.CharField(max_length=255) + birth_date = models.DateField(null=True, blank=True) + gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) + + def __str__(self): + return self.name + + +class Team(models.Model): + play = models.ForeignKey(Play, on_delete=models.DO_NOTHING) + players = models.ManyToManyField(Player) + factions = models.ManyToManyField(Faction, blank=True) + points = models.IntegerField(null=True, blank=True) + winner = models.NullBooleanField(null=True) + + def __str__(self): + return str((self.play, self.points, self.winner)) diff --git a/pool/shard001/Python/0012689_models.py b/pool/shard001/Python/0012689_models.py new file mode 100644 index 0000000000000000000000000000000000000000..26db4f045a0ceab99d3272f6eccd8c17104997b0 --- /dev/null +++ b/pool/shard001/Python/0012689_models.py @@ -0,0 +1,115 @@ +import random +import datetime +from hashlib import sha1 +from django.conf import settings +from django.utils.translation import ugettext_lazy as _ +from django.db import models +from django.core.mail import send_mail +from django.core.urlresolvers import reverse +from django.template.loader import render_to_string +from django.contrib.auth.models import User +from django.contrib.sites.models import get_current_site + + +class EmailConfirmation(models.Model): + user = models.ForeignKey(User, + related_name='email_confirmations', + editable=False) + email = models.EmailField(_('e-mail address')) + key = models.CharField(_('confirmation key'), + max_length=40, + editable=False) + last_sent = models.DateTimeField(_('last time confirmation was sent'), + null=True) + + def __unicode__(self): + return self.email + + def save(self, *args, **kwargs): + if not self.key: + salt = sha1(str(random.random())).hexdigest()[:5] + self.key = sha1(salt+self.user.username).hexdigest() + super(EmailConfirmation, self).save(*args, **kwargs) + + def send(self, request, update_timestamp=True): + """ + Sends a confirmation message to the user optionally updating + last_sent timestamp. + """ + site = get_current_site(request) + context = { + 'confirmation': self, + 'confirmation_url': '%s://%s%s' % ( + 'https' if request.is_secure() else 'http', + site.domain, + reverse('accounts.confirm_email', + kwargs={'key': self.key}) + ) + } + subject = render_to_string( + 'accounts/email_confirmation_subject.j.txt', context) + message = render_to_string( + 'accounts/email_confirmation_message.j.txt', context) + email = send_mail(subject, message, + settings.DEFAULT_FROM_EMAIL, + [self.email]) + if update_timestamp: + self.last_sent = datetime.datetime.utcnow() + self.save() + return email + + def confirm(self, key): + if self.key == key: + self.delete() + return True + return False + + +class PasswordReset(models.Model): + user = models.ForeignKey(User, + related_name='password_resets', + editable=False) + key = models.CharField(_('reset key'), + max_length=40, + editable=False) + last_sent = models.DateTimeField(_('last time reset email was sent'), + null=True) + + def __unicode__(self): + return self.key + + def save(self, *args, **kwargs): + if not self.key: + salt = sha1(str(random.random())).hexdigest()[:5] + self.key = sha1(salt+self.user.username).hexdigest() + super(PasswordReset, self).save(*args, **kwargs) + + def send(self, request, update_timestamp=True): + """ + Sends a password reset message to the user optionally updating + last_sent timestamp. + """ + site = get_current_site(request) + context = { + 'reset': self, + 'reset_url': '%s://%s%s' % ( + 'https' if request.is_secure() else 'http', + site.domain, + reverse('accounts.password_reset_confirm', + kwargs={'key': self.key}) + ) + } + subject = render_to_string( + 'accounts/password_reset_subject.j.txt', context) + message = render_to_string( + 'accounts/password_reset_message.j.txt', context) + email = send_mail(subject, message, + settings.DEFAULT_FROM_EMAIL, + [self.user.email]) + if update_timestamp: + self.last_sent = datetime.datetime.utcnow() + self.save() + return email + + def verify(self, key): + return self.key == key diff --git a/pool/shard001/Python/0012693_drop_stale_gradient_optimizer.py b/pool/shard001/Python/0012693_drop_stale_gradient_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..586991a4b342a3866ff3e1913d7a59b5342eb43f --- /dev/null +++ b/pool/shard001/Python/0012693_drop_stale_gradient_optimizer.py @@ -0,0 +1,112 @@ +# Copyright 2017 The TensorFlow Authors. 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. +# ============================================================================== + +"""Wrapper optimizer for checking and dropping stale gradients.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.summary import summary +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_util + + +class DropStaleGradientOptimizer(optimizer.Optimizer): + """Wrapper optimizer that checks and drops stale gradient. + + This optimizer records the global step for each worker before computing + gradients and compares it with the global step at the time of applying the + gradients. If the difference is larger than a threshold, it will drop all + the computed gradients. + """ + + def __init__(self, + opt, + staleness, + use_locking=False, + name="DropStaleGradient"): + """Constructs a new DropStaleGradientOptimizer. + + Args: + opt: The actual optimizer that will be used to compute and apply the + gradients. Must be one of the Optimizer classes. + staleness: The maximum staleness allowed for the optimizer. + use_locking: If `True` use locks for clip update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "DropStaleGradient". + """ + super(DropStaleGradientOptimizer, self).__init__(use_locking, name) + self._opt = opt + self._staleness = staleness + + def compute_gradients(self, loss, *args, **kwargs): + # Record current global step for worker. + with ops.colocate_with(loss): + self._local_step = training_util.get_global_step() + 0 + + with ops.control_dependencies([self._local_step]): + loss = gen_array_ops.identity(loss) + return self._opt.compute_gradients(loss, *args, **kwargs) + + def get_slot(self, *args, **kwargs): + return self._opt.get_slot(*args, **kwargs) + + def get_slot_names(self, *args, **kwargs): + return self._opt.get_slot_names(*args, **kwargs) + + def apply_gradients(self, grads_and_vars, global_step=None, name=None): + gradients = [] + # Number of stale gradients. + stale_counter = variable_scope.get_variable( + "stale_counter", [], + initializer=init_ops.zeros_initializer(), + trainable=False) + + def _AcceptGradientOp(): + with ops.control_dependencies( + [self._opt.apply_gradients( + grads_and_vars, global_step=global_step, name=name)]): + return gen_array_ops.identity(0.0) + + def _DropGradientOp(): + return gen_array_ops.identity(1.0) + + for grad_and_var in grads_and_vars: + grad = grad_and_var[0] + if isinstance(grad, ops.Tensor): + gradients.append(grad) + else: + gradients.append(grad.op) + + with ops.control_dependencies(gradients), ops.colocate_with(global_step): + staleness = gen_array_ops.reshape( + global_step - self._local_step, shape=()) + conditional_update = stale_counter.assign_add(control_flow_ops.cond( + gen_math_ops.less_equal(staleness, self._staleness), + _AcceptGradientOp, _DropGradientOp)) + + summary.scalar( + "Gradient staleness percentage", + stale_counter / (math_ops.cast(global_step + 1, dtypes.float32))) + return conditional_update diff --git a/pool/shard001/Python/0012698_test_runner.py b/pool/shard001/Python/0012698_test_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..78a7a190b2efba82fe39c8350f640e12978f73b6 --- /dev/null +++ b/pool/shard001/Python/0012698_test_runner.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. +# +# Use of this source code is governed by a BSD-style license +# that can be found in the LICENSE file in the root of the source +# tree. An additional intellectual property rights grant can be found +# in the file PATENTS. All contributing project authors may +# be found in the AUTHORS file in the root of the source tree. + +""" +Runs tests on Android devices. + +This script exists to avoid WebRTC being broken by changes in the Chrome Android +test execution toolchain. It also conveniently sets the CHECKOUT_SOURCE_ROOT +environment variable. +""" + +import os +import sys + +SCRIPT_DIR = os.path.dirname(__file__) +SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir, + os.pardir)) +CHROMIUM_BUILD_ANDROID_DIR = os.path.join(SRC_DIR, 'build', 'android') +sys.path.insert(0, CHROMIUM_BUILD_ANDROID_DIR) + + +import test_runner # pylint: disable=W0406 +from pylib.gtest import gtest_test_instance + +def main(): + # Set our own paths to the .isolate files. + # pylint: disable=protected-access + gtest_test_instance._DEFAULT_ISOLATE_FILE_PATHS.update({ + 'audio_decoder_unittests': + 'webrtc/modules/audio_decoder_unittests.isolate', + 'common_audio_unittests': + 'webrtc/common_audio/common_audio_unittests.isolate', + 'common_video_unittests': + 'webrtc/common_video/common_video_unittests.isolate', + 'libjingle_peerconnection_unittest': + 'talk/libjingle_peerconnection_unittest.isolate', + 'modules_tests': 'webrtc/modules/modules_tests.isolate', + 'modules_unittests': 'webrtc/modules/modules_unittests.isolate', + 'rtc_unittests': 'webrtc/rtc_unittests.isolate', + 'system_wrappers_unittests': + 'webrtc/system_wrappers/system_wrappers_unittests.isolate', + 'test_support_unittests': 'webrtc/test/test_support_unittests.isolate', + 'tools_unittests': 'webrtc/tools/tools_unittests.isolate', + 'video_capture_tests': + 'webrtc/modules/video_capture/video_capture_tests.isolate', + 'video_engine_tests': 'webrtc/video_engine_tests.isolate', + 'voice_engine_unittests': + 'webrtc/voice_engine/voice_engine_unittests.isolate', + 'webrtc_nonparallel_tests': 'webrtc/webrtc_nonparallel_tests.isolate', + 'webrtc_perf_tests': 'webrtc/webrtc_perf_tests.isolate', + }) + # Override environment variable to make it possible for the scripts to find + # the root directory (our symlinking of the Chromium build toolchain would + # otherwise make them fail to do so). + os.environ['CHECKOUT_SOURCE_ROOT'] = SRC_DIR + return test_runner.main() + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard001/Python/0012703_lirc2raw.py b/pool/shard001/Python/0012703_lirc2raw.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9e23b2f5a2db419ad32502041a7182796f28af --- /dev/null +++ b/pool/shard001/Python/0012703_lirc2raw.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python +# Copyright (C) 2011 Woelfware + +'''Parser to convert lirc config files to BluMote config files. + +Usage: lirc2bm.py +''' + +import os.path +import sys + +parser_ver = '0.1' + +class lirc2raw(): + def __init__(self): + '''Initialize the lirc2raw object with code parameters and buttons.''' + self.remote_kw = { # key words for costructing the button codes + 'name' : 'name', + 'bits' : 'bits', + 'header' : 'header', + 'one' : 'one', + 'zero' : 'zero', + 'ptrail' : 'ptrail', + 'gap' : 'gap'} + self.code_kw = { # keys that can be automatically assigned + '0' : '0', 'zero' : '0', 'KEY_0' : '1', + '1' : '1', 'one' : '1', 'KEY_1' : '1', + '2' : '2', 'two' : '2', 'KEY_2' : '1', + '3' : '3', 'three' : '3', 'KEY_3' : '1', + '4' : '4', 'four' : '4', 'KEY_4' : '1', + '5' : '5', 'five' : '5', 'KEY_5' : '1', + '6' : '6', 'six' : '6', 'KEY_6' : '1', + '7' : '7', 'seven' : '7', 'KEY_7' : '1', + '8' : '8', 'eight' : '8', 'KEY_8' : '1', + '9' : '9', 'nine' : '9', 'KEY_9' : '1', + 'PLAY' : 'PLAY', + 'PAUSE' : 'PAUSE', + 'STOP' : 'STOP', + 'FORWARD' : 'FORWARD', + 'REVERSE' : 'REVERSE', + 'SKIP+' : 'SKIP+', + 'SKIP-' : 'SKIP-', + 'MENU' : 'MENU', + 'UP' : 'UP', 'KEY_UP' : 'UP', + 'DOWN' : 'DOWN', 'KEY_DOWN' : 'DOWN', + 'LEFT' : 'LEFT', 'KEY_LEFT' : 'LEFT', + 'RIGHT' : 'RIGHT', 'KEY_RIGHT' : 'RIGHT'} + + + def parse(self, fh): + '''Parse an LIRC remote config file.''' + remote = {'attributes' : {}, 'codes' : {}} + begin_remote = False + begin_codes = False + + for line in fh: + if line.startswith('#'): + continue + + words = line.split() + if not words: + continue + + if begin_codes: + if ' '.join(words[:2]) == 'end codes': + begin_codes = False + elif words[0] in self.code_kw.keys(): + # automatically assign codes for known buttons + try: + remote['codes'][self.code_kw[words[0]]] = '0x{:X}'.format(int(words[1])) + except ValueError: + remote['codes'][self.code_kw[words[0]]] = '0x{:X}'.format(int(words[1], 16)) + else: + # store codes in the database for buttons + # that could be used in an activity + try: + remote['codes'][words[0]] = '0x{:X}'.format(int(words[1])) + except ValueError: + remote['codes'][words[0]] = '0x{:X}'.format(int(words[1], 16)) + elif begin_remote: + if words[:2] == ['end', 'remote']: + begin_remote = False + elif ' '.join(words[:2]) == 'begin codes': + begin_codes = True + elif words[0] in self.remote_kw.keys(): + try: + remote['attributes'][self.remote_kw[words[0]]] = [int(i) for i in words[1:]] + except ValueError: + remote['attributes'][self.remote_kw[words[0]]] = ' '.join(words[1:]) + elif ' '.join(words[:2]) == 'begin remote': + begin_remote = True + + return remote + + def write_raw_config(self, remote, fin_name, fout_name): + '''Write the BluMote raw config file.''' + fout = open(fout_name, 'w') + + # file header + fout.write('# This file was automatically generated with {} ver {}' + ' using {} from the LIRC project.\n'.format(os.path.basename(__file__), + parser_ver, fin_name)) + + for key, code in sorted(remote['codes'].items()): + fout.write('{}\n'.format(key)) + code = int(code, 16) + + fout.write('\t{}\n'.format(remote['attributes']['header'][0])) + fout.write('\t{}\n'.format(remote['attributes']['header'][1])) + + for bit in range(remote['attributes']['bits'][0]): + if ((code >> (remote['attributes']['bits'][0] - bit - 1)) & 1): + # '1' + fout.write('\t{}\n'.format(remote['attributes']['one'][0])) + fout.write('\t{}\n'.format(remote['attributes']['one'][1])) + else: + # '0' + fout.write('\t{}\n'.format(remote['attributes']['zero'][0])) + fout.write('\t{}\n'.format(remote['attributes']['zero'][1])) + + fout.write('\t{}\n'.format(remote['attributes']['ptrail'][0])) + fout.write('\t{}\n'.format(remote['attributes']['gap'][0])) + + fout.close() + +if __name__ == '__main__': + if len(sys.argv) != 2: + print(__doc__) + sys.exit(1) + + parser = lirc2raw() + with open(sys.argv[1]) as fin: + remote = parser.parse(fin) + fin_name = os.path.basename(sys.argv[1]) + parser.write_raw_config(remote, fin_name, fin_name + '.bmraw') diff --git a/pool/shard001/Python/0012713_assigneddiscount.py b/pool/shard001/Python/0012713_assigneddiscount.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d77ac21e4ff24cecef8df0202e7e1358b98056 --- /dev/null +++ b/pool/shard001/Python/0012713_assigneddiscount.py @@ -0,0 +1,81 @@ + +""" + This code was generated by Codezu. + + Changes to this file may cause incorrect behavior and will be lost if + the code is regenerated. +""" + + +from mozurestsdk.mozuclient import default as default_client +from mozurestsdk.mozuurl import MozuUrl; +from mozurestsdk.urllocation import UrlLocation +from mozurestsdk.apicontext import ApiContext; + +class AssignedDiscount(object): + def __init__(self, apiContext: ApiContext = None, mozuClient = None): + self.client = mozuClient or default_client(); + if (apiContext is not None): + self.client.withApiContext(apiContext); + else: + self.client.withApiContext(ApiContext()); + + def getAssignedDiscounts(self,couponSetCode): + """ Retrieves the discountIds of any assigned discounts for the specified coupon set. + + Args: + | couponSetCode (string) - The unique identifier of the coupon set. + + Returns: + | array of AssignedDiscount + + Raises: + | ApiException + + """ + + url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts", "GET", UrlLocation.TenantPod, False); + url.formatUrl("couponSetCode", couponSetCode); + self.client.withResourceUrl(url).execute(); + return self.client.result(); + + + + def assignDiscount(self,assignedDiscount, couponSetCode): + """ Assigns or associates an existing discount to a specified coupon set. Use the couponSetCode parameter to specify the coupon set. + + Args: + | assignedDiscount(assignedDiscount) - The details of the discount assigned to the coupon set. + | couponSetCode (string) - The unique identifier of the coupon set. + + Raises: + | ApiException + + """ + + url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts", "POST", UrlLocation.TenantPod, False); + url.formatUrl("couponSetCode", couponSetCode); + self.client.withResourceUrl(url).withBody(assignedDiscount).execute(); + + + + def unAssignDiscount(self,couponSetCode, discountId): + """ Unassigns or disassociates the specified discount with the specified coupon set. + + Args: + | couponSetCode (string) - The unique identifier of the coupon set. + | discountId (int) - discountId parameter description DOCUMENT_HERE + + Raises: + | ApiException + + """ + + url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts/{discountId}", "DELETE", UrlLocation.TenantPod, False); + url.formatUrl("couponSetCode", couponSetCode); + url.formatUrl("discountId", discountId); + self.client.withResourceUrl(url).execute(); + + + + \ No newline at end of file diff --git a/pool/shard001/Python/0012715_test_cli.py b/pool/shard001/Python/0012715_test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..0127abf0a018884c4f469bc601d78a4ecad65fe4 --- /dev/null +++ b/pool/shard001/Python/0012715_test_cli.py @@ -0,0 +1,111 @@ +import argparse +import collections +import os +import subprocess +import yaml +import shutil + +from conda_smithy import cli + +_thisdir = os.path.abspath(os.path.dirname(__file__)) + +InitArgs = collections.namedtuple('ArgsObject', ('recipe_directory', + 'feedstock_directory')) + +RegenerateArgs = collections.namedtuple('ArgsObject', ('commit', + 'feedstock_directory', + 'no_check_uptodate', + 'exclusive_config_file')) + + +def test_init(py_recipe): + """This is the command that takes the initial staged-recipe folder and turns it into a + feedstock""" + # actual parser doesn't matter. It's used for initialization only + parser = argparse.ArgumentParser() + subparser = parser.add_subparsers() + init_obj = cli.Init(subparser) + recipe = py_recipe.recipe + # expected args object has + args = InitArgs(recipe_directory=os.path.join(recipe, 'recipe'), + feedstock_directory=os.path.join(recipe, '{package.name}-feedstock')) + init_obj(args) + destination = os.path.join(recipe, 'py-test-feedstock') + assert os.path.isdir(destination) + + +def test_init_multiple_output_matrix(testing_workdir): + parser = argparse.ArgumentParser() + subparser = parser.add_subparsers() + init_obj = cli.Init(subparser) + regen_obj = cli.Regenerate(subparser) + recipe = os.path.join(_thisdir, 'recipes', 'multiple_outputs') + feedstock_dir = os.path.join(testing_workdir, 'multiple-outputs-test-feedstock') + args = InitArgs(recipe_directory=recipe, + feedstock_directory=feedstock_dir) + init_obj(args) + # Ignore conda-forge-pinning for this test, as the test relies on conda-forge-pinning + # not being present + args = RegenerateArgs(feedstock_directory=feedstock_dir, + commit=False, + no_check_uptodate=True, + exclusive_config_file="recipe/conda_build_config.yaml") + regen_obj(args) + matrix_dir = os.path.join(feedstock_dir, '.ci_support') + # the matrix should be consolidated among all outputs, as well as the top-level + # reqs. Only the top-level reqs should have indedependent config files, + # though - loops within outputs are contained in those top-level configs. + assert len(os.listdir(matrix_dir)) == 13 + linux_libpng16 = os.path.join(matrix_dir, 'linux_libpng1.6libpq9.5.yaml') + assert os.path.isfile(linux_libpng16) + with open(linux_libpng16) as f: + config = yaml.load(f) + assert config['libpng'] == ['1.6'] + assert config['libpq'] == ['9.5'] + # this is a zipped key, but it's not used, so it shouldn't show up + assert 'libtiff' not in config + assert 'zip_keys' not in config or not any('libtiff' in group for group in config['zip_keys']) + # this is a variable only for one of the outputs + assert config['jpeg'] == ['8', '9'] + # this is in conda_build_config.yaml, but is a transitive dependency. It should + # not show up in the final configs. + assert 'zlib' not in config + + +def test_regenerate(py_recipe, testing_workdir): + parser = argparse.ArgumentParser() + subparser = parser.add_subparsers() + regen_obj = cli.Regenerate(subparser) + recipe = py_recipe.recipe + feedstock_dir = os.path.join(_thisdir, 'recipes', 'click-test-feedstock') + dest_dir = os.path.join(testing_workdir, 'click-test-feedstock') + shutil.copytree(feedstock_dir, dest_dir) + subprocess.call('git init'.split(), cwd=dest_dir) + subprocess.call('git add *'.split(), cwd=dest_dir) + subprocess.call('git commit -m "init"'.split(), cwd=dest_dir) + matrix_folder = os.path.join(dest_dir, '.ci_support') + + # original rendering was with py27, 36, no target_platform + assert len(os.listdir(matrix_folder)) == 7 + + # Ignore conda-forge-pinning for this test, as the test relies on conda-forge-pinning + # not being present + args = RegenerateArgs(feedstock_directory=dest_dir, + commit=False, + no_check_uptodate=True, + exclusive_config_file=os.path.join(recipe, 'config.yaml')) + + regen_obj(args) + + # should add 2, as the config.yaml adds in target_platform + assert len(os.listdir(matrix_folder)) == 9 + + # reduce the python matrix and make sure the matrix files reflect the change + args = RegenerateArgs(feedstock_directory=dest_dir, + commit=False, + no_check_uptodate=True, + exclusive_config_file=os.path.join(recipe, 'short_config.yaml')) + regen_obj(args) + + # one py ver, no target_platform (tests that older configs don't stick around) + assert len(os.listdir(matrix_folder)) == 4 diff --git a/pool/shard001/Python/0012716_config.py b/pool/shard001/Python/0012716_config.py new file mode 100644 index 0000000000000000000000000000000000000000..54a77f749f6b816db7e5e3d06a947a694bdcd9ad --- /dev/null +++ b/pool/shard001/Python/0012716_config.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- + +try: + # Python 2.7 + from collections import OrderedDict +except: + # Python 2.6 + from gluon.contrib.simplejson.ordered_dict import OrderedDict + +from gluon import current +from gluon.storage import Storage + +def config(settings): + """ + Template settings: 'Skeleton' designed to be copied to quickly create + custom templates + + All settings which are to configure a specific template are located + here. Deployers should ideally not need to edit any other files outside + of their template folder. + """ + + T = current.T + + #settings.base.system_name = T("Sahana Skeleton") + #settings.base.system_name_short = T("Sahana") + + # PrePopulate data + #settings.base.prepopulate = ("skeleton", "default/users") + settings.base.prepopulate += ("skeleton", "default/users") + + # Theme (folder to use for views/layout.html) + #settings.base.theme = "skeleton" + + # Authentication settings + # Should users be allowed to register themselves? + #settings.security.self_registration = False + # Do new users need to verify their email address? + #settings.auth.registration_requires_verification = True + # Do new users need to be approved by an administrator prior to being able to login? + #settings.auth.registration_requires_approval = True + #settings.auth.registration_requests_organisation = True + + # Approval emails get sent to all admins + settings.mail.approver = "ADMIN" + + # Restrict the Location Selector to just certain countries + # NB This can also be over-ridden for specific contexts later + # e.g. Activities filtered to those of parent Project + #settings.gis.countries = ("US",) + # Uncomment to display the Map Legend as a floating DIV + settings.gis.legend = "float" + # Uncomment to Disable the Postcode selector in the LocationSelector + #settings.gis.postcode_selector = False # @ToDo: Vary by country (include in the gis_config!) + # Uncomment to show the Print control: + # http://eden.sahanafoundation.org/wiki/UserGuidelines/Admin/MapPrinting + #settings.gis.print_button = True + + # L10n settings + # Languages used in the deployment (used for Language Toolbar & GIS Locations) + # http://www.loc.gov/standards/iso639-2/php/code_list.php + #settings.L10n.languages = OrderedDict([ + # ("ar", "العربية"), + # ("bs", "Bosanski"), + # ("en", "English"), + # ("fr", "Français"), + # ("de", "Deutsch"), + # ("el", "ελληνικά"), + # ("es", "Español"), + # ("it", "Italiano"), + # ("ja", "日本語"), + # ("km", "ភាសាខ្មែរ"), + # ("ko", "한국어"), + # ("ne", "नेपाली"), # Nepali + # ("prs", "دری"), # Dari + # ("ps", "پښتو"), # Pashto + # ("pt", "Português"), + # ("pt-br", "Português (Brasil)"), + # ("ru", "русский"), + # ("tet", "Tetum"), + # ("tl", "Tagalog"), + # ("tr", "Türkçe"), + # ("ur", "اردو"), + # ("vi", "Tiếng Việt"), + # ("zh-cn", "中文 (简体)"), + # ("zh-tw", "中文 (繁體)"), + #]) + # Default language for Language Toolbar (& GIS Locations in future) + #settings.L10n.default_language = "en" + # Uncomment to Hide the language toolbar + #settings.L10n.display_toolbar = False + # Default timezone for users + #settings.L10n.utc_offset = "+0100" + # Number formats (defaults to ISO 31-0) + # Decimal separator for numbers (defaults to ,) + settings.L10n.decimal_separator = "." + # Thousands separator for numbers (defaults to space) + settings.L10n.thousands_separator = "," + # Uncomment this to Translate Layer Names + #settings.L10n.translate_gis_layer = True + # Uncomment this to Translate Location Names + #settings.L10n.translate_gis_location = True + # Uncomment this to Translate Organisation Names/Acronyms + #settings.L10n.translate_org_organisation = True + # Finance settings + #settings.fin.currencies = { + # "EUR" : "Euros", + # "GBP" : "Great British Pounds", + # "USD" : "United States Dollars", + #} + #settings.fin.currency_default = "USD" + + # Security Policy + # http://eden.sahanafoundation.org/wiki/S3AAA#System-widePolicy + # 1: Simple (default): Global as Reader, Authenticated as Editor + # 2: Editor role required for Update/Delete, unless record owned by session + # 3: Apply Controller ACLs + # 4: Apply both Controller & Function ACLs + # 5: Apply Controller, Function & Table ACLs + # 6: Apply Controller, Function, Table ACLs and Entity Realm + # 7: Apply Controller, Function, Table ACLs and Entity Realm + Hierarchy + # 8: Apply Controller, Function, Table ACLs, Entity Realm + Hierarchy and Delegations + # + #settings.security.policy = 7 # Organisation-ACLs + + # ------------------------------------------------------------------------- + # Comment/uncomment modules here to disable/enable them + # Modules menu is defined in modules/eden/menu.py + settings.modules = OrderedDict([ + # Core modules which shouldn't be disabled + ("default", Storage( + name_nice = T("Home"), + restricted = False, # Use ACLs to control access to this module + access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller + module_type = None # This item is not shown in the menu + )), + ("admin", Storage( + name_nice = T("Administration"), + #description = "Site Administration", + restricted = True, + access = "|1|", # Only Administrators can see this module in the default menu & access the controller + module_type = None # This item is handled separately for the menu + )), + ("appadmin", Storage( + name_nice = T("Administration"), + #description = "Site Administration", + restricted = True, + module_type = None # No Menu + )), + ("errors", Storage( + name_nice = T("Ticket Viewer"), + #description = "Needed for Breadcrumbs", + restricted = False, + module_type = None # No Menu + )), + #("sync", Storage( + # name_nice = T("Synchronization"), + # #description = "Synchronization", + # restricted = True, + # access = "|1|", # Only Administrators can see this module in the default menu & access the controller + # module_type = None # This item is handled separately for the menu + #)), + #("tour", Storage( + # name_nice = T("Guided Tour Functionality"), + # module_type = None, + #)), + #("translate", Storage( + # name_nice = T("Translation Functionality"), + # #description = "Selective translation of strings based on module.", + # module_type = None, + #)), + ("gis", Storage( + name_nice = T("Map"), + #description = "Situation Awareness & Geospatial Analysis", + restricted = True, + module_type = 6, # 6th item in the menu + )), + ("pr", Storage( + name_nice = T("Person Registry"), + #description = "Central point to record details on People", + restricted = True, + access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still) + module_type = 10 + )), + ("org", Storage( + name_nice = T("Organizations"), + #description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities', + restricted = True, + module_type = 1 + )), + #("hrm", Storage( + # name_nice = T("Staff"), + # #description = "Human Resources Management", + # restricted = True, + # module_type = 2, + #)), + #("vol", Storage( + # name_nice = T("Volunteers"), + # #description = "Human Resources Management", + # restricted = True, + # module_type = 2, + #)), + #("cms", Storage( + # name_nice = T("Content Management"), + # #description = "Content Management System", + # restricted = True, + # module_type = 10, + #)), + #("doc", Storage( + # name_nice = T("Documents"), + # #description = "A library of digital resources, such as photos, documents and reports", + # restricted = True, + # module_type = 10, + #)), + #("msg", Storage( + # name_nice = T("Messaging"), + # #description = "Sends & Receives Alerts via Email & SMS", + # restricted = True, + # # The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules. + # module_type = None, + #)), + #("supply", Storage( + # name_nice = T("Supply Chain Management"), + # #description = "Used within Inventory Management, Request Management and Asset Management", + # restricted = True, + # module_type = None, # Not displayed + #)), + #("inv", Storage( + # name_nice = T("Warehouses"), + # #description = "Receiving and Sending Items", + # restricted = True, + # module_type = 4 + #)), + #("asset", Storage( + # name_nice = T("Assets"), + # #description = "Recording and Assigning Assets", + # restricted = True, + # module_type = 5, + #)), + # Vehicle depends on Assets + #("vehicle", Storage( + # name_nice = T("Vehicles"), + # #description = "Manage Vehicles", + # restricted = True, + # module_type = 10, + #)), + #("req", Storage( + # name_nice = T("Requests"), + # #description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.", + # restricted = True, + # module_type = 10, + #)), + #("project", Storage( + # name_nice = T("Projects"), + # #description = "Tracking of Projects, Activities and Tasks", + # restricted = True, + # module_type = 2 + #)), + #("cr", Storage( + # name_nice = T("Shelters"), + # #description = "Tracks the location, capacity and breakdown of victims in Shelters", + # restricted = True, + # module_type = 10 + #)), + #("hms", Storage( + # name_nice = T("Hospitals"), + # #description = "Helps to monitor status of hospitals", + # restricted = True, + # module_type = 10 + #)), + #("dvr", Storage( + # name_nice = T("Disaster Victim Registry"), + # #description = "Allow affected individuals & households to register to receive compensation and distributions", + # restricted = True, + # module_type = 10, + #)), + #("event", Storage( + # name_nice = T("Events"), + # #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).", + # restricted = True, + # module_type = 10, + #)), + #("transport", Storage( + # name_nice = T("Transport"), + # restricted = True, + # module_type = 10, + #)), + #("stats", Storage( + # name_nice = T("Statistics"), + # #description = "Manages statistics", + # restricted = True, + # module_type = None, + #)), + ]) + +# END ========================================================================= \ No newline at end of file diff --git a/pool/shard001/Python/0012723_main.py b/pool/shard001/Python/0012723_main.py new file mode 100644 index 0000000000000000000000000000000000000000..757f2e895f44c1f4325f446bc5e35788a34f1fc0 --- /dev/null +++ b/pool/shard001/Python/0012723_main.py @@ -0,0 +1,71 @@ +import sys,tty,termios,time +import RPi.GPIO as GPIO + +LEFT_PIN = 26 +RIGHT_PIN = 16 +STATUS_PIN = 13 + +class _Getch: + def __call__(self): + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setraw(sys.stdin.fileno()) + ch = sys.stdin.read(1) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + return ch + +def forward(): + GPIO.output(LEFT_PIN, True) + time.sleep(0.1) + GPIO.output(RIGHT_PIN, True) + +def left(): + GPIO.output(LEFT_PIN, True) + GPIO.output(RIGHT_PIN, False) + +def right(): + GPIO.output(LEFT_PIN, False) + GPIO.output(RIGHT_PIN, True) + +def stop(): + GPIO.output((LEFT_PIN, RIGHT_PIN), False) + +def get(): + inkey = _Getch() + while(1): + k=inkey() + if k!='':break + + if k == 'w': + forward() + elif k == 'a': + left() + elif k == 'd': + right() + elif k == 's': + stop() + elif k == 'p': + return False + + return True + +def main(): + print "Hello Spider" + + GPIO.setmode(GPIO.BCM) + GPIO.setup(LEFT_PIN, GPIO.OUT) + GPIO.setup(RIGHT_PIN, GPIO.OUT) + GPIO.setup(STATUS_PIN, GPIO.OUT) + + GPIO.output(STATUS_PIN, True) + while get(): + print "Still Running" + + print "Exiting" + GPIO.output(STATUS_PIN, False) + GPIO.cleanup() + +if __name__=='__main__': + main() diff --git a/pool/shard001/Python/0012726_launcher.py b/pool/shard001/Python/0012726_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..da798ac7d41507a2d257c22545ce0d052d3ab603 --- /dev/null +++ b/pool/shard001/Python/0012726_launcher.py @@ -0,0 +1,23 @@ +import sys +import Tkinter as tk + +from lib import config +#from lib import cheats +from lib import module +from lib import game + +def show_module(): + x = module.file.read() + return +def set_module_native(): + module.file.write(module.native() ) +def set_module_viking(): + module.file.write(module.viking_conquest() ) +def set_module_napoleonic(): + module.file.write(module.napoleonic_wars() ) + +root = tk.Tk() +root.title("Bley-Bley Launcher") + + +root.mainloop() diff --git a/pool/shard001/Python/0012730_filters.py b/pool/shard001/Python/0012730_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..9e116bcc8f9953a7937c37a33c7b296f90060e66 --- /dev/null +++ b/pool/shard001/Python/0012730_filters.py @@ -0,0 +1,245 @@ +import numpy as np +from scipy.interpolate import CubicSpline + +from hrv.rri import RRi +from hrv.utils import _create_time_info + + +__all__ = ['quotient', 'moving_average', 'moving_median', 'threshold_filter'] + + +def quotient(rri): + """ + Remove ectopic beats which the variation of two consecutive values + exceeds 20% + + Parameters + ---------- + rri : array_like + sequence containing the RRi series + + Returns + ------- + results : RRi array + instance of the RRi class containing the filtered RRi values + + See Also + ------- + moving_median, moving_averange, threshold_filter + + References + ---------- + - Piskorski J, Guzik P. Filtering poincare plots. + Comput Methods Sci Technol. 2005;11(1):39–48. + + Examples + -------- + >>> from hrv.filters import quotient + >>> from hrv.sampledata import load_noisy_rri + >>> noisy_rri = load_noisy_rri() + >>> quotient(noisy_rri) + RRi array([904., 913., 937., ..., 704., 805., 808.]) + """ + # TODO: Receive option to replaced outliers with stats + # functions (i.e mean, median etc) + # TODO: Receive option to re-create time array with cumsum of filtered rri + # TODO: Receive threshold value + + if isinstance(rri, RRi): + rri_time = rri.time + rri = rri.values + else: + rri = np.array(rri) + rri_time = _create_time_info(rri) + + L = len(rri) - 1 + + indices = np.where( + (rri[: L - 1] / rri[1:L] < 0.8) + | (rri[: L - 1] / rri[1:L] > 1.2) + | (rri[1:L] / rri[: L - 1] < 0.8) + | (rri[1:L] / rri[: L - 1] > 1.2) + ) + + rri_filt, time_filt = np.delete(rri, indices), np.delete(rri_time, indices) + return RRi(rri_filt, time_filt) + + +def moving_average(rri, order=3): + """ + Low-pass filter. Replace each RRi value by the average of its ⌊N/2⌋ + neighbors. The first and the last ⌊N/2⌋ RRi values are not filtered + + Parameters + ---------- + rri : array_like + sequence containing the RRi series + order : int, optional + Strength of the filter. Number of adjacent RRi values used to calculate + the average value to replace the current RRi. Defaults to 3. + + .. math:: + considering movinge average of order equal to 3: + RRi[j] = sum(RRi[j-2] + RRi[j-1] + RRi[j+1] + RRi[j+2]) / 3 + + Returns + ------- + results : RRi array + instance of the RRi class containing the filtered RRi values + + See Also + ------- + moving_median, threshold_filter, quotient + + Examples + -------- + >>> from hrv.filters import moving_average + >>> from hrv.sampledata import load_noisy_rri + >>> noisy_rri = load_noisy_rri() + >>> moving_average(noisy_rri) + RRi array([904., 918., 941.66666667, ..., 732.66666667, 772.33333, 808.]) + + """ + return _moving_function(rri, order, np.mean) + + +def moving_median(rri, order=3): + """ + Low-pass filter. Replace each RRi value by the median of its ⌊N/2⌋ + neighbors. The first and the last ⌊N/2⌋ RRi values are not filtered + + Parameters + ---------- + rri : array_like + sequence containing the RRi series + order : int, optional + Strength of the filter. Number of adjacent RRi values used to calculate + the median value to replace the current RRi. Defaults to 3. + + .. math:: + considering movinge average of order equal to 3: + RRi[j] = np.median([RRi[j-2], RRi[j-1], RRi[j+1], RRi[j+2]]) + + Returns + ------- + results : RRi array + instance of the RRi class containing the filtered RRi values + + See Also + ------- + moving_average, threshold_filter, quotient + + Examples + -------- + >>> from hrv.filters import moving_average + >>> from hrv.sampledata import load_noisy_rri + >>> noisy_rri = load_noisy_rri() + >>> moving_median(noisy_rri) + RRi array([904., 913., 937., ..., 704., 805., 808.]) + """ + return _moving_function(rri, order, np.median) + + +def threshold_filter(rri, threshold="medium", local_median_size=5): + """ + Low-pass filter. Inspired by the threshold-based artifact correction + algorithm offered by Kubios®. To elect outliers in the tachogram series, + each RRi is compared to the median value of local RRi (default N=5). + All the RRi which the difference is greater than the local median value + plus a threshold is replaced by cubic spline interpolated RRi. + + Parameters + ---------- + rri : array_like + sequence containing the RRi series + threshold : str or int, optional + Strength of the filter. If str will be translated to a threshold + in miliseconds according to the dict below. If int, it is considered + the threshold in miliseconds. Defaults to 'medium' (250ms) + - Very Low: 450ms + - Low: 350ms + - Medium: 250ms + - Strong: 150ms + - Very Strong: 50ms + local_median_size : int, optional + Number of RRi values considered to caculate a local median to be + compared with each RRi value + + .. math:: + considering the threshold equal to 'medium' and local_median_size + equal to 5: + local median RRi = np.median([RRi[j-5], RRi[j-4], RRi[j-3], + RRi[j-2], RRi[j-1]]) + - Ectopic beat, if abs(RRi[j] - local median RRi) > 250 + - Normal beat, if abs(RRi[j] - local median RRi) <= 250 + + Returns + ------- + results : RRi array + instance of the RRi class containing the filtered and cubic + interpolated RRi values + + See Also + ------- + moving_average, threshold_filter, quotient + + Examples + -------- + >>> from hrv.filters import moving_average + >>> from hrv.sampledata import load_noisy_rri + >>> noisy_rri = load_noisy_rri() + >>> threshold_filter(noisy_rri) + RRi array([904., 913., 937., ..., 704., 805., 808.]) + """ + # TODO: DRY + if isinstance(rri, RRi): + rri_time = rri.time + rri = rri.values + else: + rri_time = _create_time_info(rri) + + # Filter strength inspired in Kubios threshold based artifact correction + strength = { + "very low": 450, + "low": 350, + "medium": 250, + "strong": 150, + "very strong": 50, + } + threshold = strength[threshold] if threshold in strength else threshold + + n_rri = len(rri) + rri_to_remove = [] + # Apply filter in the beginning later + for j in range(local_median_size, n_rri): + slice_ = slice(j - local_median_size, j) + if rri[j] > (np.median(rri[slice_]) + threshold): + rri_to_remove.append(j) + + first_idx = list(range(local_median_size + 1)) + for j in range(local_median_size): + slice_ = [f for f in first_idx if not f == j] + if abs(rri[j] - np.median(rri[slice_])) > threshold: + rri_to_remove.append(j) + + rri_temp = [r for idx, r in enumerate(rri) if idx not in rri_to_remove] + time_temp = [t for idx, t in enumerate(rri_time) if idx not in rri_to_remove] + cubic_spline = CubicSpline(time_temp, rri_temp) + return RRi(cubic_spline(rri_time), rri_time) + + +def _moving_function(rri, order, func): + if isinstance(rri, RRi): + rri_time = rri.time + rri = rri.values + else: + rri_time = _create_time_info(rri) + + offset = int(order / 2) + + # TODO: Implemente copy method for RRi class + filt_rri = np.array(rri.copy(), dtype=np.float64) + for i in range(offset, len(rri) - offset, 1): + filt_rri[i] = func(rri[i - offset : i + offset + 1]) + + return RRi(filt_rri, rri_time) diff --git a/pool/shard001/Python/0012732_brenda_soap.py b/pool/shard001/Python/0012732_brenda_soap.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4625dd7409024da6722446b6fc6db7b34012c1 --- /dev/null +++ b/pool/shard001/Python/0012732_brenda_soap.py @@ -0,0 +1,32 @@ +#!/usr/bin/python +#the upper line depends on your operating system +from SOAPpy import WSDL +wsdl = 'http://www.brenda-enzymes.info/soap/brenda.wsdl' +serv = WSDL.Proxy(wsdl) + +orgs = ['falciparum','vivax'] + +for o in orgs: + results = serv.getKmValue({'organism':'Plasmodium '+o}) + + + for r in results: + ec = r[0][0][1] + + print r[0][5][1] + print r[0][0][1] + print r[0][4][1] + print r[0][6][1] + + results2 = serv.getRecommendedName({'ecNumber':ec}) + print results2[0][0][1][1] + break + + + + + + + + + diff --git a/pool/shard001/Python/0012734_models.py b/pool/shard001/Python/0012734_models.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcdf0cd4cd7e16cffaa99605757e384cba6e67a --- /dev/null +++ b/pool/shard001/Python/0012734_models.py @@ -0,0 +1,63 @@ +from conduit.database import (Model, SurrogatePK, db, + reference_col, relationship) +from flask_jwt import current_identity + +followers_assoc = db.Table("followers_assoc", + db.Column("follower", db.Integer, db.ForeignKey("userprofile.user_id")), + db.Column("followed_by", db.Integer, db.ForeignKey("userprofile.user_id"))) + + +class UserProfile(Model, SurrogatePK): + __tablename__ = 'userprofile' + + # id is needed for primary join, it does work with SurrogatePK class + id = db.Column(db.Integer, primary_key=True) + + user_id = reference_col('users', nullable=False) + user = relationship('User', backref=db.backref('profile', uselist=False)) + follows = relationship('UserProfile', + secondary=followers_assoc, + primaryjoin=id == followers_assoc.c.follower, + secondaryjoin=id == followers_assoc.c.followed_by, + backref='followed_by', + lazy='dynamic') + + def __init__(self, user, **kwargs): + db.Model.__init__(self, user=user, **kwargs) + + def is_following(self, profile): + return bool(self.follows.filter(followers_assoc.c.followed_by == profile.id).count()) + + def follow(self, profile): + if self is not profile and not self.is_following(profile): + self.follows.append(profile) + return True + return False + + def unfollow(self, profile): + if self is not profile and self.is_following(profile): + self.follows.remove(profile) + return True + return False + + @property + def following(self): + if current_identity: + return current_identity.profile.is_following(self) + return False + + @property + def username(self): + return self.user.username + + @property + def bio(self): + return self.user.bio + + @property + def image(self): + return self.user.image + + @property + def email(self): + return self.user.email diff --git a/pool/shard001/Python/0012739_pull.py b/pool/shard001/Python/0012739_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee4c192b3b0e991cf02a1ecee2e7b630b41dfb5 --- /dev/null +++ b/pool/shard001/Python/0012739_pull.py @@ -0,0 +1,97 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import sys +import traceback + +from neutron_lib import context as n_context + +from gbpservice.nfp.common import constants as nfp_constants +from gbpservice.nfp.core import log as nfp_logging +from gbpservice.nfp.core import module as nfp_api +from gbpservice.nfp.lib import transport as transport +from gbpservice.nfp.proxy_agent.lib import topics as a_topics + +LOG = nfp_logging.getLogger(__name__) + +ResourceMap = { + 'device_orch': a_topics.DEVICE_ORCH_TOPIC, + 'service_orch': a_topics.SERVICE_ORCH_TOPIC, + 'nas_service': a_topics.CONFIG_ORCH_TOPIC +} + + +"""Periodic Class to pull notification from configurator""" + + +class PullNotification(nfp_api.NfpEventHandler): + + def __init__(self, sc, conf): + self._sc = sc + self._conf = conf + + def handle_event(self, ev): + self._sc.poll_event(ev) + + def _method_handler(self, notification): + # Method handles notification as per resource, resource_type and method + try: + requester = notification['info']['context']['requester'] + if requester in ResourceMap: + topic = ResourceMap[requester] + context = notification['info']['context']['neutron_context'] + rpc_ctx = n_context.Context.from_dict(context) + else: + topic = requester.lower() + '_notifications' + rpc_ctx = n_context.get_admin_context() + rpcClient = transport.RPCClient(topic) + rpcClient.cctxt.cast(rpc_ctx, + 'network_function_notification', + notification_data=notification) + except Exception as e: + msg = "Exception while calling notification: %s" % (e) + LOG.error(msg) + raise Exception(e) + + @nfp_api.poll_event_desc(event='PULL_NOTIFICATIONS', + spacing=nfp_constants.PULL_NOTIFICATIONS_SPACING) + def pull_notifications(self, ev): + """Pull and handle notification from configurator.""" + notifications = transport.get_response_from_configurator(self._conf) + + if not isinstance(notifications, list): + message = "Notfications not list, %s" % (notifications) + LOG.error(message) + + else: + for notification in notifications: + if not notification: + message = "Receiver Response: Empty" + LOG.info(message) + continue + try: + self._method_handler(notification) + except AttributeError: + exc_type, exc_value, exc_traceback = sys.exc_info() + message = ("AttributeError while handling" + "message %s : %s " % (notification, + traceback.format_exception( + exc_type, exc_value, exc_traceback))) + LOG.error(message) + + except Exception as e: + exc_type, exc_value, exc_traceback = sys.exc_info() + message = ("Generic exception (%s)" + "while handling message (%s) : %s" % ( + e, notification, traceback.format_exception( + exc_type, exc_value, exc_traceback))) + LOG.error(message) diff --git a/pool/shard001/Python/0012740_vfs.py b/pool/shard001/Python/0012740_vfs.py new file mode 100644 index 0000000000000000000000000000000000000000..650a805bd7f15a7008f65dd124a29286ead36472 --- /dev/null +++ b/pool/shard001/Python/0012740_vfs.py @@ -0,0 +1,92 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +# implementation of dfs interface functions + +import shutil +import os.path +from dfsinterface import DfsInterface + +class Vfs(DfsInterface): + def __init__(self, config): + DfsInterface.__init__(self, config) + self.prefix = self.config.get("Vfs", "prefix") + + def __dfsToReal(self, dfspath): + realpath = os.path.join(self.prefix, dfspath) + return realpath + + def copyTo(self, localSrc, dst): + realdest = self.__dfsToReal(dst) + shutil.copy(localSrc, realdest) + # just assuming this works + return None + + def copyFrom(self, src, localDst): + realsrc = self.__dfsToReal(src) + shutil.copy(realsrc, localDst) + # just assuming this works + return None + + def copy(self, src, dst): + realsrc = self.__dfsToReal(src) + realdst = self.__dfsToReal(dst) + shutil.copy(realsrc, realdst) + # just assuming this works + return None + + def list(self, path): + try: + realpath = self.__dfsToReal(path) + return os.listdir(realpath) + except OSError, e: + # XXXstroucki error 20 = ENOTDIR + if (e.errno == 20): + return [path.split('/')[-1]] + else: + raise + + def stat(self, path): + realpath = self.__dfsToReal(path) + return os.stat(realpath) + + def move(self, src, dst): + realsrc = self.__dfsToReal(src) + realdst = self.__dfsToReal(dst) + shutil.move(realsrc, realdst) + # just assuming this works + return None + + def mkdir(self, path): + realpath = self.__dfsToReal(path) + return os.mkdir(realpath) + + def unlink(self, path): + realpath = self.__dfsToReal(path) + return os.unlink(realpath) + + def rmdir(self, path): + realpath = self.__dfsToReal(path) + return os.rmdir(realpath) + + def open(self, path, perm): + realpath = self.__dfsToReal(path) + return open(realpath, perm) + + def getLocalHandle(self, path): + realpath = self.__dfsToReal(path) + return realpath diff --git a/pool/shard001/Python/0012748_lorentz.py b/pool/shard001/Python/0012748_lorentz.py new file mode 100644 index 0000000000000000000000000000000000000000..2dce20cce44afe0b917789e5dd17f0fff7150c77 --- /dev/null +++ b/pool/shard001/Python/0012748_lorentz.py @@ -0,0 +1,98 @@ +# This file was automatically created by FeynRules $Revision: 510 $ +# Mathematica version: 7.0 for Linux x86 (64-bit) (February 18, 2009) +# Date: Wed 2 Mar 2011 15:09:56 + + +from object_library import all_lorentz, Lorentz + +from function_library import complexconjugate, re, im, csc, sec, acsc, asec + + + +SSS1 = Lorentz(name = 'SSS1', + spins = [ 1, 1, 1 ], + structure = '1') + +FFS1 = Lorentz(name = 'FFS1', + spins = [ 2, 2, 1 ], + structure = 'ProjM(2,1)') + +FFS2 = Lorentz(name = 'FFS2', + spins = [ 2, 2, 1 ], + structure = 'ProjP(2,1)') + +FFV1 = Lorentz(name = 'FFV1', + spins = [ 2, 2, 3 ], + structure = 'Gamma(3,2,1)') + +FFV2 = Lorentz(name = 'FFV2', + spins = [ 2, 2, 3 ], + structure = 'Gamma(3,2,-1)*ProjM(-1,1)') + +FFV3 = Lorentz(name = 'FFV3', + spins = [ 2, 2, 3 ], + structure = 'Gamma(3,2,-1)*ProjP(-1,1)') + +FFV4 = Lorentz(name = 'FFV4', + spins = [ 2, 2, 3 ], + structure = 'Gamma(3,2,-1)*ProjM(-1,1) - Gamma(3,2,-1)*ProjP(-1,1)') + +FFV5 = Lorentz(name = 'FFV5', + spins = [ 2, 2, 3 ], + structure = 'Gamma(3,2,-1)*ProjM(-1,1) + Gamma(3,2,-1)*ProjP(-1,1)') + +VSS1 = Lorentz(name = 'VSS1', + spins = [ 3, 1, 1 ], + structure = 'P(1,2) - P(1,3)') + +VVS1 = Lorentz(name = 'VVS1', + spins = [ 3, 3, 1 ], + structure = 'Metric(1,2)') + +VVV1 = Lorentz(name = 'VVV1', + spins = [ 3, 3, 3 ], + structure = 'P(3,1)*Metric(1,2) - P(3,2)*Metric(1,2) - P(2,1)*Metric(1,3) + P(2,3)*Metric(1,3) + P(1,2)*Metric(2,3) - P(1,3)*Metric(2,3)') + +VVSS1 = Lorentz(name = 'VVSS1', + spins = [ 3, 3, 1, 1 ], + structure = 'Metric(1,2)') + +VVVV1 = Lorentz(name = 'VVVV1', + spins = [ 3, 3, 3, 3 ], + structure = 'Metric(1,4)*Metric(2,3) - Metric(1,3)*Metric(2,4)') + +VVVV2 = Lorentz(name = 'VVVV2', + spins = [ 3, 3, 3, 3 ], + structure = 'Metric(1,4)*Metric(2,3) + Metric(1,3)*Metric(2,4) - 2*Metric(1,2)*Metric(3,4)') + +VVVV3 = Lorentz(name = 'VVVV3', + spins = [ 3, 3, 3, 3 ], + structure = 'Metric(1,4)*Metric(2,3) - Metric(1,2)*Metric(3,4)') + +VVVV4 = Lorentz(name = 'VVVV4', + spins = [ 3, 3, 3, 3 ], + structure = 'Metric(1,3)*Metric(2,4) - Metric(1,2)*Metric(3,4)') + +VVVV5 = Lorentz(name = 'VVVV5', + spins = [ 3, 3, 3, 3 ], + structure = 'Metric(1,4)*Metric(2,3) - (Metric(1,3)*Metric(2,4))/2. - (Metric(1,2)*Metric(3,4))/2.') + + + +# +# added for ADM +# +# by Deshpreet Singh Bedi and Ian-Woo Kim +# date : Apr 6, 2012 +# + + + +FFSS1 = Lorentz(name = 'FFSS1', + spins = [ 2, 2, 1, 1 ], + structure = 'ProjM(2,1)') + +FFSS2 = Lorentz(name = 'FFSS2', + spins = [ 2, 2, 1, 1 ], + structure = 'ProjP(2,1)') + diff --git a/pool/shard001/Python/0012749_fixtures.py b/pool/shard001/Python/0012749_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..79088261082774e4ab99fa5b9dbbf114d5a65826 --- /dev/null +++ b/pool/shard001/Python/0012749_fixtures.py @@ -0,0 +1,207 @@ +import pytest +from datetime import date, datetime +from dateutil.relativedelta import relativedelta + +from django.contrib.auth.models import User + +from records.models import ( + Category, Record, Budget, OUTCOME, INCOME, SAVINGS, tmz) +from records.month_control import MonthControl, MonthControlWithBudget + + +@pytest.fixture +def current_date(): + today = date.today() + today_datetime = datetime( + day=today.day, month=today.month, year=today.year) + return tmz(today_datetime) + + +@pytest.fixture +def future_date(current_date): + date = current_date+relativedelta(days=1) + return date + + +@pytest.fixture +def day_of_month(future_date): + return future_date.day + + +@pytest.fixture +def start_of_recurrence(future_date): + """ + Date object representing the first day of a record with recurrence + """ + return future_date + + +@pytest.fixture +def end_of_recurrence(future_date): + """ + Return a date which is used to determine the end month the recurrence + should occur + """ + date = future_date+relativedelta(months=6) + return date + + +@pytest.fixture +def next_month(current_date): + date = current_date+relativedelta(months=1) + return date + + +@pytest.fixture +def next_month_future(future_date): + date = future_date+relativedelta(months=1) + return date + + +@pytest.fixture +def infinite_future_date(current_date): + date = current_date+relativedelta(years=360) + return date + + +@pytest.fixture +def month_control(user, current_date): + """ + Return a MonthControl object for the current date. + + Important: currently any Record fixture should come before month_control + """ + month_control = MonthControl( + user, current_date.month, current_date.year, cache={}) + return month_control + + +@pytest.fixture +def month_control_with_budget(user, current_date): + """ + Return a MonthControlWithBudget object for the current date. + + Important: currently any Record fixture should come before month_control + """ + month_control = MonthControlWithBudget( + user, current_date.month, current_date.year, cache={}) + return month_control + + +def _user(username='test_user'): + raw_password = "fake" + new_user = User.objects.create_user( + username=username, email="a@b.com", password=raw_password) + setattr(new_user, "raw_password", raw_password) + return new_user + + +@pytest.fixture +def user(): + return _user() + + +@pytest.fixture +def another_user(): + return _user('another_user') + + +@pytest.fixture +def outcome(user): + """ + Main category of outcome type + """ + category = Category.objects.create( + name="outcome", type_category=OUTCOME, user=user) + return category + + +@pytest.fixture +def income(user): + """ + Main category of income type + """ + category = Category.objects.create( + name="income", type_category=INCOME, user=user) + return category + + +@pytest.fixture +def savings(user): + """ + Category of Savings + """ + category = Category.objects.create( + name="savings", type_category=SAVINGS, user=user) + return category + + +@pytest.fixture +def outcome_current(user, outcome, current_date): + """ + Record of type Outcome set to today (current date) + """ + record = Record.objects.create( + category=outcome, amount=1, start_date=current_date, user=user) + return record + + +@pytest.fixture +def outcome_future(user, outcome, future_date): + """ + Record of type Outcome set in the future + """ + record = Record.objects.create( + category=outcome, amount=1, start_date=future_date, user=user) + return record + + +@pytest.fixture +def outcome_recurrent(user, outcome, start_of_recurrence): + """ + Record of type Outcome set in the future with a day of the month set + to create a recurring record + + This fixture should not be used with outcome_recurrent_limited and + outcome_with_parent since they change the instance of this own record + """ + record = Record.objects.create( + category=outcome, amount=1, start_date=start_of_recurrence, user=user, + day_of_month=start_of_recurrence.day) + return record + + +@pytest.fixture +def outcome_recurrent_limited(user, outcome_recurrent, end_of_recurrence): + """ + Record of type Outcome set in the future with a recurring day of the month + set and limited to a certain time + """ + outcome_recurrent.end_date = end_of_recurrence + outcome_recurrent.save() + return outcome_recurrent + + +@pytest.fixture +def outcome_with_parent( + outcome_future, outcome_recurrent, next_month_future): + outcome_future.parent = outcome_recurrent + outcome_future.start_date = next_month_future + outcome_future.save() + return outcome_future + + +@pytest.fixture +def savings_current(request, user, savings, current_date): + """ + Record of type Outcome set in the future + """ + record = Record.objects.create( + category=savings, amount=1, start_date=current_date, user=user) + return record + + +@pytest.fixture +def budget(user): + budget = Budget.objects.create(user=user, amount=1) + return budget diff --git a/pool/shard001/Python/0012754_insert_sample_data.py b/pool/shard001/Python/0012754_insert_sample_data.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7036e5b28fd5fc3c79f97e23d8c5d35a29967c --- /dev/null +++ b/pool/shard001/Python/0012754_insert_sample_data.py @@ -0,0 +1,58 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from models import Base, User, Category, Item +import json +import sys +import time + +engine = create_engine('postgresql+psycopg2:///item_catalog', client_encoding='utf8') +Base.metadata.bind = engine +DBSession = sessionmaker(bind=engine) +db_session = DBSession() + + +def read_data_from_json_file(file_name): + """Method that reads a file with JSON content. + Args: + file_name: Exactly path of the file, if the file is in the same + directory of the program just pass the name. + Returns: + A python Dict Object from a valid Json Document. + Raises: + An Exception if the data being deserialized is not a valid JSON + document or the file isn't found. + """ + try: + file = open(file_name, encoding="utf-8") + data = json.load(file) + except Exception as e1: + print("Error failed to open file: {}".format(file_name)) + print(e1) + sys.exit(0) + return data + + +def main(): + """ Method that insert users by by one, and add them a set of categories with items into database + """ + data = read_data_from_json_file("sample_data.json") + for element_user in data: + user = User(name=element_user["name"], email=element_user["email"], + picture=element_user["picture"]) + db_session.add(user) + db_session.commit() + for element_category in element_user["categories"]: + category = Category(name=element_category["name"], user_id=user.id) + db_session.add(category) + db_session.commit() + time.sleep(1) + for element_item in element_category["items"]: + item = Item(name=element_item["name"], description=element_item["description"], + category_id=category.id, image_path=element_item["image_path"], + user_id=user.id) + db_session.add(item) + db_session.commit() + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0012755_setup.py b/pool/shard001/Python/0012755_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..285a1b5f3b797f598f6788937fd23d49b38df658 --- /dev/null +++ b/pool/shard001/Python/0012755_setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +#!/usr/bin/env python + +import os +import sys + +import appengine_toolkit + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +version = appengine_toolkit.__version__ + +if sys.argv[-1] == 'publish': + os.system('python setup.py sdist upload') + print("You probably want to also tag the version now:") + print(" git tag -a %s -m 'version %s'" % (version, version)) + print(" git push --tags") + sys.exit() + +readme = open('README.rst').read() +history = open('HISTORY.rst').read().replace('.. :changelog:', '') + +setup( + name='django-appengine-toolkit', + version=version, + description='Deploy Django projects on Google App Engine with ease', + long_description=readme + '\n\n' + history, + author='Massimiliano Pippi', + author_email='mpippi@gmail.com', + url='https://github.com/masci/django-appengine-toolkit', + packages=[ + 'appengine_toolkit', + ], + include_package_data=True, + install_requires=[ + 'django<1.6', + 'GoogleAppEngineCloudStorageClient', + ], + license="BSD", + zip_safe=False, + keywords='django-appengine-toolkit', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Framework :: Django', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + "Programming Language :: Python :: 2", + 'Programming Language :: Python :: 2.7', + ], +) \ No newline at end of file diff --git a/pool/shard001/Python/0012763_build-docs.py b/pool/shard001/Python/0012763_build-docs.py new file mode 100644 index 0000000000000000000000000000000000000000..306d0deb5d3e09b679e5440c9dbae0ab31347cd6 --- /dev/null +++ b/pool/shard001/Python/0012763_build-docs.py @@ -0,0 +1,82 @@ +#!/usr/bin/python + +import glob +import re +import readconfig +import yaml + +header_start = ''' + +%(title)s + + +''' + +header_mid = '''## Description + +%(description)s + +By default this image requires %(cpus)d CPU(s) and %(mem)dMB RAM. + +''' + +header_end = "<!-- HEADER -->" + +footer_start = "<!-- FOOTER -->" + +footer_mid = ''' + +## VM image maintainer(s) + +%(maintainers)s + +## Please contribute to this demo! + +Questions, comments, bug reports, feature requests, patches, pull requests and +cake are all welcomed on [GitHub](http://github.com/RedHatEMEA/demobuilder) or +to [jminter@redhat.com](mailto:jminter@redhat.com). + +If sending a bug report, please include the contents of +[/etc/demobuilder](/etc/demobuilder), as this will indicate the builds that were +used to create the VM image.''' + +footer_end = ''' + + + + + + +''' + +def main(): + for path in glob.glob("layers/*/@docs/*.html"): + layer = path.split("/")[1] + + config = readconfig.read_config(".") + for l in readconfig.layers(layer): + readconfig.update(config, readconfig.read_config(l)) + + maintainers = "\n".join([re.sub("(.*?) <(.*)>", r"- \1 <[\2](mailto:\2)>", m) for m in config["maintainers"]]) + + if path.endswith("/index.html"): + head = (header_start + header_mid + header_end) % {"title": config["name"], "description": config["description"].strip(), "cpus": config["layer"]["cpus"], "mem": config["layer"]["mem"]} + foot = (footer_start + footer_mid + footer_end) % {"maintainers": maintainers} + else: + head = (header_start + header_end) % {"title": config["name"], "description": config["description"].strip()} + foot = (footer_start + footer_end) % {"maintainers": maintainers} + + f = open(path).read() + + f = re.sub(".*" + head.splitlines()[-1], head, f, flags=re.S) + f = re.sub(foot.splitlines()[0] + ".*", foot, f, flags=re.S) + + open(path, "w").write(f) + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0012765_read_cutplane_pos.py b/pool/shard001/Python/0012765_read_cutplane_pos.py new file mode 100644 index 0000000000000000000000000000000000000000..103b8008865ccedbbe19999cd82cd2d238c99849 --- /dev/null +++ b/pool/shard001/Python/0012765_read_cutplane_pos.py @@ -0,0 +1,30 @@ +###################################################################### +# +# Function to read a .pos file generated by the gmsh CutPlane plugin +# (with no volume extraction, eg. when getting the value along a line.) +# +# Returns the x,y,z coordinates of the cut plane and the value along +# that plane +# +###################################################################### + +from numpy import * +import re + +def read_cutplane_pos(fname): + + x = []; + y = []; + z = []; + value = []; + + with open(fname) as f: + for line in f: + if 'SL(' in line: + line = re.split(r'[,|(|)|{|}]',line) + x.extend([float(line[1]),float(line[4])]) + y.extend([float(line[2]),float(line[5])]) + z.extend([float(line[3]),float(line[6])]) + value.extend([float(line[8]),float(line[9])]) + return x,y,z,value + diff --git a/pool/shard001/Python/0012766_wasb_hook.py b/pool/shard001/Python/0012766_wasb_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a766cf69de74911829a58f0c46995f850c60c7 --- /dev/null +++ b/pool/shard001/Python/0012766_wasb_hook.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 airflow.exceptions import AirflowException +from airflow.hooks.base_hook import BaseHook + +from azure.storage.blob import BlockBlobService + + +class WasbHook(BaseHook): + """ + Interacts with Azure Blob Storage through the wasb:// protocol. + + Additional options passed in the 'extra' field of the connection will be + passed to the `BlockBlockService()` constructor. For example, authenticate + using a SAS token by adding {"sas_token": "YOUR_TOKEN"}. + + :param wasb_conn_id: Reference to the wasb connection. + :type wasb_conn_id: str + """ + + def __init__(self, wasb_conn_id='wasb_default'): + self.conn_id = wasb_conn_id + self.connection = self.get_conn() + + def get_conn(self): + """Return the BlockBlobService object.""" + conn = self.get_connection(self.conn_id) + service_options = conn.extra_dejson + return BlockBlobService(account_name=conn.login, + account_key=conn.password, **service_options) + + def check_for_blob(self, container_name, blob_name, **kwargs): + """ + Check if a blob exists on Azure Blob Storage. + + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.exists()` takes. + :type kwargs: object + :return: True if the blob exists, False otherwise. + :rtype: bool + """ + return self.connection.exists(container_name, blob_name, **kwargs) + + def check_for_prefix(self, container_name, prefix, **kwargs): + """ + Check if a prefix exists on Azure Blob storage. + + :param container_name: Name of the container. + :type container_name: str + :param prefix: Prefix of the blob. + :type prefix: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.list_blobs()` takes. + :type kwargs: object + :return: True if blobs matching the prefix exist, False otherwise. + :rtype: bool + """ + matches = self.connection.list_blobs(container_name, prefix, + num_results=1, **kwargs) + return len(list(matches)) > 0 + + def load_file(self, file_path, container_name, blob_name, **kwargs): + """ + Upload a file to Azure Blob Storage. + + :param file_path: Path to the file to load. + :type file_path: str + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.create_blob_from_path()` takes. + :type kwargs: object + """ + # Reorder the argument order from airflow.hooks.S3_hook.load_file. + self.connection.create_blob_from_path(container_name, blob_name, + file_path, **kwargs) + + def load_string(self, string_data, container_name, blob_name, **kwargs): + """ + Upload a string to Azure Blob Storage. + + :param string_data: String to load. + :type string_data: str + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.create_blob_from_text()` takes. + :type kwargs: object + """ + # Reorder the argument order from airflow.hooks.S3_hook.load_string. + self.connection.create_blob_from_text(container_name, blob_name, + string_data, **kwargs) + + def get_file(self, file_path, container_name, blob_name, **kwargs): + """ + Download a file from Azure Blob Storage. + + :param file_path: Path to the file to download. + :type file_path: str + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.create_blob_from_path()` takes. + :type kwargs: object + """ + return self.connection.get_blob_to_path(container_name, blob_name, + file_path, **kwargs) + + def read_file(self, container_name, blob_name, **kwargs): + """ + Read a file from Azure Blob Storage and return as a string. + + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param kwargs: Optional keyword arguments that + `BlockBlobService.create_blob_from_path()` takes. + :type kwargs: object + """ + return self.connection.get_blob_to_text(container_name, + blob_name, + **kwargs).content + + def delete_file(self, container_name, blob_name, is_prefix=False, + ignore_if_missing=False, **kwargs): + """ + Delete a file from Azure Blob Storage. + + :param container_name: Name of the container. + :type container_name: str + :param blob_name: Name of the blob. + :type blob_name: str + :param is_prefix: If blob_name is a prefix, delete all matching files + :type is_prefix: bool + :param ignore_if_missing: if True, then return success even if the + blob does not exist. + :type ignore_if_missing: bool + :param kwargs: Optional keyword arguments that + `BlockBlobService.create_blob_from_path()` takes. + :type kwargs: object + """ + + if is_prefix: + blobs_to_delete = [ + blob.name for blob in self.connection.list_blobs( + container_name, prefix=blob_name, **kwargs + ) + ] + elif self.check_for_blob(container_name, blob_name): + blobs_to_delete = [blob_name] + else: + blobs_to_delete = [] + + if not ignore_if_missing and len(blobs_to_delete) == 0: + raise AirflowException('Blob(s) not found: {}'.format(blob_name)) + + for blob_uri in blobs_to_delete: + self.log.info("Deleting blob: " + blob_uri) + self.connection.delete_blob(container_name, + blob_uri, + delete_snapshots='include', + **kwargs) diff --git a/pool/shard001/Python/0012772_simple_snapshot.py b/pool/shard001/Python/0012772_simple_snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..a726aa7482a929cc9ffe4837e8bf6a240af65ea3 --- /dev/null +++ b/pool/shard001/Python/0012772_simple_snapshot.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +from delphixpy.v1_6_0.delphix_engine import DelphixEngine +from delphixpy.v1_6_0.web import group, database +group_name = "Dev Copies" +database_name = "Employee DB - Dev" + +server_session = DelphixEngine("landsharkengine", "delphix_admin", "landshark", "DOMAIN") + +all_groups = group.get_all(server_session) + +for each in all_groups: + if group_name == each.name: + group_reference = each.reference + break + +database_objs = database.get_all(server_session, group=group_reference) + +for obj in database_objs: + if database_name == obj.name: + database_reference = obj.reference + break + +database.sync(server_session, database_reference) \ No newline at end of file diff --git a/pool/shard001/Python/0012779_inmemdb.py b/pool/shard001/Python/0012779_inmemdb.py new file mode 100644 index 0000000000000000000000000000000000000000..e37bd51fbda908cf952f146467eff86a88e298b4 --- /dev/null +++ b/pool/shard001/Python/0012779_inmemdb.py @@ -0,0 +1,73 @@ +# Copyright 2013 Metacloud, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""Keystone In-Memory Dogpile.cache backend implementation.""" + +import copy + +from dogpile.cache import api +from oslo_log import versionutils + + +NO_VALUE = api.NO_VALUE + + +@versionutils.deprecated( + versionutils.deprecated.OCATA, + what='keystone.common.kvs.backends.MemoryBackend', + remove_in=+1) +class MemoryBackend(api.CacheBackend): + """A backend that uses a plain dictionary. + + There is no size management, and values which are placed into the + dictionary will remain until explicitly removed. Note that Dogpile's + expiration of items is based on timestamps and does not remove them from + the cache. + + E.g.:: + + from dogpile.cache import make_region + + region = make_region().configure( + 'keystone.common.kvs.Memory' + ) + """ + + def __init__(self, arguments): + self._db = {} + + def _isolate_value(self, value): + if value is not NO_VALUE: + return copy.deepcopy(value) + return value + + def get(self, key): + return self._isolate_value(self._db.get(key, NO_VALUE)) + + def get_multi(self, keys): + return [self.get(key) for key in keys] + + def set(self, key, value): + self._db[key] = self._isolate_value(value) + + def set_multi(self, mapping): + for key, value in mapping.items(): + self.set(key, value) + + def delete(self, key): + self._db.pop(key, None) + + def delete_multi(self, keys): + for key in keys: + self.delete(key) diff --git a/pool/shard001/Python/0012783_html_output_formatter.py b/pool/shard001/Python/0012783_html_output_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..46d264c32876bb66c77942595fa7ca9b7e95aa65 --- /dev/null +++ b/pool/shard001/Python/0012783_html_output_formatter.py @@ -0,0 +1,190 @@ +# Copyright 2014 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. + +import datetime +import json +import logging +import os +import re + +from catapult_base import cloud_storage # pylint: disable=import-error + +from telemetry.core import util +from telemetry.internal.results import chart_json_output_formatter +from telemetry.internal.results import output_formatter +from telemetry import value as value_module +from telemetry.value import list_of_scalar_values + + +_TEMPLATE_HTML_PATH = os.path.join( + util.GetTelemetryDir(), 'support', 'html_output', 'results-template.html') +_JS_PLUGINS = [os.path.join('flot', 'jquery.flot.min.js'), + os.path.join('WebKit', 'PerformanceTests', 'resources', + 'jquery.tablesorter.min.js'), + os.path.join('WebKit', 'PerformanceTests', 'resources', + 'statistics.js')] +_UNIT_JSON = os.path.join( + util.GetTelemetryDir(), 'telemetry', 'value', 'unit-info.json') + + +def _DatetimeInEs5CompatibleFormat(dt): + return dt.strftime('%Y-%m-%dT%H:%M:%S.%f') + + +def _ShortDatetimeInEs5CompatibleFormat(dt): + return dt.strftime('%Y-%m-%d %H:%M:%S') + + +# TODO(eakuefner): rewrite template to use Telemetry JSON directly +class HtmlOutputFormatter(output_formatter.OutputFormatter): + def __init__(self, output_stream, metadata, reset_results, upload_results, + browser_type, results_label=None): + super(HtmlOutputFormatter, self).__init__(output_stream) + self._metadata = metadata + self._reset_results = reset_results + self._upload_results = upload_results + self._build_time = self._GetBuildTime() + self._existing_results = self._ReadExistingResults(output_stream) + if results_label: + self._results_label = results_label + else: + self._results_label = '%s (%s)' % ( + metadata.name, _ShortDatetimeInEs5CompatibleFormat(self._build_time)) + self._result = { + 'buildTime': _DatetimeInEs5CompatibleFormat(self._build_time), + 'label': self._results_label, + 'platform': browser_type, + 'tests': {} + } + + def _GetBuildTime(self): + return datetime.datetime.utcnow() + + def _GetHtmlTemplate(self): + with open(_TEMPLATE_HTML_PATH) as f: + return f.read() + + def _GetPlugins(self): + plugins = '' + for p in _JS_PLUGINS: + with open(os.path.join(util.GetTelemetryThirdPartyDir(), p)) as f: + plugins += f.read() + return plugins + + def _GetUnitJson(self): + with open(_UNIT_JSON) as f: + return f.read() + + def _ReadExistingResults(self, output_stream): + results_html = output_stream.read() + if self._reset_results or not results_html: + return [] + m = re.search( + '^$', + results_html, re.MULTILINE | re.DOTALL) + if not m: + logging.warn('Failed to extract previous results from HTML output') + return [] + return json.loads(m.group(1))[:512] + + def _SaveResults(self, results): + self._output_stream.seek(0) + self._output_stream.write(results) + self._output_stream.truncate() + + def _PrintPerfResult(self, measurement, trace, values, units, + result_type='default', std=None): + metric_name = measurement + if trace != measurement: + metric_name += '.' + trace + self._result['tests'].setdefault(self._test_name, {}) + self._result['tests'][self._test_name].setdefault('metrics', {}) + metric_data = { + 'current': values, + 'units': units, + 'important': result_type == 'default' + } + if std is not None: + metric_data['std'] = std + self._result['tests'][self._test_name]['metrics'][metric_name] = metric_data + + def _TranslateChartJson(self, chart_json_dict): + dummy_dict = dict() + + for chart_name, traces in chart_json_dict['charts'].iteritems(): + for trace_name, value_dict in traces.iteritems(): + # TODO(eakuefner): refactor summarization so we don't have to jump + # through hoops like this. + if 'page_id' in value_dict: + del value_dict['page_id'] + result_type = 'nondefault' + else: + result_type = 'default' + + # Note: we explicitly ignore TraceValues because Buildbot did. + if value_dict['type'] == 'trace': + continue + value = value_module.Value.FromDict(value_dict, dummy_dict) + + perf_value = value.GetBuildbotValue() + + if '@@' in chart_name: + chart_name_to_print = '%s-%s' % tuple(chart_name.split('@@')) + else: + chart_name_to_print = str(chart_name) + + if trace_name == 'summary': + trace_name = chart_name_to_print + + std = None + if isinstance(value, list_of_scalar_values.ListOfScalarValues): + std = value.std + + self._PrintPerfResult(chart_name_to_print, trace_name, perf_value, + value.units, result_type, std) + + @property + def _test_name(self): + return self._metadata.name + + def GetResults(self): + return self._result + + def GetCombinedResults(self): + all_results = list(self._existing_results) + all_results.append(self.GetResults()) + return all_results + + def Format(self, page_test_results): + chart_json_dict = chart_json_output_formatter.ResultsAsChartDict( + self._metadata, page_test_results.all_page_specific_values, + page_test_results.all_summary_values) + + self._TranslateChartJson(chart_json_dict) + self._PrintPerfResult('telemetry_page_measurement_results', 'num_failed', + [len(page_test_results.failures)], 'count', + 'unimportant') + + html = self._GetHtmlTemplate() + html = html.replace('%json_results%', json.dumps(self.GetCombinedResults())) + html = html.replace('%json_units%', self._GetUnitJson()) + html = html.replace('%plugins%', self._GetPlugins()) + self._SaveResults(html) + + if self._upload_results: + file_path = os.path.abspath(self._output_stream.name) + file_name = 'html-results/results-%s' % datetime.datetime.now().strftime( + '%Y-%m-%d_%H-%M-%S') + try: + cloud_storage.Insert(cloud_storage.PUBLIC_BUCKET, file_name, file_path) + print + print ('View online at ' + 'http://storage.googleapis.com/chromium-telemetry/%s' + % file_name) + except cloud_storage.PermissionError as e: + logging.error('Cannot upload profiling files to cloud storage due to ' + ' permission error: %s' % e.message) + print + print 'View result at file://%s' % os.path.abspath( + self._output_stream.name) diff --git a/pool/shard001/Python/0012786_models.py b/pool/shard001/Python/0012786_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8aa096763e24a64a4df1b2f2bf6837f76d947aaa --- /dev/null +++ b/pool/shard001/Python/0012786_models.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import +from django.db import models +from .choices import * +from config.settings.common import DOMINIO, DEFAULT_FROM_EMAIL + + +from django.contrib.auth.models import AbstractUser +# from django.db import models +# from django.utils.translation import ugettext_lazy as _ + +from django.template.loader import get_template +from django.template import Context +from django.core.mail import EmailMultiAlternatives + +class User(AbstractUser): + + perfil = models.CharField(max_length=25, choices=Perfiles, default="Operador") + + def __unicode__(self): + return self.username + + def mail_usuario(self, password): + + fail_silently = True + + c = Context({ + 'usuario': self, + 'password': password, + 'dominio': DOMINIO, + }) + + html_content = get_template('email/mail_usuario_alta.html').render(c) + plaintext = get_template('email/mail_usuario_alta.txt').render(c) + + msg = EmailMultiAlternatives( + subject="Notificación de usuario", + body=plaintext, + from_email=DEFAULT_FROM_EMAIL, + to= (self.email,), + ) + + msg.attach_alternative(html_content, "text/html") + + msg.send(fail_silently) + diff --git a/pool/shard001/Python/0012790_tasks.py b/pool/shard001/Python/0012790_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..22332a822da570555ce3cf0d13a6edc21929f148 --- /dev/null +++ b/pool/shard001/Python/0012790_tasks.py @@ -0,0 +1,33 @@ +# Eve W-Space +# Copyright 2014 Andrew Austin and contributors +# +# 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 celery import task +from API.models import APIKey, MemberAPIKey +from django.core.cache import cache +from django.contrib.auth import get_user_model +import sys +reload(sys) +sys.setdefaultencoding("utf-8") + +User = get_user_model() + +@task() +def update_char_data(): + #Get all users + user_list = User.objects.all() + for user in user_list: + #Get all API keys of a user and validate them + for key in user.api_keys.all(): + key.validate() diff --git a/pool/shard001/Python/0012793_init__.py b/pool/shard001/Python/0012793_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..649b791131bd38b680f1fad10ea97a332c450a07 --- /dev/null +++ b/pool/shard001/Python/0012793_init__.py @@ -0,0 +1,112 @@ +#============================================================================== +# Copyright 2013 Amazon.com, Inc. or its affiliates. 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. +#============================================================================== +__author__ = 'aws' +__version__ = '0.2' + +import logging.config +import os.path +import sys +import StringIO + +try: + from logging import NullHandler +except ImportError: + class NullHandler(logging.Handler): + def emit(self, record): + pass + +_config = """[loggers] +keys=root,cfnresourcebridge +[handlers] +keys=%(all_handlers)s +[formatters] +keys=amzn +[logger_root] +level=NOTSET +handlers=%(root_handler)s +[logger_cfnresourcebridge] +level=NOTSET +handlers=%(root_handler)s +qualname=cfn.resourcebridge +propagate=0 +[logger_wire] +level=NOTSET +handlers=%(wire_handler)s +qualname=wire +propagate=0 +[handler_default] +class=handlers.RotatingFileHandler +level=%(conf_level)s +formatter=amzn +args=('%(conf_file)s', 'a', 5242880, 5, 'UTF-8') +[handler_wire] +class=handlers.RotatingFileHandler +level=DEBUG +formatter=amzn +args=('%(wire_file)s', 'a', 5242880, 5, 'UTF-8') +[handler_tostderr] +class=StreamHandler +level=%(conf_level)s +formatter=amzn +args=(sys.stderr,) +[formatter_amzn] +format=%(asctime)s [%(levelname)s] %(message)s +datefmt= +class=logging.Formatter +""" + + +def _get_log_file(filename): + if os.name == 'nt': + logdir = os.path.expandvars(r'${SystemDrive}\cfn\log') + if not os.path.exists(logdir): + os.makedirs(logdir) + return logdir + os.path.sep + filename + + return '/var/log/%s' % filename + + +def configure_logging(level='INFO', quiet=False, filename='cfn-resource-bridge.log', log_dir=None, wire_log=True): + if not log_dir: + output_file = _get_log_file(filename) + wire_file = _get_log_file('cfn-resource-bridge-wire.log') if wire_log else None + else: + output_file = os.path.join(log_dir, filename) + wire_file = os.path.join(log_dir, 'cfn-resource-bridge-wire.log') if wire_log else None + + config = {'conf_level': level, + 'all_handlers': 'default' + (',wire' if wire_log else ''), + 'root_handler': 'default', + 'wire_handler': 'wire' if wire_log else None, + 'conf_file': output_file} + + if wire_file: + config['wire_file'] = wire_file + + try: + logging.config.fileConfig(StringIO.StringIO(_config), config) + if not wire_log: + logging.getLogger('wire').addHandler(NullHandler()) + except IOError: + config['all_handlers'] = 'tostderr' + config['root_handler'] = 'tostderr' + config['wire_handler'] = None + if not quiet: + print >> sys.stderr, "Could not open %s for logging. Using stderr instead." % output_file + logging.config.fileConfig(StringIO.StringIO(_config), config) + logging.getLogger('wire').addHandler(NullHandler()) + +configure_logging(quiet=True, wire_log=True) diff --git a/pool/shard001/Python/0012794_regional_distribute_unplaced_jobs_model_configuration_creator.py b/pool/shard001/Python/0012794_regional_distribute_unplaced_jobs_model_configuration_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..0eccb11dd3dbf81792eb304b655cc6a4a5173b8b --- /dev/null +++ b/pool/shard001/Python/0012794_regional_distribute_unplaced_jobs_model_configuration_creator.py @@ -0,0 +1,56 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + +from opus_core.configuration import Configuration +from urbansim.configurations.distribute_unplaced_jobs_model_configuration_creator import DistributeUnplacedJobsModelConfigurationCreator + +class RegionalDistributeUnplacedJobsModelConfigurationCreator(DistributeUnplacedJobsModelConfigurationCreator): + + _model_name = 'regional_distribute_unplaced_jobs_model' + + def execute(self): + conf = DistributeUnplacedJobsModelConfigurationCreator.execute(self) + conf['import'] = {'washtenaw.models.%s' % self._model_name: 'RegionalDistributeUnplacedJobsModel'} + conf['init']['name'] = 'RegionalDistributeUnplacedJobsModel' + return conf + +from opus_core.tests import opus_unittest + + +class TestDistributeUnplacedJobsModelConfigurationCreator(opus_unittest.OpusTestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_defaults(self): + creator = RegionalDistributeUnplacedJobsModelConfigurationCreator() + + expected = Configuration({ + 'import': { + 'washtenaw.models.regional_distribute_unplaced_jobs_model': 'RegionalDistributeUnplacedJobsModel' + }, + 'init': { + 'arguments': {'debuglevel': 'debuglevel', + 'dataset_pool': 'dataset_pool', + 'filter':None}, + 'name': 'RegionalDistributeUnplacedJobsModel', + }, + 'run': { + 'arguments': { + 'agent_set': 'job', + 'data_objects': 'datasets', + 'location_set': 'gridcell', + 'agents_filter':None + } + }, + }) + + result = creator.execute() + self.assertDictsEqual(result, expected) + + +if __name__ == '__main__': + opus_unittest.main() \ No newline at end of file diff --git a/pool/shard001/Python/0012804_measurement_pyscript.py b/pool/shard001/Python/0012804_measurement_pyscript.py new file mode 100644 index 0000000000000000000000000000000000000000..e632ae71318371637c03f3b8e222095c44646c68 --- /dev/null +++ b/pool/shard001/Python/0012804_measurement_pyscript.py @@ -0,0 +1,76 @@ +from __future__ import absolute_import +from pychron.core.ui import set_qt + +set_qt() + +__author__ = 'ross' + +import unittest +import os +from pychron.pyscripts.measurement_pyscript import MeasurementPyScript, MeasurementCTXObject + + +class DocstrContextTestCase(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.script = MeasurementPyScript() + p = 'pychron/pyscripts/tests/data/measurement_script.txt' + if not os.path.isfile(p): + p = './data/measurement_script.txt' + + with open(p, 'r') as rfile: + cls.script.text = rfile.read() + + cls.script.bootstrap() + cls.script.setup_context() + + def test_mx(self): + self.assertIsInstance(self.script._ctx['mx'], MeasurementCTXObject) + + def test_mx_multicollect_counts(self): + self.assertEqual(self.script._ctx['mx'].multicollect.counts, 5) + + def test_mx_baseline_counts(self): + self.assertEqual(self.script._ctx['mx'].baseline.counts, 3) + + +class InterpolationTestCase(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.script = MeasurementPyScript() + cls.script.bootstrap() + p = 'pychron/pyscripts/tests/data/script_options.yaml' + if not os.path.isfile(p): + p = './data/script_options.yaml' + cls.script.interpolation_path = p + + def test_warm_cdd(self): + v = self.script.warm_cdd + self.assertEqual(v, False) + + def test_float(self): + v = self.script.float_value + self.assertIsInstance(v, float) + + def test_fail_attr(self): + # v = self.script.novalue + # self.assertIsNone(v) + self.assertRaises(AttributeError, lambda: self.script.novalue) + + def test_execute_snippet(self): + snippet = '''def main(): a= float_value+2''' + v = self.script.execute_snippet(snippet) + self.assertIs(v, None) + + # snippet = '''def main(): a= float_value+boo*bat''' + # v = self.script.execute_snippet(snippet) + # self.assertIs(v, None) + + def test_execute_snippet_fail(self): + snippet = '''def main(): a= float_valufe+2''' + v = self.script.execute_snippet(snippet) + self.assertIsInstance(v, str) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0012806_test_platform.py b/pool/shard001/Python/0012806_test_platform.py new file mode 100644 index 0000000000000000000000000000000000000000..b3302eb9c807ef74c0d1e2fe99e1cdbf21665a4b --- /dev/null +++ b/pool/shard001/Python/0012806_test_platform.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# +# 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 json + +from functionaltests.api import base + + +class TestPlatformAndContainers(base.TestCase): + + def _test_get_resource(self, url, rtype, name): + resp, body = self.client.get(url) + self.assertEqual(200, resp.status, 'GET %s resource' % rtype) + resource = json.loads(body) + self.assertEqual(rtype, resource['type']) + self.assertEqual(name, resource['name']) + + def test_get_platform_and_containers(self): + # get and test our platform resource + resp, body = self.client.get('camp/v1_1/platform/') + self.assertEqual(200, resp.status, 'GET platform resource') + platform = json.loads(body) + self.assertEqual('platform', platform['type']) + self.assertEqual('Solum_CAMP_v1_1_platform', platform['name']) + self.assertEqual('CAMP 1.1', platform['specification_version']) + self.assertEqual('Solum CAMP 1.1', platform['implementation_version']) + + # get and test the supported formats resource + url = (platform['supported_formats_uri'] + [len(self.client.base_url) + 1:]) + self._test_get_resource(url, 'formats', 'Solum_CAMP_formats') + + # get and test the extensions resource + url = (platform['extensions_uri'] + [len(self.client.base_url) + 1:]) + self._test_get_resource(url, 'extensions', 'Solum_CAMP_extensions') + + # get and test the type_definitions resource + url = (platform['type_definitions_uri'] + [len(self.client.base_url) + 1:]) + self._test_get_resource(url, + 'type_definitions', + 'Solum_CAMP_type_definitions') + + # get and test the platform_endpoints resource + url = (platform['platform_endpoints_uri'] + [len(self.client.base_url) + 1:]) + self._test_get_resource(url, + 'platform_endpoints', + 'Solum_CAMP_endpoints') + + # get and test the assemblies collection resource + url = platform['assemblies_uri'][len(self.client.base_url) + 1:] + self._test_get_resource(url, 'assemblies', 'Solum_CAMP_assemblies') + + # get and test the services collection resource + url = platform['services_uri'][len(self.client.base_url) + 1:] + self._test_get_resource(url, 'services', 'Solum_CAMP_services') + + # get and test the plans collection resource + url = platform['plans_uri'][len(self.client.base_url) + 1:] + self._test_get_resource(url, 'plans', 'Solum_CAMP_plans') diff --git a/pool/shard001/Python/0012810_test_json.py b/pool/shard001/Python/0012810_test_json.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9d1f53e5915c970fc172859bdfc50a23be8512 --- /dev/null +++ b/pool/shard001/Python/0012810_test_json.py @@ -0,0 +1,28 @@ +from __future__ import absolute_import, division, print_function + +from blaze.utils import example +from odo.backends.json import JSON, JSONLines +from odo import Chunks +from blaze import symbol, discover, compute, into, resource + + +js = JSON(example('accounts.json')) +jss = JSONLines(example('accounts-streaming.json')) + +s = symbol('s', discover(js)) + + +def test_simple(): + assert compute(s.count(), js) == 5 + assert compute(s.count(), jss) == 5 + + +def test_less_simple(): + assert compute(s.amount.sum(), js) == 100 + assert compute(s.amount.sum(), jss) == 100 + + +def test_chunks_json(): + r = resource(example('accounts-streaming*.json')) + assert isinstance(r, Chunks) + assert compute(s.amount.sum(), r) == 200 diff --git a/pool/shard001/Python/0012815_PropertyTest.py b/pool/shard001/Python/0012815_PropertyTest.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc0827e8f36e6ecf8ac4d6923a23c47a3a4aeef --- /dev/null +++ b/pool/shard001/Python/0012815_PropertyTest.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import +from PyOpenWorm.pProperty import Property +from .DataTestTemplate import _DataTest + + +class PropertyTest(_DataTest): + def test_one(self): + """ `one` should return None if there isn't a value or just the value if there is one """ + t = T() + self.assertIsNone(t.one()) + t.b = 42 + self.assertEqual(42, t.one()) + + def test_context_getter(self): + p = Property() + self.assertIsNone(p.context) + + def test_values_property(self): + p = Property() + self.assertEquals(p.values, []) + + def test_call_without_arg(self): + t = T() + self.assertIsNone(t()) + t.b = 42 + self.assertEqual(42, t()) + + def test_call_with_arg(self): + t = T() + self.assertIsNone(t()) + n = t(42) + self.assertEquals(n.b, 42) + + +class T(Property): + def __init__(self): + Property.__init__(self) + self.b = None + + def get(self): + if self.b is not None: + yield self.b + yield self.b + + def set(self, b): + self.b = b \ No newline at end of file diff --git a/pool/shard001/Python/0012824_sample4.py b/pool/shard001/Python/0012824_sample4.py new file mode 100644 index 0000000000000000000000000000000000000000..eeda770343fe4583437e8bb2f771e061cd0213ab --- /dev/null +++ b/pool/shard001/Python/0012824_sample4.py @@ -0,0 +1,33 @@ +""" +Lookup sample. +""" +from pyactor.context import set_context, create_host, sleep, shutdown + + +class Echo(object): + _tell = {'echo', 'bye'} + _ask = {'say_something'} + + def echo(self, msg): + print(msg) + + def bye(self): + print("bye") + + def say_something(self): + return "something" + + +if __name__ == '__main__': + set_context() + h = create_host() + e1 = h.spawn('echo1', Echo) + + e = h.lookup('echo1') + print(e.say_something()) + + ee = h.lookup_url("local://local:6666/echo1", Echo) + print(ee.say_something()) + + sleep(1) + shutdown() diff --git a/pool/shard001/Python/0012825_fields.py b/pool/shard001/Python/0012825_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c929ef09d7572fff12cc1b8d995a8fb2da7f88 --- /dev/null +++ b/pool/shard001/Python/0012825_fields.py @@ -0,0 +1,79 @@ +from __future__ import unicode_literals + +import json + +from django.forms import forms +from .models import Contact, ContactGroup, ContactURN, URN + + +class OmniboxWidget(forms.TextInput): + + @classmethod + def get_objects_spec(cls, spec, user): + org = user.get_org() + + group_uuids = [] + contact_uuids = [] + urn_ids = [] + raw_numbers = [] + + item_lists = {'g': group_uuids, 'c': contact_uuids, 'u': urn_ids, 'n': raw_numbers} + + ids = spec.split(",") if spec else [] + for item_id in ids: + item_type, item_id = item_id.split("-", 1) + item_lists[item_type].append(item_id) + + # turn our raw numbers into new contacts with tel URNs for orgs that aren't anonymous + if not org.is_anon: + for number in raw_numbers: + urn = URN.from_tel(number) + contact = Contact.get_or_create(org, user, urns=[urn]) + urn_obj = contact.urn_objects[urn] + urn_ids.append(urn_obj.pk) + + groups = ContactGroup.user_groups.filter(uuid__in=group_uuids, org=org) + contacts = Contact.objects.filter(uuid__in=contact_uuids, org=org, is_active=True) + urns = ContactURN.objects.filter(id__in=urn_ids, org=org) + + return dict(groups=groups, contacts=contacts, urns=urns) + + def set_user(self, user): + self.__dict__['user'] = user + + def render(self, name, value, attrs=None): + value = self.get_json(value) + return super(OmniboxWidget, self).render(name, value, attrs) + + def get_json(self, value): + + if 'user' not in self.__dict__: # pragma: no cover + raise ValueError("Omnibox requires a user, make sure you set one using field.set_user(user) in your form.__init__") + + objects = OmniboxWidget.get_objects_spec(value, self.user) + + selected = [] + for group in objects['groups']: + selected.append(dict(text=group.name, id="g-%s" % group.uuid, contacts=group.contacts.count())) + + for contact in objects['contacts']: + selected.append(dict(text=str(contact), id="c-%s" % contact.uuid)) + + return json.dumps(selected) if selected else None + + +class OmniboxField(forms.Field): + default_error_messages = {} + widget = OmniboxWidget(attrs={"class": "omni_widget", "style": "width:85%"}) + + def __init__(self, **kwargs): + super(OmniboxField, self).__init__(**kwargs) + + def set_user(self, user): + self.user = user + self.widget.set_user(user) + + def to_python(self, value): + if 'user' not in self.__dict__: # pragma: no cover + raise ValueError("Omnibox requires a user, make sure you set one using field.set_user(user) in your form.__init__") + return OmniboxWidget.get_objects_spec(value, self.user) diff --git a/pool/shard001/Python/0012830_main.py b/pool/shard001/Python/0012830_main.py new file mode 100644 index 0000000000000000000000000000000000000000..da6150e738684296d009be8087f79a7b10826ebd --- /dev/null +++ b/pool/shard001/Python/0012830_main.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python + +import Queue +import socket +import threading +import time +import paramiko + +# import custom modules +import util_uploader as uploader +import util_ip_operations as ipop +import module_linux as ml + + +__version__ = "3.4" + +# environment and other stuff +lock = threading.Lock() +q = Queue.Queue() + + + +def remove_stale_ips(ips, name): + rest = uploader.Rest( debug) + fetched_ips = rest.get_device_by_name(name) + ips_to_remove = set(fetched_ips) - set(ips) + if ips_to_remove: + print '\n[*] IPs to remove: %s' % ips_to_remove + for ip in ips_to_remove: + rest.delete_ip(ip) + + +def get_linux_data(ip, usr, pwd): + if mod_linux: + lock.acquire() + print '[+] Collecting data from: %s' % ip + lock.release() + linux = ml.GetLinuxData(ip, ssh_port, timeout, usr, pwd, use_key_file, key_file, + get_serial_info, add_hdd_as_device_properties, add_hdd_as_parts, + get_hardware_info, get_os_details, get_cpu_info, get_memory_info, + ignore_domain, upload_ipv6, give_hostname_precedence, get_dv_install_info, debug) + + data = linux.main() + print "value debug: %s" % debug + if debug: + lock.acquire() + #print '\nLinux data: ' + for rec in data: + print rec + lock.release() + if DICT_OUTPUT: + return data + else: + # Upload ----------- + # upload(data) + print {ip:data} + + +def process_data(data_out, ip, usr, pwd): + msg = str(data_out).lower() + if 'linux' in msg: + lock.acquire() + print '[+] Linux running @ %s ' % ip + lock.release() + data = get_linux_data(ip, usr, pwd) + return data + + else: + lock.acquire() + print '[!] Connected to SSH @ %s, but the OS cannot be determined.' % ip + print '\tInfo: %s\n\tSkipping... ' % str(msg) + lock.release() + return + + +def check_os(ip): + # global success + usr = None + success = False + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + if not use_key_file: + creds = credentials.split(',') + for cred in creds: + if cred not in ('', ' ', '\n'): + try: + usr, pwd = cred.split(':') + except ValueError: + print '\n[!] Error. \n\tPlease check credentials formatting. It should look like user:password\n' + sys.exit() + if not success: + try: + lock.acquire() + print '[*] Connecting to %s:%s as "%s"' % (ip, ssh_port, usr) + lock.release() + ssh.connect(ip, username=usr, password=pwd, timeout=timeout, allow_agent=False, look_for_keys=False) + stdin, stdout, stderr = ssh.exec_command("uname -a") + data_out = stdout.readlines() + if data_out: + success = True + data = process_data(data_out, ip, usr, pwd) + return data + else: + lock.acquire() + print '[!] Connected to SSH @ %s, but the OS cannot be determined. ' % ip + lock.release() + + except paramiko.AuthenticationException: + lock.acquire() + print '[!] Could not authenticate to %s as user "%s"' % (ip, usr) + lock.release() + + except socket.error: + lock.acquire() + print '[!] timeout %s ' % ip + lock.release() + + except Exception, e: + print e + else: + if credentials.lower() in ('none', 'false', 'true'): + print '\n[!] Error!. You must specify user name!' + print '[-] starter.py 192.168.3.102 True ./id_rsa root' + print '[!] Exiting...' + sys.exit() + try: + if ':' in credentials: + usr, pwd = credentials.split(':') + else: + usr = credentials + pwd = None + print '[*] Connecting to %s:%s as "%s" using key file.' % (ip, ssh_port, usr) + ssh.connect(ip, username=usr, key_filename=key_file, timeout=timeout) + stdin, stdout, stderr = ssh.exec_command("uname -a") + data_out = stdout.readlines() + if data_out: + data = process_data(data_out, ip, usr, pwd) + return data + + else: + lock.acquire() + print '[!] Connected to SSH @ %s, but the OS cannot be determined. ' % ip + lock.release() + + except paramiko.AuthenticationException: + lock.acquire() + print '[!] Could not authenticate to %s as user "%s"' % (ip, usr) + lock.release() + + except socket.error: + lock.acquire() + print '[!] timeout %s ' % ip + lock.release() + + except Exception, e: + if str(e) == 'not a valid EC private key file': + print '\n[!] Error: Could not login probably due to the wrong username or key file.' + else: + print e + + +def main(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(float(timeout)) + msg = '\r\n[!] Running %s threads.' % THREADS + print msg + print targets + # parse IP address [single, range or CIDR] + if targets: + ipops = ipop.IPOperations(targets) + scope = ipops.sort_ip() + + # exclude IPs from scope + if exclude_ips: + xops = ipop.IPOperations(exclude_ips) + xscope = xops.sort_ip() + ip_scope = set(scope) - set(xscope) + else: + ip_scope = scope + + if not ip_scope: + msg = '[!] Empty IP address scope! Please, check target IP address[es].' + print msg + sys.exit() + else: + if len(ip_scope) == 1: + q.put(ip_scope[0]) + else: + for ip in ip_scope: + q.put(ip) + while not q.empty(): + tcount = threading.active_count() + if tcount < int(THREADS): + ip = q.get() + p = threading.Thread(target=check_os, args=(str(ip),)) + p.setDaemon(True) + p.start() + else: + time.sleep(0.5) + else: + tcount = threading.active_count() + while tcount > 1: + time.sleep(2) + tcount = threading.active_count() + msg = '[_] Waiting for threads to finish. Current thread count: %s' % str(tcount) + lock.acquire() + print msg + lock.release() + + msg = '\n[!] Done!' + print msg + else: + print "some Error" + + +if __name__ == '__main__': + from module_shared import * + + main() + sys.exit() +else: + # you can use dict_output if called from external script (starter.py) + from module_shared import * diff --git a/pool/shard001/Python/0012835_setup.py b/pool/shard001/Python/0012835_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2cdab18c2caf99ffee6c2c5db08fb79fa0102e05 --- /dev/null +++ b/pool/shard001/Python/0012835_setup.py @@ -0,0 +1,26 @@ +import sys +sys.path.append ('.') + +import setuptools +from distutils.core import setup + +with open ("README", "r") as fh: + long_description = fh.read() + +setup( + name="innermodel_python3", + version="0.0.1", + author="Akash Kumar Singh", + author_email="akashsingh049811@gmail.com", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/ksakash/innermodel-python3", + packages=setuptools.find_packages(), + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: GNU General Public License", + "Operating System :: OS Independent", + ], + python_requires='>=3.6', +) + diff --git a/pool/shard001/Python/0012837_init__.py b/pool/shard001/Python/0012837_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8bb9432b787f644f2b942842f48b5c39274cf3 --- /dev/null +++ b/pool/shard001/Python/0012837_init__.py @@ -0,0 +1,17 @@ +from flask import Flask +from flask_admin import Admin +from flask_mongoengine import MongoEngine + + +def setup(): + app = Flask(__name__) + app.config['SECRET_KEY'] = '1' + app.config['CSRF_ENABLED'] = False + app.config['MONGODB_SETTINGS'] = {'DB': 'tests'} + + db = MongoEngine() + db.init_app(app) + + admin = Admin(app) + + return app, db, admin diff --git a/pool/shard001/Python/0012842_453b49f6b2b8_put_district_field_i.py b/pool/shard001/Python/0012842_453b49f6b2b8_put_district_field_i.py new file mode 100644 index 0000000000000000000000000000000000000000..cc962e5bbf9db5725172c50494c9e8da3687ff1f --- /dev/null +++ b/pool/shard001/Python/0012842_453b49f6b2b8_put_district_field_i.py @@ -0,0 +1,32 @@ +"""Put district field in candidacy table + +Revision ID: 453b49f6b2b8 +Revises: 36c44957687f +Create Date: 2013-05-10 17:17:12.342177 + +""" + +# revision identifiers, used by Alembic. +revision = '453b49f6b2b8' +down_revision = '36c44957687f' + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + + +def upgrade(): + op.add_column('candidacy', sa.Column('district_id', postgresql.ARRAY(sa.String(length=16)), nullable=True)) + op.add_column('candidacy', sa.Column('district', postgresql.ARRAY(sa.Unicode(length=20)), nullable=True)) + op.drop_column('candidacy', u'region3') + op.drop_column('candidacy', u'region2') + op.drop_column('candidacy', u'region1') + + +def downgrade(): + op.add_column('candidacy', sa.Column(u'region1', sa.VARCHAR(length=20))) + op.add_column('candidacy', sa.Column(u'region2', sa.VARCHAR(length=20))) + op.add_column('candidacy', sa.Column(u'region3', sa.VARCHAR(length=4))) + op.drop_column('candidacy', 'district') + op.drop_column('candidacy', 'district_id') + diff --git a/pool/shard001/Python/0012853_thread.py b/pool/shard001/Python/0012853_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..d841c23dd173f72553f7cf7227f333332868ce1e --- /dev/null +++ b/pool/shard001/Python/0012853_thread.py @@ -0,0 +1,113 @@ +# Copyright 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import telemetry.core.timeline.event as timeline_event +import telemetry.core.timeline.tracing.sample as tracing_sample +import telemetry.core.timeline.tracing.slice as tracing_slice + +class Thread(timeline_event.TimelineEvent): + ''' A Thread stores all the trace events collected for a particular + thread. We organize the synchronous slices on a thread by "subrows," where + subrow 0 has all the root slices, subrow 1 those nested 1 deep, and so on. + The asynchronous slices are stored in an AsyncSliceGroup object. + ''' + def __init__(self, process, tid): + super(Thread, self).__init__('thread %s' % tid, 0, 0, parent=process) + self.tid = tid + self._open_slices = [] + self._async_slices = [] + self._samples = [] + + @property + def slices(self): + return self.children + + @property + def samples(self): + return self._samples + + @property + def open_slice_count(self): + return len(self._open_slices) + + @property + def async_slices(self): + return self._async_slices + + def AddSample(self, category, name, timestamp, args=None): + if len(self._samples) and timestamp < self._samples[-1].start: + raise ValueError( + 'Samples must be added in increasing timestamp order') + sample = tracing_sample.Sample( + category, name, timestamp, args=args, parent=self) + self._samples.append(sample) + self.children.append(sample) + + def AddAsyncSlice(self, async_slice): + self._async_slices.append(async_slice) + async_slice.parent = self + self.children.append(async_slice) + + def BeginSlice(self, category, name, timestamp, args=None): + """Opens a new slice for the thread. + Calls to beginSlice and endSlice must be made with + non-monotonically-decreasing timestamps. + + * category: Category to which the slice belongs. + * name: Name of the slice to add. + * timestamp: The timetsamp of the slice, in milliseconds. + * args: Arguments associated with + + Returns newly opened slice + """ + if len(self._open_slices) > 0 and timestamp < self._open_slices[-1].start: + raise ValueError( + 'Slices must be added in increasing timestamp order') + self._open_slices.append( + tracing_slice.Slice(category, name, timestamp, args=args, parent=self)) + + def EndSlice(self, end_timestamp): + """ Ends the last begun slice in this group and pushes it onto the slice + array. + + * end_timestamp: Timestamp when the slice ended in milliseconds + + returns completed slice. + """ + if not len(self._open_slices): + raise ValueError( + 'EndSlice called without an open slice') + curr_slice = self._open_slices.pop() + if end_timestamp < curr_slice.start: + raise ValueError( + 'Slice %s end time is before its start.' % curr_slice.name) + curr_slice.duration = end_timestamp - curr_slice.start + return self.PushSlice(curr_slice) + + def PushSlice(self, new_slice): + self.children.append(new_slice) + return new_slice + + def AutoCloseOpenSlices(self, max_timestamp=None): + if max_timestamp is None: + self.UpdateBounds() + max_timestamp = self.end + while len(self._open_slices) > 0: + curr_slice = self.EndSlice(max_timestamp) + curr_slice.did_not_finish = True + + def IsTimestampValidForBeginOrEnd(self, timestamp): + if not len(self._open_slices): + return True + return timestamp >= self._open_slices[-1].start + + def UpdateBounds(self): + super(Thread, self).UpdateBounds() + + # Take open slices into account for the start and duration of thread event + if len(self._open_slices) > 0: + if not len(self.slices) or self.start > self._open_slices[0].start: + self.start = self._open_slices[0].start + if not len(self.slices) or self.end < self._open_slices[-1].start: + self.duration = self._open_slices[-1].start - self.start diff --git a/pool/shard001/Python/0012855_ActionsFactory.py b/pool/shard001/Python/0012855_ActionsFactory.py new file mode 100644 index 0000000000000000000000000000000000000000..8f80d633f331ce433a1c1f014fca22943db32604 --- /dev/null +++ b/pool/shard001/Python/0012855_ActionsFactory.py @@ -0,0 +1,68 @@ +import gio +import logging +from deskbar.handlers.actions.OpenWithApplicationAction import OpenWithApplicationAction +from deskbar.handlers.actions.CopyToClipboardAction import CopyToClipboardAction +from deskbar.handlers.actions.GoToLocationAction import GoToLocationAction +from deskbar.handlers.actions.SendFileViaEmailAction import SendFileViaEmailAction +from os.path import isdir +from gettext import gettext as _ + +LOGGER = logging.getLogger(__name__) + +def get_actions_for_uri(uri, display_name=None): + """ + Return a list of applications suitable for + the file depending on MIME type + + The default application is not included. + Use the OpenFileAction for that purpose. + + @param uri: Unescaped URI or path of the file + @param display_name: The optional name of + the file for display. + """ + if not uri.startswith("file://"): + gfile = gio.File(path=uri) + else: + gfile = gio.File(uri=uri) + if display_name == None: + display_name = gfile.get_basename() + + # Check if file exists + path = gfile.get_path() + if path == None: + LOGGER.warning("File %s does not exist", uri) + return [] + + # If we have a directory only return one action + if isdir(path): + return [CopyToClipboardAction( _("Location"), gfile.get_path())] + + try: + fileinfo = gfile.query_info("standard::content-type") + except Exception, msg: + LOGGER.error("Could not retrieve content type of %s: %s", gfile.get_path(), msg) + return [] + + actions = [] + + default_appinfo = gio.app_info_get_default_for_type(fileinfo.get_content_type(), True) + for appinfo in gio.app_info_get_all_for_type(fileinfo.get_content_type()): + if default_appinfo == None \ + or appinfo.get_executable() != default_appinfo.get_executable(): + cmd = appinfo.get_executable() + args = [gfile.get_path ()] + + cmd_args = cmd.split(" ") + if len(cmd_args) > 0: + cmd = cmd_args[0] + args = cmd_args[1:] + args + + actions.append( OpenWithApplicationAction(display_name, cmd, args, + display_program_name=appinfo.get_name()) ) + + actions.append( GoToLocationAction(display_name, gfile.get_uri ()) ) + actions.append( SendFileViaEmailAction(display_name, gfile.get_uri ()) ) + actions.append( CopyToClipboardAction( _("URL of %s") % display_name, gfile.get_path ()) ) + + return actions diff --git a/pool/shard001/Python/0012858_autoeditimg.py b/pool/shard001/Python/0012858_autoeditimg.py new file mode 100644 index 0000000000000000000000000000000000000000..16278cfaea317b80559af8d9f8ed6e412d50c446 --- /dev/null +++ b/pool/shard001/Python/0012858_autoeditimg.py @@ -0,0 +1,35 @@ +#!/usr/bin/python2.7 +import os +from PIL import Image + +DATEI_WEB_GROSSE = 700 + +def isimg(isitimg): + ext = os.path.splitext(isitimg)[1].lower() + if ext == ".jpg" or ext == ".png" or ext == ".gif": + return True + return False + +def bearbeiten(datei): + img = Image.open(datei) + wrel = DATEI_WEB_GROSSE / float(img.size[0]) + habs = int( float(img.size[1]) * float(wrel) ) + + splt = os.path.splitext(datei) + newfilename = splt[0] + splt[1].lower() + + img = img.resize((DATEI_WEB_GROSSE, habs), Image.ANTIALIAS) + img.save(newfilename, quality=100, optimize=True, progressive=True) + + if newfilename != datei: + os.rename(newfilename, datei) + +def main(): + files = os.listdir('.') + files = filter(isimg, files) + for f in files: + print f + bearbeiten(f) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard001/Python/0012861_test_0179.py b/pool/shard001/Python/0012861_test_0179.py new file mode 100644 index 0000000000000000000000000000000000000000..3edc34b2c51d69d0102629bac220d5ad7fcea907 --- /dev/null +++ b/pool/shard001/Python/0012861_test_0179.py @@ -0,0 +1,34 @@ +import functools +import unittest + + +def cmp(a, b): + return (a > b) - (a < b) + + +# O(nlog(n)). Sorting +class Solution: + # @param {integer[]} nums + # @return {string} + def largestNumber(self, nums): + nums = [str(num) for num in nums] + + nums.sort(key=functools.cmp_to_key(lambda x, y: cmp(y + x, x + y))) + + result = ''.join(nums).lstrip('0') + return result if result else '0' + + +class Test(unittest.TestCase): + def test(self): + self._test([3, 30, 34, 5, 9], '9534330') + self._test([3, 30, 34, 5, 9, 91], '991534330') + self._test([0, 0], '0') + + def _test(self, nums, expected): + actual = Solution().largestNumber(nums) + self.assertEqual(expected, actual) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0012862_test_wfc_sinkcorr.py b/pool/shard001/Python/0012862_test_wfc_sinkcorr.py new file mode 100644 index 0000000000000000000000000000000000000000..e8805608095777965cc0bb56a6fe4544a5a51ee5 --- /dev/null +++ b/pool/shard001/Python/0012862_test_wfc_sinkcorr.py @@ -0,0 +1,44 @@ +import subprocess +import pytest + +from ..helpers import BaseACS + + +class TestSinkcorr(BaseACS): + """ + Process a single fullframe and a single subarray WFC dataset + using all standard calibration steps with the sink pixel flagging + and no PCTE correction. + """ + detector = 'wfc' + ignore_keywords = ['filename', 'date', 'iraf-tlm', 'fitsdate', + 'opus_ver', 'cal_ver', 'proctime', 'history', + 'bitpix', 'naxis', 'extend', 'simple'] + + def test_fullframe_sinkcorr(self): + """Ported from ``wfc_sinkcorr``, routine test_sinkcorr_fullframe.""" + raw_file = 'jd1y03r5q_raw.fits' + + # Prepare input file. + self.get_input_file(raw_file) + + # Run CALACS + subprocess.call(['calacs.e', raw_file, '-v']) + + # Compare results + outputs = [('jd1y03r5q_flt.fits', 'jd1y03r5q_flt_ref.fits')] + self.compare_outputs(outputs, ignore_keywords_overwrite=TestSinkcorr.ignore_keywords) + + def test_subarray_sinkcorr(self): + """Ported from ``wfc_sinkcorr``, routine test_sinkcorr_subarr.""" + raw_file = 'jd0q13ktq_raw.fits' + + # Prepare input file. + self.get_input_file(raw_file) + + # Run CALACS + subprocess.call(['calacs.e', raw_file, '-v']) + + # Compare results + outputs = [('jd0q13ktq_flt.fits', 'jd0q13ktq_flt_ref.fits')] + self.compare_outputs(outputs, ignore_keywords_overwrite=TestSinkcorr.ignore_keywords) diff --git a/pool/shard001/Python/0012865_jsonfile.py b/pool/shard001/Python/0012865_jsonfile.py new file mode 100644 index 0000000000000000000000000000000000000000..4319b88fd62d54dfc8f6140aaf8fcc0bc543a73b --- /dev/null +++ b/pool/shard001/Python/0012865_jsonfile.py @@ -0,0 +1,64 @@ +# (c) 2014, Brian Coca, Josh Drake, et al +# (c) 2017 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +DOCUMENTATION = ''' + cache: jsonfile + short_description: JSON formatted files. + description: + - This cache uses JSON formatted, per host, files saved to the filesystem. + version_added: "1.9" + author: Ansible Core (@ansible-core) + options: + _uri: + required: True + description: + - Path in which the cache plugin will save the JSON files + type: list + env: + - name: ANSIBLE_CACHE_PLUGIN_CONNECTION + ini: + - key: fact_caching_connection + section: defaults + _prefix: + description: User defined prefix to use when creating the JSON files + env: + - name: ANSIBLE_CACHE_PLUGIN_PREFIX + ini: + - key: fact_caching_prefix + section: defaults + _timeout: + default: 86400 + description: Expiration timeout for the cache plugin data + env: + - name: ANSIBLE_CACHE_PLUGIN_TIMEOUT + ini: + - key: fact_caching_timeout + section: defaults + type: integer +''' + +import codecs +import json + +from ansible.parsing.ajson import AnsibleJSONEncoder, AnsibleJSONDecoder +from ansible.plugins.cache import BaseFileCacheModule + + +class CacheModule(BaseFileCacheModule): + """ + A caching module backed by json files. + """ + + def _load(self, filepath): + # Valid JSON is always UTF-8 encoded. + with codecs.open(filepath, 'r', encoding='utf-8') as f: + return json.load(f, cls=AnsibleJSONDecoder) + + def _dump(self, value, filepath): + with codecs.open(filepath, 'w', encoding='utf-8') as f: + f.write(json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4)) diff --git a/pool/shard001/Python/0012868_Top.py b/pool/shard001/Python/0012868_Top.py new file mode 100644 index 0000000000000000000000000000000000000000..c7c39d9db97aa5cf96d93bf8bea3bbbb23b52680 --- /dev/null +++ b/pool/shard001/Python/0012868_Top.py @@ -0,0 +1,129 @@ +import os +from NN_Models import Reconnet as rnet +from NN_Models import Model_Manager as modelManager +from util import Image_Excel_Wrapper as wrapper +from util import Image_Processor as imp +#from optimization import Genome_Optimizer as gOpt +import numpy as np +def create_excel_files(): + workingDirectory = "" + dirs = ["0. Unstained", "1. Red", "2. Blue", "3. Dual"] + colors = ["uns", "red", "blue", "dual"] + folders = ["BT474_{}_bot left,BT474_{}_bot right,BT474_{}_top left,BT474_{}_top right".format(c, c, c, c).split(',') + for c in colors] + gen = os.walk(workingDirectory) + dirs = next(gen)[1] + for d in dirs: + gen2 = os.walk(''.join([workingDirectory,'/',d])) + directory = ''.join([workingDirectory, '/', d, '/training']) + print(d) + wrapper.cell_images_to_excel(directory) + imageFolders = next(gen2)[1] + for folder in imageFolders: + try: + continue + except: + continue + +def sort_training_samples(): + if not os.path.exists("../training_data"): + os.mkdir("../training_data") + os.mkdir("../training_data/reconnet") + os.mkdir("../training_data/reconnet/cells") + os.mkdir("../training_data/reconnet/non_cells") + + workingDirectory = "" + gen = os.walk(workingDirectory) + dirs = next(gen)[1] + for d in dirs: + gen2 = os.walk(''.join([workingDirectory, '/', d])) + imageFolders = next(gen2)[1] + for folder in imageFolders: + try: + directory = ''.join([workingDirectory, '/', d, '/', folder, '/training']) + print(directory) + wrapper.sort_training_samples(directory) + except: + continue + +def train_model(): + net = rnet.Reconnet(0) + net.load_data() + net.build_model() + net.train() + +def train_single_color_models(): + manager = modelManager.Manager() + manager.train_models() +def find_cell_coordinates(directory): + processedIms = imp.process_dual_wavelength(directory) + imp.save_processed_images_txt(processedIms) +def examine_models(): + from keras.models import load_model + model_file = "reconnet_model_file_" + for i in range(10): + print("/n/n****MODEL {}****/n".format(i)) + model = load_model("data/{}{}{}".format(model_file, i, ".h5")) + print(model.summary()) + +def check_model(model): + import numpy as np + net = rnet.Reconnet(0) + net.load_data() + net.model_file = model + net.build_model(load=True) + xv, yv = net.valData + y1, y2 = yv + acc1 = 0 + acc2 = 0 + print(xv.shape) + for i in range(xv.shape[0]): + x = xv[i] + y = [y1[i], y2[i]] + preds = np.asarray(net.classify(x)) + if np.argmax(preds[0]) == np.argmax(y[0]): + acc1 += 1 + if np.argmax(preds[1]) == np.argmax(y[1]): + acc2 += 1 + acc1 /= xv.shape[0] + acc2 /= xv.shape[0] + print("Acc1: ", acc1) + print("Acc2: ", acc2) + +def evaluate_data(workingDirectory): + net = rnet.Reconnet(0) + net.load_data() + net.model_file = "data/model_0/reconnet_model_0.h5" + net.build_model(load=True) + gen = os.walk(workingDirectory) + dirs = next(gen)[1] + for d in dirs: + directory = ''.join([workingDirectory,'/',d]) + processedImages = imp.process_dual_wavelength(directory) + imp.save_processed_images(processedImages,net) +def optimize_MSER(): + from optimization.targets import MSER_Target as targ + #genome = [[0, 27], [1, 192], [2, 345], [3, 0.47969661370152983], [4, 0.47349351051002975], [5, 721], [6, 6], [7, 0.8067395218562651], [8, 1]] + #target = targ.Target() + #target.build_from_genome(genome) + #target.evaluate() + #opt = gOpt.Optimizer(targ.Target(),1,1) + #opt.run() +""" + On Windows platforms there is no fork() routine, so the multiprocessing library is forced to import + the current module to get access to the worker function. Without the if statement below, the child + process from that import would start its own children which would all import multiprocessing and thus all + call on themselves to start their own children and so on. +""" +#Basically this line is necessary because windows is shit. +if __name__ == '__main__': + #optimize_MSER() + workingDirectory = "" + #find_cell_coordinates(workingDirectory) + #evaluate_data(workingDirectory) + #check_model("data/model_0/reconnet_model_0.h5") + #train_model() + train_single_color_models() + #sort_training_samples() + #create_excel_files() + #wrapper.create_fake_noise_samples('../training_data_method1/background/negative') \ No newline at end of file diff --git a/pool/shard001/Python/0012870_test_M116.py b/pool/shard001/Python/0012870_test_M116.py new file mode 100644 index 0000000000000000000000000000000000000000..3865a1f947eaa159f3d4c01c8134145be38bc071 --- /dev/null +++ b/pool/shard001/Python/0012870_test_M116.py @@ -0,0 +1,61 @@ +from __future__ import absolute_import + +import logging +import mock +from .MockPrinter import MockPrinter + +logging.info = mock.Mock() + + +def mock_sleep(t): + global heaters + for heater in heaters: + if mock_sleep.counter == list(heaters.keys()).index(heater) * 3: + print("{:04d}: Heater {} target reached".format(mock_sleep.counter, heater)) + heaters[heater].is_target_temperature_reached.return_value = True + mock_sleep.counter += 1 + return None + + +class M116_Tests(MockPrinter): + def reset(self): + for heater in self.printer.heaters: + self.printer.heaters[heater] = mock.Mock() + self.printer.heaters[heater].is_target_temperature_reached = mock.Mock(return_value=False) + mock_sleep.counter = -3 + + def setUp(self): + global heaters + heaters = self.printer.heaters + self.reset() + self.printer.processor.execute = mock.Mock() # mock M116's call to M105 + + @mock.patch("redeem.gcodes.M116.time.sleep", side_effect=mock_sleep) + def test_gcodes_M116_no_param(self, m): + print("") + self.execute_gcode("M116") + for heater in heaters: + self.assertTrue(heaters[heater].is_target_temperature_reached()) + + @mock.patch("redeem.gcodes.M116.time.sleep", side_effect=mock_sleep) + def test_gcodes_M116_Pn_Tn(self, m): + + print("HEATERS: ", heaters) + + heater_index_order = [ + 'HBP', + 'E', + 'H', + ] + + for pt in ["P", "T"]: + for heater in heater_index_order: + heater_index = heater_index_order.index(heater) - 1 + self.reset() + g = "M116 {}{}".format(pt, heater_index) + print("\nGCODE: ", g) + self.execute_gcode(g) + + print("Heater {} target reached: {} ".format( + heater, heaters[heater].is_target_temperature_reached())) + self.assertTrue(heaters[heater].is_target_temperature_reached()) diff --git a/pool/shard001/Python/0012873_verify.py b/pool/shard001/Python/0012873_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..22641a0605e5d1ec27430277db15e93ab53877e7 --- /dev/null +++ b/pool/shard001/Python/0012873_verify.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# Prototype database validation script. Same args as abe.py. + +# Copyright(C) 2011 by John Tobey + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public +# License along with this program. If not, see +# . + +import sys +import DataStore +import util +import logging +import readconf + +def verify_tx_merkle_hashes(store, logger, chain_id): + checked, bad = 0, 0 + for block_id, merkle_root, num_tx in store.selectall(""" + SELECT b.block_id, b.block_hashMerkleRoot, b.block_num_tx + FROM block b + JOIN chain_candidate cc ON (b.block_id = cc.block_id) + WHERE cc.chain_id = ?""", (chain_id,)): + merkle_root = store.hashout(merkle_root) + tree = [] + for (tx_hash,) in store.selectall(""" + SELECT tx.tx_hash + FROM block_tx bt + JOIN tx ON (bt.tx_id = tx.tx_id) + WHERE bt.block_id = ? + ORDER BY bt.tx_pos""", (block_id,)): + tree.append(store.hashout(tx_hash)) + if len(tree) != num_tx: + logger.warning("block %d: block_num_tx=%d but found %d", + block_id, num_tx, len(tree)) + root = util.merkle(tree) or DataStore.NULL_HASH + if root != merkle_root: + logger.error("block %d: block_hashMerkleRoot mismatch.", + block_id) + bad += 1 + checked += 1 + if checked % 1000 == 0: + logger.info("%d Merkle trees, %d bad", checked, bad) + if checked % 1000 > 0: + logger.info("%d Merkle trees, %d bad", checked, bad) + return checked, bad + +def main(argv): + logging.basicConfig(level=logging.DEBUG) + args, argv = readconf.parse_argv(argv, DataStore.CONFIG_DEFAULTS, + strict=False) + if argv and argv[0] in ('-h', '--help'): + print "Usage: verify.py --dbtype=MODULE --connect-args=ARGS" + return 0 + store = DataStore.new(args) + logger = logging.getLogger("verify") + checked, bad = 0, 0 + for (chain_id,) in store.selectall(""" + SELECT chain_id FROM chain"""): + logger.info("checking chain %d", chain_id) + checked1, bad1 = verify_tx_merkle_hashes(store, logger, chain_id) + checked += checked1 + bad += bad1 + logger.info("All chains: %d Merkle trees, %d bad", checked, bad) + return bad and 1 + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/pool/shard001/Python/0012874_graph.py b/pool/shard001/Python/0012874_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..e17d33f8b4b50a77f8b895145ca91ea0f4667cba --- /dev/null +++ b/pool/shard001/Python/0012874_graph.py @@ -0,0 +1,105 @@ +############################################################################## +# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/llnl/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License (as +# published by the Free Software Foundation) version 2.1, February 1999. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from __future__ import print_function + +import argparse +import llnl.util.tty as tty + +import spack +import spack.cmd +import spack.store +from spack.spec import * +from spack.dependency import * +from spack.graph import * + +description = "generate graphs of package dependency relationships" +section = "basic" +level = "long" + + +def setup_parser(subparser): + setup_parser.parser = subparser + + method = subparser.add_mutually_exclusive_group() + method.add_argument( + '-a', '--ascii', action='store_true', + help="draw graph as ascii to stdout (default)") + method.add_argument( + '-d', '--dot', action='store_true', + help="generate graph in dot format and print to stdout") + + subparser.add_argument( + '-n', '--normalize', action='store_true', + help="skip concretization; only print normalized spec") + + subparser.add_argument( + '-s', '--static', action='store_true', + help="use static information from packages, not dynamic spec info") + + subparser.add_argument( + '-i', '--installed', action='store_true', + help="graph all installed specs in dot format (implies --dot)") + + subparser.add_argument( + '-t', '--deptype', action='store', + help="comma-separated list of deptypes to traverse. default=%s" + % ','.join(all_deptypes)) + + subparser.add_argument( + 'specs', nargs=argparse.REMAINDER, + help="specs of packages to graph") + + +def graph(parser, args): + concretize = not args.normalize + if args.installed: + if args.specs: + tty.die("Can't specify specs with --installed") + args.dot = True + specs = spack.store.db.query() + + else: + specs = spack.cmd.parse_specs( + args.specs, normalize=True, concretize=concretize) + + if not specs: + setup_parser.parser.print_help() + return 1 + + deptype = all_deptypes + if args.deptype: + deptype = tuple(args.deptype.split(',')) + if deptype == ('all',): + deptype = 'all' + deptype = canonical_deptype(deptype) + + if args.dot: # Dot graph only if asked for. + graph_dot(specs, static=args.static, deptype=deptype) + + elif specs: # ascii is default: user doesn't need to provide it explicitly + graph_ascii(specs[0], debug=spack.debug, deptype=deptype) + for spec in specs[1:]: + print() # extra line bt/w independent graphs + graph_ascii(spec, debug=spack.debug) diff --git a/pool/shard001/Python/0012875_package_version.py b/pool/shard001/Python/0012875_package_version.py new file mode 100644 index 0000000000000000000000000000000000000000..23274fea1ba9fdc1ff24bd5345f4f18ccd47efc6 --- /dev/null +++ b/pool/shard001/Python/0012875_package_version.py @@ -0,0 +1,146 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2012, Willow Garage, Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Willow Garage, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from __future__ import print_function +import datetime +import docutils.core +import os +import re + +from catkin_pkg.changelog_generator import FORTHCOMING_LABEL + + +def _replace_version(package_str, new_version): + """ + replaces the version tag in contents if there is only one instance + + :param package_str: str contents of package.xml + :param new_version: str version number + :returns: str new package.xml + :raises RuntimeError: + """ + # try to replace contens + new_package_str, number_of_subs = re.subn(']*)>[^<>]*', '>%s' % new_version, package_str) + if number_of_subs != 1: + raise RuntimeError('Illegal number of version tags: %s' % (number_of_subs)) + return new_package_str + + +def _check_for_version_comment(package_str, new_version): + """ + checks if a comment is present behind the version tag and return it + + :param package_str: str contents of package.xml + :param version: str version number + :returns: str comment if available, else None + """ + version_tag = '>%s' % new_version + pattern = '%s[ \t]*%s *(.+) *%s' % (re.escape(version_tag), re.escape('')) + comment = re.search(pattern, package_str) + if comment: + comment = comment.group(1) + return comment + + +def update_versions(paths, new_version): + """ + bulk replace of version: searches for package.xml files directly in given folders and replaces version tag within. + + :param paths: list of string, folder names + :param new_version: version string "int.int.int" + :raises RuntimeError: if any one package.xml cannot be updated + """ + files = {} + for path in paths: + package_path = os.path.join(path, 'package.xml') + with open(package_path, 'r') as f: + package_str = f.read() + try: + new_package_str = _replace_version(package_str, new_version) + comment = _check_for_version_comment(new_package_str, new_version) + if comment: + print('NOTE: The package manifest "%s" contains a comment besides the version tag:\n %s' % (path, comment)) + except RuntimeError as rue: + raise RuntimeError('Could not bump version number in file %s: %s' % (package_path, str(rue))) + files[package_path] = new_package_str + # if all replacements successful, write back modified package.xml + for package_path, new_package_str in files.items(): + with open(package_path, 'w') as f: + f.write(new_package_str) + + +def get_forthcoming_label(rst): + document = docutils.core.publish_doctree(rst) + forthcoming_label = None + for child in document.children: + title = None + if isinstance(child, docutils.nodes.subtitle): + title = child + elif isinstance(child, docutils.nodes.section): + section = child + if len(section.children) > 0 and isinstance(section.children[0], docutils.nodes.title): + title = section.children[0] + if title and len(title.children) > 0 and isinstance(title.children[0], docutils.nodes.Text): + title_text = title.children[0].rawsource + if FORTHCOMING_LABEL.lower() in title_text.lower(): + if forthcoming_label: + raise RuntimeError('Found multiple forthcoming sections') + forthcoming_label = title_text + return forthcoming_label + + +def update_changelog_sections(changelogs, new_version): + # rename forthcoming sections to new_version including current date + new_changelog_data = {} + new_label = '%s (%s)' % (new_version, datetime.date.today().isoformat()) + for pkg_name, (changelog_path, changelog, forthcoming_label) in changelogs.items(): + data = rename_section(changelog.rst, forthcoming_label, new_label) + new_changelog_data[changelog_path] = data + + for changelog_path, data in new_changelog_data.items(): + with open(changelog_path, 'wb') as f: + f.write(data.encode('utf-8')) + + +def rename_section(data, old_label, new_label): + valid_section_characters = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + + def replace_section(match): + section_char = match.group(2)[0] + return new_label + '\n' + section_char * len(new_label) + pattern = '^(' + re.escape(old_label) + ')\n([' + re.escape(valid_section_characters) + ']+)$' + data, count = re.subn(pattern, replace_section, data, flags=re.MULTILINE) + if count == 0: + raise RuntimeError('Could not find section') + if count > 1: + raise RuntimeError('Found multiple matching sections') + return data diff --git a/pool/shard001/Python/0012879_test_new_pr_label_hook.py b/pool/shard001/Python/0012879_test_new_pr_label_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..0077b764a59ecbffbd7c86de64d98a04bb204dd9 --- /dev/null +++ b/pool/shard001/Python/0012879_test_new_pr_label_hook.py @@ -0,0 +1,58 @@ +from ghi_assist.hooks.new_pr_label_hook import NewPrLabelHook +from mock import Mock +import json + +def test_no_labels(): + """Test no labels to apply.""" + hook = NewPrLabelHook() + payload = { + "action": "opened", + "issue": { + "labels": [], + }, + "pull_request": { + "body": "foo bar baz", + "issue_url": "http://", + } + } + assert hook.should_perform_action(payload), "No labels: mark as untriaged" + assert hook.actions(payload, Mock())[0]["args"]["labels"] == ["status: untriaged"] + +def test_labels_from_comments(): + """Test with new labels.""" + hook = NewPrLabelHook(whitelist=["foo"]) + payload = { + "action": "opened", + "issue": { + "labels": [], + }, + "pull_request": { + "body": "##foo bar baz", + "issue_url": "http://", + } + } + assert hook.should_perform_action(payload), "Got labels." + assert hook.actions(payload, Mock())[0]["args"]["labels"] == ["foo"] + +def test_invalid_action(): + """Test with action other than "opened".""" + hook = NewPrLabelHook() + payload = { + "action": "closed" + } + assert not hook.should_perform_action(payload), "Not newly opened." + +def test_payload(): + """Test using "real" payload.""" + hook = NewPrLabelHook(whitelist=["foo"]) + payload = get_payload("new_pr_label.json") + assert hook.should_perform_action(payload), "New PR with labels" + assert hook.actions(payload, Mock())[0]["args"] == { + "labels": ["foo"], + "issue_url": "https://api.github.com/repos/user-foo/repo-bar/issues/11", + } + +def get_payload(input_filename): + """Parse the JSON payload and return an object.""" + with open("tests/payloads/" + input_filename) as input_file: + return json.load(input_file) diff --git a/pool/shard001/Python/0012882_test_typechecks.py b/pool/shard001/Python/0012882_test_typechecks.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4ae3505880ee80dc34263701057bd1df489e0c --- /dev/null +++ b/pool/shard001/Python/0012882_test_typechecks.py @@ -0,0 +1,21 @@ +import pytest +import typeguard + +from opentrons_shared_data.deck import load +from opentrons_shared_data.deck.dev_types import ( + DeckDefinitionV1, DeckDefinitionV2 +) + +from . import list_deck_def_paths + + +@pytest.mark.parametrize('defname', list_deck_def_paths(2)) +def test_v2_defs(defname): + defn = load(defname, 2) + typeguard.check_type('defn', defn, DeckDefinitionV2) + + +@pytest.mark.parametrize('defname', list_deck_def_paths(1)) +def test_v1_defs(defname): + defn = load(defname, 1) + typeguard.check_type('defn', defn, DeckDefinitionV1) diff --git a/pool/shard001/Python/0012883_Preprocessing.py b/pool/shard001/Python/0012883_Preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..d70a7a80369202c36199594ec40cee6d4d5d1b6f --- /dev/null +++ b/pool/shard001/Python/0012883_Preprocessing.py @@ -0,0 +1,96 @@ + +# coding: utf-8 + +# In[1]: + +import numpy as np +import pandas as pd +import scipy + + +# In[2]: + +def extract_test_and_train_data(output_train_file, output_test_file): + + # Read the filtered file + df = pd.read_csv('raw/test_rating_filtered.csv') + + # Get a list of all the user ids + users = list(df['user_id'].unique()) + + df_train = pd.DataFrame() + df_test = pd.DataFrame() + count = 0 + for u in users: + df_u = df[df['user_id'] == u] + train_u = df_u.sample(frac=0.8, random_state=200) + test_u = df_u.drop(train_u.index) + df_train = df_train.append(train_u, ignore_index=True) + df_test = df_test.append(test_u, ignore_index=True) + + count += 1 + if count % 100 == 0: + print count + + df_train.to_csv(output_train_file, index=False, encoding='UTF-8') + df_test.to_csv(output_test_file, index=False, encoding='UTF-8') + + +# In[6]: + +def filter_raiting_and_winsorizing(output_filtered): + # Read the original data file + f_rating = 'raw/rating.csv' + df_rating = pd.read_csv(f_rating) + + # Remove the movies watched where the rating is below or equal to 5 + rating_5 = df_rating[df_rating['rating'].isin([-1, 6, 7, 8, 9, 10])] + + # Perform 98% winsorizing + lower_threshold = 0.01 + upper_threshold = 0.99 + + # Get the number of movies watched by each user + users_no_movies = rating_5.groupby('user_id').size().to_frame().sort_values(by=0) + + lower_no_movies = users_no_movies.quantile(lower_threshold).astype(int).values[0] + higher_no_movies = users_no_movies.quantile(upper_threshold).astype(int).values[0] + + # Reindex the dataframe so they have two columns only: user_id and count of movies + users_no_movies.reset_index(inplace=True) + + # If the lower number of movies is below 10, then the cut is performed at 10 + if lower_no_movies < 10: + lower_no_movies = 10 + + # Get the ids of the users that should be kept + users_ids = users_no_movies['user_id'].loc[users_no_movies[0].isin(range(lower_no_movies,higher_no_movies))].astype(int).tolist() + + # Filter the users + user_ratings = rating_5[rating_5['user_id'].isin(users_ids)] + + # Create the filtered data file + user_ratings.to_csv(output_filtered, encoding='UTF-8', index=False) + + +# In[7]: + +print("Filtering started...") +# Filter the original file according to the preprocessing considerations +filter_raiting_and_winsorizing(output_filtered = 'raw/test_rating_filtered.csv') + +print("Filtering done!") + +print("Train/Test split started...") + +# Separate the filtered file into train and test datasets +extract_test_and_train_data(output_train_file = "raw/rating_train.csv", + output_test_file = "raw/rating_test.csv") + +print("Train/Test split done") + + +# In[ ]: + + + diff --git a/pool/shard001/Python/0012892_loopback_test.py b/pool/shard001/Python/0012892_loopback_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a871295ad6fd83f3efdd4c254eb4ad2135a6c1a4 --- /dev/null +++ b/pool/shard001/Python/0012892_loopback_test.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +from __future__ import print_function +import os +import sys +import time +import random +import argparse + +from hexdump import hexdump +from itertools import permutations + +sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) +from panda import Panda + +def get_test_string(): + return b"test"+os.urandom(10) + +def run_test(sleep_duration): + pandas = Panda.list() + print(pandas) + + if len(pandas) == 0: + print("NO PANDAS") + assert False + + if len(pandas) == 1: + # if we only have one on USB, assume the other is on wifi + pandas.append("WIFI") + run_test_w_pandas(pandas, sleep_duration) + +def run_test_w_pandas(pandas, sleep_duration): + h = list(map(lambda x: Panda(x), pandas)) + print("H", h) + + for hh in h: + hh.set_safety_mode(Panda.SAFETY_ALLOUTPUT) + + # test both directions + for ho in permutations(range(len(h)), r=2): + print("***************** TESTING", ho) + + panda0, panda1 = h[ho[0]], h[ho[1]] + + if(panda0._serial == "WIFI"): + print(" *** Can not send can data over wifi panda. Skipping! ***") + continue + + # **** test health packet **** + print("health", ho[0], h[ho[0]].health()) + + # **** test K/L line loopback **** + for bus in [2,3]: + # flush the output + h[ho[1]].kline_drain(bus=bus) + + # send the characters + st = get_test_string() + st = b"\xaa"+chr(len(st)+3).encode()+st + h[ho[0]].kline_send(st, bus=bus, checksum=False) + + # check for receive + ret = h[ho[1]].kline_drain(bus=bus) + + print("ST Data:") + hexdump(st) + print("RET Data:") + hexdump(ret) + assert st == ret + print("K/L pass", bus, ho, "\n") + time.sleep(sleep_duration) + + # **** test can line loopback **** + for bus, gmlan in [(0, False), (1, False), (2, False), (1, True), (2, True)]: + print("\ntest can", bus) + # flush + cans_echo = panda0.can_recv() + cans_loop = panda1.can_recv() + + panda0.set_gmlan(None) + panda1.set_gmlan(None) + + if gmlan is True: + panda0.set_gmlan(bus) + panda1.set_gmlan(bus) + bus = 3 + + # send the characters + at = random.randint(1, 2000) + st = get_test_string()[0:8] + panda0.can_send(at, st, bus) + time.sleep(0.1) + + # check for receive + cans_echo = panda0.can_recv() + cans_loop = panda1.can_recv() + + print("Bus", bus, "echo", cans_echo, "loop", cans_loop) + + assert len(cans_echo) == 1 + assert len(cans_loop) == 1 + + assert cans_echo[0][0] == at + assert cans_loop[0][0] == at + + assert cans_echo[0][2] == st + assert cans_loop[0][2] == st + + assert cans_echo[0][3] == 0x80 | bus + if cans_loop[0][3] != bus: + print("EXPECTED %d GOT %d" % (bus, cans_loop[0][3])) + assert cans_loop[0][3] == bus + + print("CAN pass", bus, ho) + time.sleep(sleep_duration) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-n", type=int, help="Number of test iterations to run") + parser.add_argument("-sleep", type=int, help="Sleep time between tests", default=0) + args = parser.parse_args() + + if args.n is None: + while True: + run_test(sleep_duration=args.sleep) + else: + for i in range(args.n): + run_test(sleep_duration=args.sleep) diff --git a/pool/shard001/Python/0012895_s3_storage.py b/pool/shard001/Python/0012895_s3_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..3fda64a882189cc1b1e08faa378d0a6ac7fee766 --- /dev/null +++ b/pool/shard001/Python/0012895_s3_storage.py @@ -0,0 +1,22 @@ +import json + +from wal_e.blobstore import s3 +from wal_e.storage.base import BackupInfo + + +class S3BackupInfo(BackupInfo): + + def load_detail(self, conn): + if self._details_loaded: + return + + uri = "{scheme}://{bucket}/{path}".format( + scheme=self.layout.scheme, + bucket=self.layout.store_name(), + path=self.layout.basebackup_sentinel(self)) + + data = json.loads(s3.uri_get_file(None, uri, conn=conn)) + for k, v in data.items(): + setattr(self, k, v) + + self._details_loaded = True diff --git a/pool/shard001/Python/0012911_oneshot.py b/pool/shard001/Python/0012911_oneshot.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa4816d14c4dad4c690e78676805748649ca0dc --- /dev/null +++ b/pool/shard001/Python/0012911_oneshot.py @@ -0,0 +1,98 @@ +# This file is part of PyPRP2. +# +# Copyright (C) 2010 PyPRP2 Project Team +# See the file AUTHORS for more info about the team. +# +# PyPRP2 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyPRP2 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PyPRP2. If not, see . + +import bpy +from bpy.props import * +from PyHSPlasma import * + +__has_init = False + +class plOneShotModSettings(bpy.types.IDPropertyGroup): + animation = StringProperty(name="Animation", default="") + seekduration = FloatProperty(name="Seek Duration", default=0.0,soft_min=0) + drivable = BoolProperty(name="Drivable", default=False) + smartseek = BoolProperty(name="Smart Seek", default=False) + reversable = BoolProperty(name="Reversable", default=False) + noseek = BoolProperty(name="No Seek", default=False) + +class OneShotMod(bpy.types.Operator): + bl_idname = 'object.ploneshotmod' + bl_label = 'One Shot' + category = 'Avatar' + + @staticmethod + def Export(rm, so, mod): + OneShotMod.InitProperties(mod) #just re-init them to make sure + oneshotmod = plOneShotMod(mod.name) + oneshotmod.animName = mod.animation + oneshotmod.seekDuration = mod.seekduration + oneshotmod.drivable = mod.drivable + oneshotmod.smartSeek = mod.smartseek + oneshotmod.reversable = mod.reversable + oneshotmod.noSeek = mod.noseek + rm.AddObject(so.key.location, oneshotmod) + so.addModifier(oneshotmod.key) + + def execute(self, context): + ob = context.object + pl = ob.plasma_settings + mod = pl.modifiers.add() + mod.name = ob.name + mod.modclass = OneShotMod.bl_idname.split('.')[1] + mod = bpy.types.plOneShotModSettings(mod) + return {'FINISHED'} + + +class OneShotModPanel(bpy.types.Panel): + bl_space_type = 'PROPERTIES' + bl_region_type = 'WINDOW' + bl_context = 'constraint' + bl_label = 'One Shot Modifier' + + @classmethod + def poll(self, context): + ob = context.active_object + if not ob is None: + pl = ob.plasma_settings + if len(pl.modifiers) > 0: + return pl.modifiers[pl.activemodifier].modclass == OneShotMod.bl_idname.split('.')[1] + return False + + def draw(self, context): + layout = self.layout + + ob = context.active_object + pl = ob.plasma_settings + plmod = pl.modifiers[pl.activemodifier] + + layout.prop(plmod, "animation") + layout.prop(plmod, "seekduration") + + layout.prop(plmod, "drivable") + layout.prop(plmod, "smartseek") + layout.prop(plmod, "reversable") + layout.prop(plmod, "noseek") + +def register(): + bpy.types.register(OneShotMod) + bpy.types.register(OneShotModPanel) + return [OneShotMod] + +def unregister(): + bpy.types.unregister(OneShotMod) + bpy.types.unregister(OneShotModPanel) diff --git a/pool/shard001/Python/0012912_GuoxiCBeam.py b/pool/shard001/Python/0012912_GuoxiCBeam.py new file mode 100644 index 0000000000000000000000000000000000000000..43be56c9f823351fb771909f9e44642f594d8031 --- /dev/null +++ b/pool/shard001/Python/0012912_GuoxiCBeam.py @@ -0,0 +1,221 @@ +# -*- coding: utf-8 -*- +# -*- coding: mbcs -*- + +from abaqus import * +from abaqusConstants import * +from caeModules import * + +from interaction import * +from optimization import * +from sketch import * +from visualization import * +from connectorBehavior import * + +import regionToolset + +#session.journalOptions.setValues(replayGeometry=COORDINATE,recoverGeometry=COORDINATE) + +span=5.0 #span unit:m + +nSpan=8 #number of span + +Gravity = 9.8 #acceleration of gravity + +#----------------------------------------------------- + +# Create a model. + +myModel = mdb.Model(name='cBeamModel') + +#----------------------------------------------------- + +from part import * + +# Create a sketch for the base feature. + +mySketch = myModel.ConstrainedSketch(name='beamSketch',sheetSize=10.0) + +# Create the line. + +mySketch.Line(point1=(0.0, 0.0), point2=(nSpan*span, 0.0)) + +# Create a three-dimensional, deformable part. + +myBeamPart = myModel.Part(name='beamPart', dimensionality=THREE_D, type=DEFORMABLE_BODY) + +# Create the part's base feature +myBeamPart.BaseWire(sketch=mySketch) + +#----------------------------------------------------- + +from material import * + +# Create a material. + +myC50 = myModel.Material(name='Material-C50', description='Concrete C50') + +# Create the elastic properties + +#elasticProperties = (209.E9, 0.28) +#mySteel.Elastic(table=(elasticProperties, ) ) + +#It(umat) seems to be no use in the situation in the "integration=BEFORE_ANALYSIS" + +myC50.Density(table=((2500.0, ), )) +myC50.Elastic(table=((34500000000.0, 0.2), )) #3.45e10N/m^2 + +#------------------------------------------------------- + +from section import * +# Create the beam section. + +myModel.GeneralizedProfile(name='beamProfile', area=3.24, i11=0.153819, i12=0.264036, i22=21.7272, j=0.60, gammaO=0.0, gammaW=0.0) + +myModel.BeamSection(name='beamSection', integration=BEFORE_ANALYSIS, + poissonRatio=0.20, beamShape=CONSTANT, profile='beamProfile', thermalExpansion=OFF, + temperatureDependency=OFF, dependencies=0, table=((34500000000.0, 13800000000.0), ), + alphaDamping=0.0,betaDamping=0.0, compositeDamping=0.0, centroid=(0.0, 0.0), + shearCenter=(0.0, 0.0), consistentMassMatrix=False) + +# Assign the section to the region. The region refers +# to the single cell in this model. + +#mdb.models['Model-1'].parts['Part-1'].SectionAssignment(offset=0.0, +# offsetField='', offsetType=MIDDLE_SURFACE, region= +# mdb.models['Model-1'].parts['Part-1'].sets['Set-1'], sectionName= +# 'Section-1', thicknessAssignment=FROM_SECTION) + +#beamRegion = (myBeamPart.cells,) +beamRegion=regionToolset.Region(edges=myBeamPart.edges) + +myBeamPart.SectionAssignment(region=beamRegion, sectionName='beamSection', + offset=0.0, offsetField='',offsetType=MIDDLE_SURFACE, + thicknessAssignment=FROM_SECTION) + +myModel.parts['beamPart'].assignBeamSectionOrientation(method= + N1_COSINES, n1=(0.0, 0.0, 1.0), region=Region( + edges=myBeamPart.edges.findAt(((0.5, 0.0, 0.0), + ), ((2.5, 0.0, 0.0), ), ))) + +#------------------------------------------------------- + +from assembly import * + +# Create a part instance. +myAssembly = myModel.rootAssembly +myAssembly.DatumCsysByDefault(CARTESIAN) +myInstance = myAssembly.Instance(name='beamInstance', + part=myBeamPart, dependent=OFF) + +#------------------------------------------------------- + +from step import * + +# Create a step. The time period of the static step is 1.0, +# and the initial incrementation is 0.1; the step is created +# after the initial step. + +myModel.StaticStep(name='beamStep', previous='Initial', + nlgeom=OFF, description='Load of the beam.') + +myModel.StaticStep(name='Step-Gravity', previous='beamStep', + minInc=0.001, initialInc=0.2, description='Load of the Gravity.') + + +#------------------------------------------------------- + +from load import * + +#mdb.models['Model-1'].rootAssembly.Set(name='Set-1', vertices= +# mdb.models['Model-1'].rootAssembly.instances['Part-1-1'].vertices.findAt((( +# 0.0, 0.0, 0.0), ))) + +#v=myAssembly.instances('beamInstance').vertices +#verts=v.findAt(((0.0, 0.0, 0.0), ),) + +v=myAssembly.instances['beamInstance'].vertices +verts=v.findAt(((0.0, 0.0, 0.0), ),) +myAssembly.Set(vertices=verts,name='Set-fix1') + +#mdb.models['Model-1'].DisplacementBC(amplitude=UNSET, createStepName='Step-1', +# distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name= +# 'BC-1', region=mdb.models['Model-1'].rootAssembly.sets['Set-1'], u1=0.0, +# u2=0.0, u3=0.0, ur1=0.0, ur2=0.0, ur3=UNSET) + +region=myAssembly.sets['Set-fix1'] + +myModel.DisplacementBC(name='BC-1', createStepName='beamStep', + region=region, u1=0.0, u2=0.0, u3=0.0, ur1=0.0, ur2=0.0, ur3=UNSET, + amplitude=UNSET, fixed=OFF, distributionType=UNIFORM,fieldName='', + localCsys=None) + +#--------------------- +#es=myBeamPart.edges +#e1=es.findAt((1.,0.,0.),) + +#for i in range(2,nSpan+2): +for i in range(2,nSpan+2): + #v=myAssembly.instances['beamInstance'].vertices + #verts=v.findAt((((i-1)*span, 0.0, 0.0), ),) + + #pt=myBeamPart.DatumPointByEdgeParam(edge=e1,parameter=(i-1)*span/(nSpan*span)) + #d=myBeamPart.datums + + verts=v.findAt((((i-1)*span, 0.0, 0.0), ),) + #verts=v.findAt(((40.0, 0.0, 0.0), ),) + + #verts=v.findAt(d[pt.id],) + #myAssembly.Set(vertices=verts,name='Set-fix'+str(i)) + myAssembly.Set(vertices=verts,name='Set-fix'+str(i)) + + region=myAssembly.sets['Set-fix'+str(i)] + + myModel.DisplacementBC(name='BC-' + str(i), createStepName='beamStep', + region=region, u1=UNSET, u2=0.0, u3=0.0, ur1=0.0, ur2=0.0, ur3=UNSET, + amplitude=UNSET, fixed=OFF, distributionType=UNIFORM,fieldName='', + localCsys=None) +#--------------------- + +#mdb.models['Model-1'].rootAssembly.Set(name='Set-3', vertices= +# mdb.models['Model-1'].rootAssembly.instances['Part-1-1'].vertices.findAt((( +# 2.0, 0.0, 0.0), ))) + + +e = myInstance.edges +setGravity = myAssembly.Set(edges=e, name='Set4Gravity') +Load = myModel.Gravity(name='Load-Gravity', + createStepName='Step-Gravity', comp2=-1.0*Gravity, field='', + distributionType=UNIFORM, region=setGravity) + +#------------------------------------------------------- + +from mesh import * + +# Assign an element type to the part instance. +#region = (myInstance.cells,) +#elemType = mesh.ElemType(elemCode=B31, elemLibrary=STANDARD) +#myAssembly.setElementType(regions=region, elemTypes=(elemType,)) + +# Seed the part instance. +myAssembly.seedPartInstance(regions=(myInstance,), size=span/5, + deviationFactor=0.1, minSizeFactor=0.1) + +# Mesh the part instance. +myAssembly.generateMesh(regions=(myInstance,)) + +#------------------------------------------------------- + +myAssembly.regenerate() +#------------------------------------------------------- + +from job import * +# Create an analysis job for the model and submit it. + +jobName='cBeam' + +myJob=mdb.Job(name=jobName, model='cBeamModel') + +myJob.submit(consistencyChecking=OFF) + + +# Save by ldn diff --git a/pool/shard001/Python/0012913_test_timezonemigration.py b/pool/shard001/Python/0012913_test_timezonemigration.py new file mode 100644 index 0000000000000000000000000000000000000000..7e208ed585c0c05f9340a5d3be458a80440f289f --- /dev/null +++ b/pool/shard001/Python/0012913_test_timezonemigration.py @@ -0,0 +1,123 @@ +import os +from django.test import TestCase +from django.test.utils import override_settings +from casexml.apps.case.models import CommCareCase +from casexml.apps.case.tests.util import delete_all_xforms, delete_all_cases +from corehq.util.test_utils import TestFileMixin +from corehq.apps.domain.shortcuts import create_domain +from corehq.apps.hqcase.dbaccessors import get_cases_in_domain +from corehq.apps.receiverwrapper.exceptions import LocalSubmissionError +from corehq.apps.tzmigration.api import set_migration_complete, \ + set_migration_started, TimezoneMigrationProgress, MigrationStatus +from corehq.apps.tzmigration.timezonemigration import \ + run_timezone_migration_for_domain, _run_timezone_migration_for_domain +from corehq.apps.receiverwrapper.util import submit_form_locally +from couchforms.dbaccessors import get_forms_by_type +from couchforms.models import XFormInstance + + +class TimeZoneMigrationTest(TestCase, TestFileMixin): + + file_path = 'data', + root = os.path.dirname(__file__) + + maxDiff = None + + def assertDictEqual(self, d1, d2, msg=None): + k1 = set(d1.keys()) + k2 = set(d2.keys()) + self.assertEqual( + k1, k2, + '{} in first but not in second; {} in second but not in first' + .format(k1 - k2, k2 - k1) + ) + for key in k1: + self.assertEqual(d1[key], d2[key], ( + '{}[{!r}]'.format(msg + ': ' if msg else '', key) + )) + + def setUp(self): + super(TimeZoneMigrationTest, self).setUp() + self.domain = 'foo' + self.domain_object = create_domain(self.domain) + tzp, _ = TimezoneMigrationProgress.objects.get_or_create(pk=self.domain) + tzp.migration_status = MigrationStatus.NOT_STARTED + tzp.save() + + def tearDown(self): + delete_all_xforms() + delete_all_cases() + self.domain_object.delete() + TimezoneMigrationProgress.objects.all().delete() + super(TimeZoneMigrationTest, self).tearDown() + + def _compare_forms(self, actual_json, expected_json, msg): + expected_json.update({ + 'domain': self.domain, + 'received_on': actual_json['received_on'], + '_rev': actual_json['_rev'], + 'initial_processing_complete': True, + '#export_tag': actual_json['#export_tag'], + 'auth_context': actual_json['auth_context'], + }) + for name, meta in actual_json.get("external_blobs", {}).iteritems(): + expected_json["external_blobs"][name]["id"] = meta["id"] + expected_json = XFormInstance.wrap(expected_json).to_json() + self.assertDictEqual(actual_json, expected_json, msg) + + def _compare_cases(self, actual_json, expected_json, msg): + expected_json.update({ + 'domain': self.domain, + '_rev': actual_json['_rev'], + 'initial_processing_complete': True, + '#export_tag': actual_json['#export_tag'], + 'server_modified_on': actual_json['server_modified_on'] + }) + for expected_action, actual_action in zip(expected_json['actions'], actual_json['actions']): + expected_action['server_date'] = actual_action['server_date'] + + expected_json = CommCareCase.wrap(expected_json).to_json() + self.assertDictEqual(actual_json, expected_json, msg) + + def test_migration(self): + xform = self.get_xml('form') + form_bad_tz = self.get_json('form') + case_bad_tz = self.get_json('case') + form_good_tz = self.get_json('form-tz') + case_good_tz = self.get_json('case-tz') + with override_settings(PHONE_TIMEZONES_HAVE_BEEN_PROCESSED=False, + PHONE_TIMEZONES_SHOULD_BE_PROCESSED=False): + submit_form_locally(xform, self.domain) + + # Form before + xform_instance, = get_forms_by_type(self.domain, 'XFormInstance', limit=10) + xform_json = xform_instance.to_json() + self._compare_forms(xform_json, form_bad_tz, + "Form before migration does not match") + + # Case before + case, = get_cases_in_domain(self.domain) + self._compare_cases(case.to_json(), case_bad_tz, + "Case before migration does not match") + run_timezone_migration_for_domain(self.domain) + + # Form after + xform_instance, = get_forms_by_type(self.domain, 'XFormInstance', limit=10) + xform_json = xform_instance.to_json() + self._compare_forms(xform_json, form_good_tz, + "Form after migration does not match") + + # Case after + case, = get_cases_in_domain(self.domain) + self._compare_cases(case.to_json(), case_good_tz, + "Case after migration does not match") + + def test_pause(self): + xform = self.get_xml('form') + set_migration_started(self.domain) + with self.assertRaisesRegexp(LocalSubmissionError, 'status code 503'): + submit_form_locally(xform, self.domain) + _run_timezone_migration_for_domain(self.domain) + set_migration_complete(self.domain) + # no issue + submit_form_locally(xform, self.domain) diff --git a/pool/shard001/Python/0012920_bridge_stats.py b/pool/shard001/Python/0012920_bridge_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..248d5e081cf54141aa39c29a1418672eaca433ac --- /dev/null +++ b/pool/shard001/Python/0012920_bridge_stats.py @@ -0,0 +1,199 @@ +# +# Copyright (c) 2008-2015 Citrix Systems, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License") +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource +from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response +from nssrc.com.citrix.netscaler.nitro.service.options import options +from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception + +from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util + +class bridge_stats(base_resource) : + """ Statistics for bridge resource. + """ + def __init__(self) : + self._clearstats = "" + self._tcptotbdgmacmoved = 0 + self._tcpbdgmacmovedrate = 0 + self._tcptotbdgcollisions = 0 + self._tcpbdgcollisionsrate = 0 + self._tcperrbdgmuted = 0 + self._tcperrbdgmutedrate = 0 + self._totbdgpkts = 0 + self._bdgpktsrate = 0 + self._totbdgmbits = 0 + self._bdgmbitsrate = 0 + + @property + def clearstats(self) : + """Clear the statsistics / counters.
Possible values = basic, full. + """ + try : + return self._clearstats + except Exception as e: + raise e + + @clearstats.setter + def clearstats(self, clearstats) : + """Clear the statsistics / counters + """ + try : + self._clearstats = clearstats + except Exception as e: + raise e + + @property + def tcpbdgcollisionsrate(self) : + """Rate (/s) counter for tcptotbdgcollisions. + """ + try : + return self._tcpbdgcollisionsrate + except Exception as e: + raise e + + @property + def tcptotbdgcollisions(self) : + """The number of bridging table collisions. + """ + try : + return self._tcptotbdgcollisions + except Exception as e: + raise e + + @property + def bdgpktsrate(self) : + """Rate (/s) counter for totbdgpkts. + """ + try : + return self._bdgpktsrate + except Exception as e: + raise e + + @property + def totbdgmbits(self) : + """The total number of bridged Mbits. + """ + try : + return self._totbdgmbits + except Exception as e: + raise e + + @property + def tcperrbdgmutedrate(self) : + """Rate (/s) counter for tcperrbdgmuted. + """ + try : + return self._tcperrbdgmutedrate + except Exception as e: + raise e + + @property + def tcpbdgmacmovedrate(self) : + """Rate (/s) counter for tcptotbdgmacmoved. + """ + try : + return self._tcpbdgmacmovedrate + except Exception as e: + raise e + + @property + def bdgmbitsrate(self) : + """Rate (/s) counter for totbdgmbits. + """ + try : + return self._bdgmbitsrate + except Exception as e: + raise e + + @property + def totbdgpkts(self) : + """The total number of bridged packets. + """ + try : + return self._totbdgpkts + except Exception as e: + raise e + + @property + def tcperrbdgmuted(self) : + """The number of bridging related interface mutes. + """ + try : + return self._tcperrbdgmuted + except Exception as e: + raise e + + @property + def tcptotbdgmacmoved(self) : + """The number of times bridging registered MAC moved. + """ + try : + return self._tcptotbdgmacmoved + except Exception as e: + raise e + + def _get_nitro_response(self, service, response) : + """ converts nitro response into object and returns the object array in case of get request. + """ + try : + result = service.payload_formatter.string_to_resource(bridge_response, response, self.__class__.__name__.replace('_stats','')) + if(result.errorcode != 0) : + if (result.errorcode == 444) : + service.clear_session(self) + if result.severity : + if (result.severity == "ERROR") : + raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) + else : + raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) + return result.bridge + except Exception as e : + raise e + + def _get_object_name(self) : + """ Returns the value of object identifier argument + """ + try : + return None + except Exception as e : + raise e + + + + @classmethod + def get(cls, service, name="", option_="") : + """ Use this API to fetch the statistics of all bridge_stats resources that are configured on netscaler. + """ + try : + obj = bridge_stats() + if not name : + response = obj.stat_resources(service, option_) + return response + except Exception as e: + raise e + + class Clearstats: + basic = "basic" + full = "full" + +class bridge_response(base_response) : + def __init__(self, length=1) : + self.bridge = [] + self.errorcode = 0 + self.message = "" + self.severity = "" + self.sessionid = "" + self.bridge = [bridge_stats() for _ in range(length)] + diff --git a/pool/shard001/Python/0012921_admin.py b/pool/shard001/Python/0012921_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..70b4d34efd097d3eced36a7a53e67824808b433b --- /dev/null +++ b/pool/shard001/Python/0012921_admin.py @@ -0,0 +1,32 @@ +#This file activates and customizes the backend admin site for the ACTIVITIES app. + +from django.contrib import admin +from activities.models import Assignment, AssignmentTitle, AssignmentType + +from citations.models import Validation +from django.contrib.contenttypes.admin import GenericStackedInline + +class ValidationInline(GenericStackedInline): + + model = Validation + extra = 0 + +class AssignmentAdmin(admin.ModelAdmin): + fields = ('id', 'individual', 'assignment_title', 'location', ('start_year', 'start_certain'), ('end_year', 'end_certain'), 'notes') + inlines = [ValidationInline] + search_fields = ['individual__name', 'assignment_title__name', 'location__name', 'notes'] + list_display = ('individual', 'assignment_title', 'location', 'start_year', 'end_year') + readonly_fields = ['id'] + ordering = ('start_year', 'end_year',) +admin.site.register(Assignment, AssignmentAdmin) + +class AssignmentTitleAdmin(admin.ModelAdmin): + search_fields = ['name', 'notes'] + readonly_fields = ['id'] + list_display = ('name', 'assignment_type') + ordering = ('name',) +admin.site.register(AssignmentTitle, AssignmentTitleAdmin) + +class AssignmentTypeAdmin(admin.ModelAdmin): + ordering = ('name',) +admin.site.register(AssignmentType) \ No newline at end of file diff --git a/pool/shard001/Python/0012923_serial_command_sender.py b/pool/shard001/Python/0012923_serial_command_sender.py new file mode 100644 index 0000000000000000000000000000000000000000..7135baf950a25fa5b336c2b22a2d68f24245e3a6 --- /dev/null +++ b/pool/shard001/Python/0012923_serial_command_sender.py @@ -0,0 +1,70 @@ +# Under MIT License, see LICENSE.txt +import time +from collections import deque + +from RULEngine.Command.command import * + + +COMMUNICATION_SLEEP = 0.001 +MOVE_COMMAND_SLEEP = 0.05 + + +class SerialCommandSender(object): + def __init__(self): + self.mcu_com = McuCommunicator(timeout=0.1) + + self.last_time = 0 + self.command_queue = deque() + + self.command_dict = {0: Stop(OurPlayer(None, 0)), 1: Stop(OurPlayer(None, 1)), 2: Stop(OurPlayer(None, 2)), + 3: Stop(OurPlayer(None, 3)), 4: Stop(OurPlayer(None, 4)), 5: Stop(OurPlayer(None, 5))} + + self.terminate = threading.Event() + self.comm_thread = threading.Thread(target=self.send_loop) + self.comm_thread.start() + + def send_loop(self): + while not self.terminate.is_set(): + if time.time() - self.last_time > MOVE_COMMAND_SLEEP: + for next_command in self.command_dict.values(): + # print(c) + self._package_commands(next_command) + time.sleep(COMMUNICATION_SLEEP) + self.last_time = time.time() + else: + time.sleep(COMMUNICATION_SLEEP) + try: + next_command = self.command_queue.popleft() + except IndexError: + next_command = None + if next_command: + self._package_commands(next_command) + + def send_command(self, command: Command): + # self.command_queue.append(command) + # print("({}) Command deque length: {}".format(time.time(), len(self.command_queue))) + + if isinstance(command, Move) or isinstance(command, Stop): + self.command_dict[command.player.id] = command + else: + self.command_queue.append(command) + + def send_responding_command(self, command: ResponseCommand): + """ + Pause le thread appelant jusqu'à qu'une réponse est reçu + """ + self.command_queue.append(command) + command.pause_thread() + + return command.response + + def stop(self): + self.terminate.set() + self.comm_thread.join() + + def _package_commands(self, command: Command): + response = command.package_command(self.mcu_com) + + if isinstance(command, ResponseCommand): + command.response = response + command.wakeup_thread() diff --git a/pool/shard001/Python/0012925_ec2_eni_facts.py b/pool/shard001/Python/0012925_ec2_eni_facts.py new file mode 100644 index 0000000000000000000000000000000000000000..981358c33afb174c359e7ecc175578abbfd53068 --- /dev/null +++ b/pool/shard001/Python/0012925_ec2_eni_facts.py @@ -0,0 +1,135 @@ +#!/usr/bin/python +# +# This is a free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This Ansible library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this library. If not, see . + +DOCUMENTATION = ''' +--- +module: ec2_eni_facts +short_description: Gather facts about ec2 ENI interfaces in AWS +description: + - Gather facts about ec2 ENI interfaces in AWS +version_added: "2.0" +author: "Rob White (@wimnat)" +options: + eni_id: + description: + - The ID of the ENI. Pass this option to gather facts about a particular ENI, otherwise, all ENIs are returned. + required: false + default: null +extends_documentation_fragment: aws +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +# Gather facts about all ENIs +- ec2_eni_facts: + +# Gather facts about a particular ENI +- ec2_eni_facts: + eni_id: eni-xxxxxxx + +''' + +import xml.etree.ElementTree as ET + +try: + import boto.ec2 + from boto.exception import BotoServerError + HAS_BOTO = True +except ImportError: + HAS_BOTO = False + + +def get_error_message(xml_string): + + root = ET.fromstring(xml_string) + for message in root.findall('.//Message'): + return message.text + + +def get_eni_info(interface): + + interface_info = {'id': interface.id, + 'subnet_id': interface.subnet_id, + 'vpc_id': interface.vpc_id, + 'description': interface.description, + 'owner_id': interface.owner_id, + 'status': interface.status, + 'mac_address': interface.mac_address, + 'private_ip_address': interface.private_ip_address, + 'source_dest_check': interface.source_dest_check, + 'groups': dict((group.id, group.name) for group in interface.groups), + } + + if interface.attachment is not None: + interface_info['attachment'] = {'attachment_id': interface.attachment.id, + 'instance_id': interface.attachment.instance_id, + 'device_index': interface.attachment.device_index, + 'status': interface.attachment.status, + 'attach_time': interface.attachment.attach_time, + 'delete_on_termination': interface.attachment.delete_on_termination, + } + + return interface_info + + +def list_eni(connection, module): + + eni_id = module.params.get("eni_id") + interface_dict_array = [] + + try: + all_eni = connection.get_all_network_interfaces(eni_id) + except BotoServerError as e: + module.fail_json(msg=get_error_message(e.args[2])) + + for interface in all_eni: + interface_dict_array.append(get_eni_info(interface)) + + module.exit_json(interfaces=interface_dict_array) + + +def main(): + argument_spec = ec2_argument_spec() + argument_spec.update( + dict( + eni_id = dict(default=None) + ) + ) + + module = AnsibleModule(argument_spec=argument_spec) + + if not HAS_BOTO: + module.fail_json(msg='boto required for this module') + + region, ec2_url, aws_connect_params = get_aws_connection_info(module) + + if region: + try: + connection = connect_to_aws(boto.ec2, region, **aws_connect_params) + except (boto.exception.NoAuthHandlerFound, StandardError), e: + module.fail_json(msg=str(e)) + else: + module.fail_json(msg="region must be specified") + + list_eni(connection, module) + +from ansible.module_utils.basic import * +from ansible.module_utils.ec2 import * + +# this is magic, see lib/ansible/module_common.py +#<> + +main() diff --git a/pool/shard001/Python/0012929_init__.py b/pool/shard001/Python/0012929_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a35a1b5e6ba8f708c808e41b82b2ed8df244b010 --- /dev/null +++ b/pool/shard001/Python/0012929_init__.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import tarfile +import requests +import io +import os +import shutil +import subprocess +import cli_common.utils +import taskcluster + +from cli_common.log import get_logger +from static_analysis_bot.config import settings +from static_analysis_bot import AnalysisException + + +logger = get_logger(__name__) + +ANDROID_MOZCONFIG = '''# Build Firefox for Android: +ac_add_options --enable-application=mobile/android +ac_add_options --target=arm-linux-androideabi + +# With the following Android SDK and NDK: +ac_add_options --with-android-sdk="{mozbuild}/android-sdk-linux/android-sdk-linux" +ac_add_options --with-android-ndk="{mozbuild}/android-ndk/android-ndk"''' + +GRADLE_PROPERTIES = ''' +// Per https://docs.gradle.org/current/userguide/build_environment.html, this +// overrides the gradle.properties in topsrcdir. +org.gradle.daemon=false +''' + + +def setup(index, job_name='linux64-infer', revision='latest', + artifact='public/build/infer.tar.xz'): + ''' + Setup Taskcluster infer build for static-analysis + Defaults values are from https://dxr.mozilla.org/mozilla-central/source/taskcluster/ci/toolchain/linux.yml + - Download the artifact from latest Taskcluster build + - Extracts it into the MOZBUILD_STATE_PATH as expected by mach + ''' + if job_name == 'linux64-infer': + jobs = [ + { + 'job-name': 'linux64-infer', + 'artifact': 'public/build/infer.tar.xz', + 'namespace': 'gecko.v2.autoland.latest.static-analysis.linux64-infer' + }, + { + 'job-name': 'linux64-android-sdk-linux-repack', + 'artifact': 'project/gecko/android-sdk/android-sdk-linux.tar.xz', + 'namespace': 'gecko.cache.level-1.toolchains.v2.linux64-android-sdk-linux-repack.latest' + }, + { + 'job-name': 'linux64-android-ndk-linux-repack', + 'artifact': 'project/gecko/android-ndk/android-ndk.tar.xz', + 'namespace': 'gecko.cache.level-1.toolchains.v2.linux64-android-ndk-linux-repack.latest' + } + ] + + for element in jobs: + namespace = element['namespace'] + artifact = element['artifact'] + # on staging buildSignedUrl will fail, because the artifacts are downloaded from + # a proxy, therefore we need to use buildUrl in case the signed version fails + try: + artifact_url = index.buildSignedUrl('findArtifactFromTask', + indexPath=namespace, + name=artifact, + expiration=7200) + except taskcluster.exceptions.TaskclusterAuthFailure: + artifact_url = index.buildUrl('findArtifactFromTask', + indexPath=namespace, + name=artifact) + target = os.path.join( + os.environ['MOZBUILD_STATE_PATH'], + os.path.basename(artifact).split('.')[0], + ) + logger.info('Downloading {}.'.format(artifact)) + cli_common.utils.retry(lambda: download(artifact_url, target)) + if not os.path.exists(target): + raise AnalysisException('artifact', 'Setup failed for {}'.format(target)) + + +def download(artifact_url, target): + # Download Taskcluster archive + resp = requests.get(artifact_url, stream=True) + resp.raise_for_status() + + # Extract archive into destination + with tarfile.open(fileobj=io.BytesIO(resp.content)) as tar: + tar.extractall(target) + + +class AndroidConfig(): + def __enter__(self): + # we copy the old mozconfig into the repository, so that we can + # enable the android build + self.__android_mozconfig = os.path.join(settings.repo_dir, 'mozconfig') + self.__old_config = os.getenv('MOZCONFIG') + shutil.copy(self.__old_config, self.__android_mozconfig) + os.environ['MOZCONFIG'] = self.__android_mozconfig + subprocess.run(['chmod', 'u+w', self.__android_mozconfig]) + with open(self.__android_mozconfig, 'a') as f: + f.write(ANDROID_MOZCONFIG.format( + mozbuild=os.environ['MOZBUILD_STATE_PATH'])) + + # set GRADLE_USER_HOME as it is needed for Gradle to use sane paths. + gradle_home_dir = os.path.join( + os.environ['MOZBUILD_STATE_PATH'], 'gradle') + if not os.path.exists(gradle_home_dir): + os.makedirs(gradle_home_dir) + logger.info('Setting GRADLE_USER_HOME to {}.'.format(gradle_home_dir)) + os.environ['GRADLE_USER_HOME'] = gradle_home_dir + + # Create the gradle.properties file and add the necessary flags + with open(os.path.join(gradle_home_dir, 'gradle.properties'), 'a') as f: + f.write(GRADLE_PROPERTIES) + + def __exit__(self, type, value, traceback): + os.environ['MOZCONFIG'] = self.__old_config + os.remove(self.__android_mozconfig) diff --git a/pool/shard001/Python/0012938_day02_b.py b/pool/shard001/Python/0012938_day02_b.py new file mode 100644 index 0000000000000000000000000000000000000000..d415a6552248c24eb84339e3c5c890d20cf81e36 --- /dev/null +++ b/pool/shard001/Python/0012938_day02_b.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python2.7 +## Advent of code 2016, AoC day 2 puzzle 2 +## This solution (python2.7) by kannix68, @ 2016-12-02. + +def assert_msg(msg, assertion): + assert assertion, "ERROR on assert: {}".format(msg) + print "assert-OK: {}".format(msg) + +def invert_dict(indict): + outdict = {} + for key, val in indict.iteritems(): + outdict[val] = key + return outdict + +def process(input): + output = "" + pos = "5" + for line in input: # iterate lines + for char in line: # iterate chars in line + pos = moves.get(char).get(pos, pos) # move to new position on valid move, else stay + output += pos + return output + +moves_r = {"2":"3", "3":"4", "5":"6", "6":"7", "7":"8", "8":"9", "A":"B", "B":"C"} # "R" moves +moves_l = invert_dict(moves_r) # "L" moves, is "R" inverted +moves_u = {"A":"6", "6":"2", "D":"B", "B":"7", "7":"3", "3":"1", "C":"8", "8":"4"} # "U" moves +moves_d = invert_dict(moves_u) # "D" moves, is "U" inverted +moves = { "R": moves_r, "L": moves_l, "U": moves_u, "D": moves_d, } + +## MAIN + +input = ''' +ULL +RRDDD +LURDL +UUUUD +'''.strip() # test data + +print("input " + input) +data = input.splitlines() +result = process(data) +assert_msg("result = {}".format("5DB3"), result == "5DB3") # asser test data + +infile = open("day02_data.txt", "r") # challenge data +input = infile.read() +data = input.splitlines() +result = process(data) +print("result for fileinput = {}; inp={}".format(result, input)) # show challenge solution result diff --git a/pool/shard001/Python/0012940_nodeview_space_menu.py b/pool/shard001/Python/0012940_nodeview_space_menu.py new file mode 100644 index 0000000000000000000000000000000000000000..d74393870d6bb011d1d279c11a9e854723c2896c --- /dev/null +++ b/pool/shard001/Python/0012940_nodeview_space_menu.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +''' +zeffii 2014. + +borrows heavily from insights provided by Dynamic Space Bar! +but massively condensed for sanity. +''' + +import bpy + +import sverchok +from sverchok.menu import make_node_cats +from sverchok.ui.sv_icons import custom_icon +# from nodeitems_utils import _node_categories + +sv_tree_types = {'SverchCustomTreeType', 'SverchGroupTreeType'} +node_cats = make_node_cats() +addon_name = sverchok.__name__ +menu_prefs = {} + +# _items_to_remove = {} + +def get_icon_switch(): + addon = bpy.context.user_preferences.addons.get(addon_name) + + if addon and hasattr(addon, "preferences"): + return addon.preferences.show_icons + + +def icon(display_icon): + '''returns empty dict if show_icons is False, else the icon passed''' + kws = {} + if menu_prefs.get('show_icons'): + if display_icon.startswith('SV_'): + kws = {'icon_value': custom_icon(display_icon)} + else: + kws = {'icon': display_icon} + return kws + + +def node_icon(node_ref): + '''returns empty dict if show_icons is False, else the icon passed''' + if not menu_prefs.get('show_icons'): + return {} + else: + if hasattr(node_ref, 'sv_icon'): + iconID = custom_icon(node_ref.sv_icon) + return {'icon_value': iconID} if iconID else {} + elif hasattr(node_ref, 'bl_icon') and node_ref.bl_icon != 'OUTLINER_OB_EMPTY': + iconID = node_ref.bl_icon + return {'icon': iconID} if iconID else {} + else: + return {} + + +def layout_draw_categories(layout, node_details): + + add_n_grab = 'node.add_node' + for node_info in node_details: + + if node_info[0] == 'separator': + layout.separator() + continue + + if not node_info: + print(repr(node_info), 'is incomplete, or unparsable') + continue + + bl_idname = node_info[0] + node_ref = getattr(bpy.types, bl_idname) + + if hasattr(node_ref, "bl_label"): + layout_params = dict(text=node_ref.bl_label, **node_icon(node_ref)) + elif bl_idname == 'NodeReroute': + layout_params = dict(text='Reroute') + else: + continue + + node_op = layout.operator(add_n_grab, **layout_params) + node_op.type = bl_idname + node_op.use_transform = True + + +# does not get registered +class NodeViewMenuTemplate(bpy.types.Menu): + bl_label = "" + + def draw(self, context): + layout_draw_categories(self.layout, node_cats[self.bl_label]) + # prop_menu_enum(data, property, text="", text_ctxt="", icon='NONE') + + +# quick class factory. +def make_class(name, bl_label): + name = 'NODEVIEW_MT_Add' + name + return type(name, (NodeViewMenuTemplate,), {'bl_label': bl_label}) + + +class NODEVIEW_MT_Dynamic_Menu(bpy.types.Menu): + bl_label = "Sverchok Nodes" + + @classmethod + def poll(cls, context): + tree_type = context.space_data.tree_type + if tree_type in sv_tree_types: + menu_prefs['show_icons'] = get_icon_switch() + # print('showing', menu_prefs['show_icons']) + return True + + def draw(self, context): + + # dont show up in other tree menu (needed because we bypassed poll by appending manually) + tree_type = context.space_data.tree_type + if not tree_type in sv_tree_types: + return + + layout = self.layout + layout.operator_context = 'INVOKE_REGION_WIN' + + if self.bl_idname == 'NODEVIEW_MT_Dynamic_Menu': + layout.operator("node.sv_extra_search", text="Search", icon='OUTLINER_DATA_FONT') + + + layout.separator() + layout.menu("NODEVIEW_MT_AddGenerators", **icon('OBJECT_DATAMODE')) + layout.menu("NODEVIEW_MT_AddTransforms", **icon('MANIPUL')) + layout.menu("NODEVIEW_MT_AddAnalyzers", **icon('VIEWZOOM')) + layout.menu("NODEVIEW_MT_AddModifiers", **icon('MODIFIER')) + layout.separator() + layout.menu("NODEVIEW_MT_AddNumber") + layout.menu("NODEVIEW_MT_AddVector") + layout.menu("NODEVIEW_MT_AddMatrix") + layout.menu("NODEVIEW_MT_AddLogic", **icon("SV_LOGIC")) + layout.menu("NODEVIEW_MT_AddListOps", **icon('NLA')) + layout.separator() + layout.menu("NODEVIEW_MT_AddViz", **icon('RESTRICT_VIEW_OFF')) + layout.menu("NODEVIEW_MT_AddText") + layout.menu("NODEVIEW_MT_AddScene", **icon('SCENE_DATA')) + layout.menu("NODEVIEW_MT_AddLayout", **icon("SV_LAYOUT")) + layout.menu("NODE_MT_category_SVERCHOK_BPY_Data", icon="BLENDER") + layout.separator() + layout.menu("NODEVIEW_MT_AddNetwork", **icon("OOPS")) + layout.menu("NODEVIEW_MT_AddBetas", **icon("SV_BETA")) + layout.menu("NODEVIEW_MT_AddAlphas", **icon("SV_ALPHA")) + layout.separator() + layout.menu("NODE_MT_category_SVERCHOK_GROUPS", icon="RNA") + + +class NODEVIEW_MT_AddGenerators(bpy.types.Menu): + bl_label = "Generators" + + def draw(self, context): + layout = self.layout + layout_draw_categories(self.layout, node_cats[self.bl_label]) + layout.menu("NODEVIEW_MT_AddGeneratorsExt", **icon('PLUGIN')) + + +class NODEVIEW_MT_AddModifiers(bpy.types.Menu): + bl_label = "Modifiers" + + def draw(self, context): + layout = self.layout + layout.menu("NODEVIEW_MT_AddModifierChange") + layout.menu("NODEVIEW_MT_AddModifierMake") + + +class NODEVIEW_MT_AddListOps(bpy.types.Menu): + bl_label = "List" + + def draw(self, context): + layout = self.layout + layout.menu("NODEVIEW_MT_AddListmain") + layout.menu("NODEVIEW_MT_AddListstruct") + layout_draw_categories(self.layout, node_cats["List Masks"]) + layout_draw_categories(self.layout, node_cats["List Mutators"]) + + +classes = [ + NODEVIEW_MT_Dynamic_Menu, + NODEVIEW_MT_AddListOps, + NODEVIEW_MT_AddModifiers, + NODEVIEW_MT_AddGenerators, + # like magic. + # make | NODEVIEW_MT_Add + class name , menu name + make_class('GeneratorsExt', "Generators Extended"), + make_class('Transforms', "Transforms"), + make_class('Analyzers', "Analyzers"), + make_class('Viz', "Viz"), + make_class('Text', "Text"), + make_class('Scene', "Scene"), + make_class('Layout', "Layout"), + make_class('Listmain', "List Main"), + make_class('Liststruct', "List Struct"), + make_class('Number', "Number"), + make_class('Vector', "Vector"), + make_class('Matrix', "Matrix"), + make_class('ModifierChange', "Modifier Change"), + make_class('ModifierMake', "Modifier Make"), + make_class('Logic', "Logic"), + make_class('Network', "Network"), + make_class('Betas', "Beta Nodes"), + make_class('Alphas', "Alpha Nodes"), +] + + +# def ff_unregister_node_categories(): +# """ +# Below (in the register function) we remove the SVERCHOK group from _node_categories collection, by doing: + +# _items_to_remove['sverchok_popped'] = _node_categories.pop("SVERCHOK") + +# this allows us to populate the NODE_MT_add menu as we want. In doing so we lose the automatic unregistration of +# various menu and category classes. This function behaves as a dedicated removal of those classes (for F8 and disable add-on), +# """ + +# def ff_unregister_node_cat_types(cats): +# for mt in cats[2]: +# bpy.utils.unregister_class(mt) +# for pt in cats[3]: +# bpy.utils.unregister_class(pt) + +# cat_types = _items_to_remove['sverchok_popped'] +# if cat_types: +# ff_unregister_node_cat_types(cat_types) + +# del _items_to_remove['sverchok_popped'] + + + +def register(): + for class_name in classes: + bpy.utils.register_class(class_name) + + # we pop sverchok from the standard nodecat collection to avoid the menu items appearing in the default Add node menu. + # _items_to_remove['sverchok_popped'] = _node_categories.pop("SVERCHOK") + + # bpy.types.NODE_MT_add.append(bpy.types.NODEVIEW_MT_Dynamic_Menu.draw) + + +def unregister(): + # bpy.types.NODE_MT_add.remove(bpy.types.NODEVIEW_MT_Dynamic_Menu.draw) + + for class_name in classes: + bpy.utils.unregister_class(class_name) + + # because we popped sverchok off the nodecat collection in register, we have to do our own class unregistration here. + # ff_unregister_node_categories() diff --git a/pool/shard001/Python/0012941_FoundationPlist.py b/pool/shard001/Python/0012941_FoundationPlist.py new file mode 100644 index 0000000000000000000000000000000000000000..23ee55547217266421440ee34266f297ab5987fd --- /dev/null +++ b/pool/shard001/Python/0012941_FoundationPlist.py @@ -0,0 +1,149 @@ +# encoding: utf-8 +# +# Copyright 2009-2020 Greg Neagle. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""FoundationPlist.py -- a tool to generate and parse OS X .plist files. + +This is intended as a drop-in replacement for Python's included plistlib, +with a few caveats: + - readPlist() and writePlist() operate only on a filepath, + not a file object. + - there is no support for the deprecated functions: + readPlistFromResource() + writePlistToResource() + - there is no support for the deprecated Plist class. + +The Property List (.plist) file format is a simple XML pickle supporting +basic object types, like dictionaries, lists, numbers and strings. +Usually the top level object is a dictionary. + +To write out a plist file, use the writePlist(rootObject, filepath) +function. 'rootObject' is the top level object, 'filepath' is a +filename. + +To parse a plist from a file, use the readPlist(filepath) function, +with a file name. It returns the top level object (again, usually a +dictionary). + +To work with plist data in strings, you can use readPlistFromString() +and writePlistToString(). +""" +from __future__ import absolute_import, print_function + +# PyLint cannot properly find names inside Cocoa libraries, so issues bogus +# No name 'Foo' in module 'Bar' warnings. Disable them. +# pylint: disable=E0611 +from Foundation import NSData +from Foundation import NSPropertyListSerialization +from Foundation import NSPropertyListMutableContainers +from Foundation import NSPropertyListXMLFormat_v1_0 +# pylint: enable=E0611 + +# Disable PyLint complaining about 'invalid' camelCase names +# pylint: disable=C0103 + + +class FoundationPlistException(Exception): + """Basic exception for plist errors""" + pass + +class NSPropertyListSerializationException(FoundationPlistException): + """Read/parse error for plists""" + pass + +class NSPropertyListWriteException(FoundationPlistException): + """Write error for plists""" + pass + +def readPlist(filepath): + """ + Read a .plist file from filepath. Return the unpacked root object + (which is usually a dictionary). + """ + plistData = NSData.dataWithContentsOfFile_(filepath) + dataObject, dummy_plistFormat, error = ( + NSPropertyListSerialization. + propertyListFromData_mutabilityOption_format_errorDescription_( + plistData, NSPropertyListMutableContainers, None, None)) + if dataObject is None: + if error: + error = error.encode('ascii', 'ignore') + else: + error = "Unknown error" + errmsg = "%s in file %s" % (error, filepath) + raise NSPropertyListSerializationException(errmsg) + else: + return dataObject + + +def readPlistFromString(data): + '''Read a plist data from a (byte)string. Return the root object.''' + plistData = NSData.dataWithBytes_length_(data, len(data)) + if not plistData: + raise NSPropertyListSerializationException( + "Could not convert string to NSData") + dataObject, dummy_plistFormat, error = ( + NSPropertyListSerialization. + propertyListFromData_mutabilityOption_format_errorDescription_( + plistData, NSPropertyListMutableContainers, None, None)) + if dataObject is None: + if error: + error = error.encode('ascii', 'ignore') + else: + error = "Unknown error" + raise NSPropertyListSerializationException(error) + else: + return dataObject + + +def writePlist(dataObject, filepath): + ''' + Write 'rootObject' as a plist to filepath. + ''' + plistData, error = ( + NSPropertyListSerialization. + dataFromPropertyList_format_errorDescription_( + dataObject, NSPropertyListXMLFormat_v1_0, None)) + if plistData is None: + if error: + error = error.encode('ascii', 'ignore') + else: + error = "Unknown error" + raise NSPropertyListSerializationException(error) + else: + if plistData.writeToFile_atomically_(filepath, True): + return + else: + raise NSPropertyListWriteException( + "Failed to write plist data to %s" % filepath) + + +def writePlistToString(rootObject): + '''Return 'rootObject' as a plist-formatted (byte)string.''' + plistData, error = ( + NSPropertyListSerialization. + dataFromPropertyList_format_errorDescription_( + rootObject, NSPropertyListXMLFormat_v1_0, None)) + if plistData is None: + if error: + error = error.encode('ascii', 'ignore') + else: + error = "Unknown error" + raise NSPropertyListSerializationException(error) + else: + return bytes(plistData) + + +if __name__ == '__main__': + print('This is a library of support tools for the Munki Suite.') diff --git a/pool/shard001/Python/0012944_config.py b/pool/shard001/Python/0012944_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c8abd540c41605a037efd36ff8372581c84a33e0 --- /dev/null +++ b/pool/shard001/Python/0012944_config.py @@ -0,0 +1,83 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import os + +from oslo.config import cfg + + +DashboardGroup = [ + cfg.StrOpt('dashboard_url', + default='http://localhost/', + help="Where the dashboard can be found"), + cfg.StrOpt('login_url', + default='http://localhost/auth/login/', + help="Login page for the dashboard"), + cfg.StrOpt('help_url', + default='http://docs.openstack.org/', + help="Dashboard help page url"), +] + +IdentityGroup = [ + cfg.StrOpt('username', + default='demo', + help="Username to use for non-admin API requests."), + cfg.StrOpt('password', + default='pass', + help="API key to use when authenticating.", + secret=True), + cfg.StrOpt('admin_username', + default='admin', + help="Administrative Username to use for admin API " + "requests."), + cfg.StrOpt('admin_password', + default='pass', + help="API key to use when authenticating as admin.", + secret=True), +] + +AvailableServiceGroup = [ + cfg.BoolOpt('sahara', + default=False) +] + +SeleniumGroup = [ + cfg.IntOpt('implicit_wait', + default=10, + help="Implicit wait timeout in seconds"), + cfg.IntOpt('explicit_wait', + default=10, + help="Explicit wait timeout in seconds"), + cfg.IntOpt('page_timeout', + default=30, + help="Page load timeout in seconds"), +] + + +def _get_config_files(): + conf_dir = os.path.join( + os.path.abspath(os.path.dirname(os.path.dirname(__file__))), + 'integration_tests') + conf_file = os.environ.get('HORIZON_INTEGRATION_TESTS_CONFIG_FILE', + "%s/horizon.conf" % conf_dir) + return [conf_file] + + +def get_config(): + cfg.CONF([], project='horizon', default_config_files=_get_config_files()) + + cfg.CONF.register_opts(DashboardGroup, group="dashboard") + cfg.CONF.register_opts(IdentityGroup, group="identity") + cfg.CONF.register_opts(AvailableServiceGroup, group="service_available") + cfg.CONF.register_opts(SeleniumGroup, group="selenium") + + return cfg.CONF diff --git a/pool/shard001/Python/0012951_cli.py b/pool/shard001/Python/0012951_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..76eaaf89d6ca6c7dadf654abe35af987a6fd5c40 --- /dev/null +++ b/pool/shard001/Python/0012951_cli.py @@ -0,0 +1,106 @@ +# encoding: utf-8 + +import sys + +import ckan.lib.cli as cli +import ckan.plugins as p +import ckanext.datastore.db as datastore_db + + +class DatapusherCommand(cli.CkanCommand): + '''Perform commands in the datapusher + + Usage: + + resubmit - Resubmit all datastore resources to the datapusher, + ignoring if their files haven't changed. + submit - Submits all resources from the package + identified by pkgname (either the short name or ID). + submit_all - Submit every package to the datastore. + This is useful if you're setting up datastore + for a ckan that already has datasets. + ''' + + summary = __doc__.split('\n')[0] + usage = __doc__ + + def command(self): + if self.args and self.args[0] == 'resubmit': + self._confirm_or_abort() + + self._load_config() + self._resubmit_all() + elif self.args and self.args[0] == 'submit_all': + self._confirm_or_abort() + + self._load_config() + self._submit_all_packages() + elif self.args and self.args[0] == 'submit': + self._confirm_or_abort() + + if len(self.args) != 2: + print "This command requires an argument\n" + print self.usage + sys.exit(1) + + self._load_config() + self._submit_package(self.args[1]) + else: + print self.usage + + def _confirm_or_abort(self): + question = ( + "Data in any datastore resource that isn't in their source files " + "(e.g. data added using the datastore API) will be permanently " + "lost. Are you sure you want to proceed?" + ) + answer = cli.query_yes_no(question, default=None) + if not answer == 'yes': + print "Aborting..." + sys.exit(0) + + def _resubmit_all(self): + resources_ids = datastore_db.get_all_resources_ids_in_datastore() + self._submit(resource_ids) + + def _submit_all_packages(self): + # submit every package + # for each package in the package list, + # submit each resource w/ _submit_package + import ckan.model as model + package_list = p.toolkit.get_action('package_list') + for p_id in package_list({'model': model, 'ignore_auth': True}, {}): + self._submit_package(p_id) + + def _submit_package(self, pkg_id): + import ckan.model as model + + package_show = p.toolkit.get_action('package_show') + try: + pkg = package_show({'model': model, 'ignore_auth': True}, + {'id': pkg_id.strip()}) + except Exception, e: + print e + print "Package '{}' was not found".format(pkg_id) + sys.exit(1) + + resource_ids = [r['id'] for r in pkg['resources']] + self._submit(resource_ids) + + def _submit(self, resources): + import ckan.model as model + + print 'Submitting %d datastore resources' % len(resources) + user = p.toolkit.get_action('get_site_user')( + {'model': model, 'ignore_auth': True}, {}) + datapusher_submit = p.toolkit.get_action('datapusher_submit') + for resource_id in resources: + print ('Submitting %s...' % resource_id), + data_dict = { + 'resource_id': resource_id, + 'ignore_hash': True, + } + if datapusher_submit({'user': user['name']}, data_dict): + print 'OK' + else: + print 'Fail' diff --git a/pool/shard001/Python/0012955_namespaced.py b/pool/shard001/Python/0012955_namespaced.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9692f66604251a515ad407482f094383af6187 --- /dev/null +++ b/pool/shard001/Python/0012955_namespaced.py @@ -0,0 +1,24 @@ +import re +from structs.nest import * + + +def nu(base): + + def dep(filename): + raw = re.sub("(?P
.*)" + base + "/(?P.+)/(?P.+?)\.js$", "\g.\g", filename)
+        return re.sub("/", ".", raw)
+
+    def pattern(word):
+        return '' + word + '.js'
+
+    def path(d):
+        qualified = dep(d)
+        last = qualified.rfind('.')
+        if last > -1:
+            rest = qualified[:last]
+            name = qualified[last + 1:len(qualified)]
+            return base + '/' + rest + '/' + name + '.js'
+        else:
+            return qualified
+
+    return Nest(base, pattern, dep, path)
diff --git a/pool/shard001/Python/0012957_opie_checksum_rewrite.py b/pool/shard001/Python/0012957_opie_checksum_rewrite.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e16ee9085ac4b2eef64a126a6eb53e2769e8775
--- /dev/null
+++ b/pool/shard001/Python/0012957_opie_checksum_rewrite.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+# ex:ts=4:sw=4:sts=4:et
+
+# Opie recipe checksum rewriter
+#
+# A crude script for rewriting recipes to contain checksum information
+#
+# Some portions copied from oe-source-checker.py, copyright (C) 2007 OpenedHand
+
+import os
+import sys
+
+def rewrite(recpfilename, sourcedir):
+	insrc = False
+	srcfirst = False
+	sums = ''
+	appname = ''
+	output = ''
+	f = open(recpfilename, 'r')
+	for line in f:
+		if line.startswith('require '):
+			pn = os.path.basename(recpfilename)
+			pn = pn[0:pn.find("_")]
+			incfilename = line[8:].strip().replace("${PN}", pn)
+			f2 = open(os.path.join(os.path.dirname(recpfilename), incfilename))
+			for line2 in f2:
+				if line2.startswith('APPNAME '):
+					appname = line2[line2.find('"'):].strip('\n\r"')
+			f2.close()
+			output = output + line
+			continue
+		
+		if line.startswith('SRC_URI['):
+			continue
+
+		if line.startswith('APPNAME '):
+			appname = line[line.find('"'):].strip('\n\r"')
+			output = output + line
+			continue
+
+		if not insrc and line.startswith('SRC_URI '):
+			insrc = True
+			srcfirst = True
+			
+		if insrc:
+			pos = line.find('-split_')
+			pos2 = line.find('.tar.bz2')
+			if pos > -1 and pos2 > -1:
+				name = line[pos+1:pos2]
+				name = name.replace('${APPNAME}', 'appname')
+				output = output + line.replace('.tar.bz2', '.tar.bz2;name=%s' % name)
+				filename = line.strip('\n\r\t "\\').replace('${APPNAME}', appname)
+				if srcfirst:
+					filename = filename[filename.find('"')+1:]
+				filename = filename.replace('http://sources.openembedded.org/', '')
+				localpath = os.path.join(sourcedir, filename)
+				if not os.path.isfile(localpath):
+					raise IOError("file %s not found" % localpath)
+				
+				md5pipe = os.popen('md5sum ' + localpath)
+				md5data = (md5pipe.readline().split() or [ "" ])[0]
+				md5pipe.close()
+
+				shapipe = os.popen('sha256sum ' + localpath)
+				shadata = (shapipe.readline().split() or [ "" ])[0]
+				shapipe.close()
+				
+				sums = sums + 'SRC_URI[%s.md5sum] = "%s"\n' % (name, md5data)
+				sums = sums + 'SRC_URI[%s.sha256sum] = "%s"\n' % (name, shadata)
+				
+			else:
+				output = output + line
+
+			if (srcfirst and line.count('"') > 1) or (not srcfirst and line.find('"') > -1):
+				insrc = False
+				if sums:
+					output = output + sums
+			
+			srcfirst = False
+		else:
+			output = output + line
+
+	f.close()
+	
+	f = open(recpfilename, 'w')
+	f.write(output)
+	f.close()
+
+
+
+if len(sys.argv) < 3:
+    print """syntax: %s recipe dl_dir
+  recipe - recipe.bb file
+  dl_dir - location of local source files""" % sys.argv[0]
+    sys.exit(1)
+
+recipe = sys.argv[1]
+dl_dir = sys.argv[2]
+
+if not os.path.isfile(recipe):
+    print >> sys.stderr, "%s: recipe file %s not found" % recipe
+	sys.exit(1)
+
+if not os.path.isdir(dl_dir):
+    print >> sys.stderr, "%s: source dir %s not found" % dl_dir
+	sys.exit(1)
+
+rewrite(recipe, dl_dir)
diff --git a/pool/shard001/Python/0012961_gevent_wsgi.py b/pool/shard001/Python/0012961_gevent_wsgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..24df12b2fe3c4a0b5cadb6c78b935440bb2d1622
--- /dev/null
+++ b/pool/shard001/Python/0012961_gevent_wsgi.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+
+# Copyright (C) Mark Breedlove and Qingyang Xi
+# See README.md and License.txt.
+
+"""
+For running with the Gevent WSGI server.
+
+This serves up static resources, e.g. /static, which may be fine for
+development, but the idea is that it's reverse-proxied behind a webserver,
+with the static resources served directly by the webserver.
+
+Example invocation:
+$ /path/to/gevent_wsgi.py -l  -p  &
+"""
+
+import sys
+import os
+import getopt
+import signal
+# gevent.wsgi is very fast and allows high concurrency, but does not support
+# streaming (for large file upload requests or large responses).  Another
+# option is gevent.pywsgi.
+from gevent.wsgi import WSGIServer
+from app import app
+
+
+port = 8080
+log = 'default'
+pidfile = None
+interface = ''
+
+
+def usage():
+    print 'gevent_wsgi.py [[-h] | [-i ] ', \
+        '[-p ] [-l ] [--pidfile=]'
+
+def main(argv):
+    global port, log, pidfile, interface
+    try:
+        opts, args = getopt.getopt(argv, "p:l:i:h", ["pidfile="])
+    except getopt.GetoptError:
+        usage()
+        sys.exit(2)
+    for opt, arg in opts:
+        if opt == '-h':
+            usage()
+            sys.exit()
+        elif opt == '-p':
+            port = int(arg)
+        elif opt == '-l':
+            try:
+                log = open(arg, 'w')
+            except:
+                sys.stderr.write("Can not open log file.\n")
+                sys.exit(1)
+        elif opt == '-i':
+            interface = arg
+        elif opt == '--pidfile':
+            pidfile = arg
+    if pidfile:
+        with open(pidfile, 'w') as f:
+            f.write(str(os.getpid()))
+        signal.signal(signal.SIGTERM, shutdown_handler)
+        signal.signal(signal.SIGINT, shutdown_handler)
+    http_server = WSGIServer((interface, port), application=app, log=log)
+    try:
+        http_server.serve_forever()
+    except:
+        clean_pidfile()
+        sys.exit()  # Don't print backtrace for KeyboardInterrupt
+
+def clean_pidfile():
+    try:
+        os.unlink(pidfile)
+    except:
+        pass
+
+def shutdown_handler(signum, frame):
+    clean_pidfile()
+    sys.exit()
+
+if __name__ == '__main__':
+   main(sys.argv[1:])
+
diff --git a/pool/shard001/Python/0012965_blog.py b/pool/shard001/Python/0012965_blog.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5602779fc005b2d43a82b805ffcd1b27bfc9f49
--- /dev/null
+++ b/pool/shard001/Python/0012965_blog.py
@@ -0,0 +1,238 @@
+# -*- coding: utf-8 -*-
+# blog.py - maps requests to methods and handles them accordingly.
+# Copyright (C) 2017 Jose Ricardo Ziviani
+# 
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see .
+
+
+# --
+# IMPORTS
+# --
+from werkzeug.routing import Map
+from werkzeug.routing import Rule
+from werkzeug.wrappers import Request
+from werkzeug.wrappers import Response
+from werkzeug.exceptions import NotFound
+from werkzeug.exceptions import HTTPException
+from werkzeug.utils import redirect
+from werkzeug.urls import url_fix
+from templates import templates
+
+import logging
+import hashlib
+import re
+
+
+# --
+# CONSTANTS
+# --
+
+
+# --
+# IMPLEMENTATION
+# --
+class Blog(object):
+    '''
+    Implements the ziviani.net controller
+    '''
+
+    def __init__(self):
+        '''
+        Constructor
+        '''
+        self._urls = Map([
+            Rule('/', endpoint='index'),
+            Rule('/ptbr', endpoint='ptbr_index'),
+            Rule('/feed', endpoint='feed'),
+            Rule('/about', endpoint='about'),
+            Rule('/ptbr/about', endpoint='ptbr_about'),
+            Rule('/articles', endpoint='articles'),
+            Rule('/ptbr/articles', endpoint='ptbr_articles'),
+            Rule('/links', endpoint='hotlinks'),
+            Rule('/ptbr/links', endpoint='ptbr_hotlinks'),
+            # Rule('/resume', endpoint='resume'),
+            Rule('//', endpoint='posts'),
+            Rule('//ptbr/', endpoint='ptbr_posts'),
+            Rule('/search', endpoint='search'),
+        ])
+
+        logging.basicConfig()
+        self._logger = logging.getLogger('[ BLOG ]')
+        self._logger.setLevel(logging.ERROR)
+        self._templates = templates()
+
+    def _on_index(self, request):
+        '''
+        Handles the main page request
+        '''
+        return self._on_posts(request, '2019', 'amps-template-engine')
+
+    def _on_ptbr_index(self, request):
+        '''
+        Handles the main page request
+        '''
+        return self._on_ptbr_posts(request, '2017', 'funcoes-em-assembly-ii')
+
+    def _on_feed(self, request):
+        '''
+        Handles the feed (rss) request
+        '''
+        response = self._templates.get_feed()
+        if response is None:
+            self._logger.error('feed not found, missed generate_metadata?')
+            raise NotFound()
+        return Response(response, mimetype='application/rss+xml')
+
+    def _on_posts(self, request, year, page):
+        '''
+        Handles requests to posts
+        '''
+        page_data = {}
+        page_data['url'] = 'https://ziviani.net/%s/%s' % (year, page)
+        page_data['uid'] = hashlib.md5(page_data['url']).hexdigest()
+
+        response = self._templates.get_template("%s.tmpl" % page,
+                                                data=page_data)
+        if response is None:
+            self._logger.error('template %s not found', page)
+            raise NotFound()
+
+        return Response(response, mimetype='text/html')
+
+    def _on_ptbr_posts(self, request, year, page):
+        '''
+        Handles requests to posts in brazilian portuguese
+        '''
+        page_data = {}
+        page_data['url'] = 'https://ziviani.net/%s/ptbr/%s/' % (year, page)
+        page_data['uid'] = hashlib.md5(page_data['url']).hexdigest()
+
+        response = self._templates.get_template("ptbr/%s.tmpl" % page, data=page_data)
+        if response is None:
+            self._logger.error('template ptbr/%s not found', page)
+            raise NotFound()
+
+        return Response(response, mimetype='text/html')
+
+    def _on_articles(self, request):
+        '''
+        Handles request to articles page
+        '''
+        response = self._templates.get_template("article.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_ptbr_articles(self, request):
+        '''
+        Handles request to articles page
+        '''
+        response = self._templates.get_template("ptbr/article.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_hotlinks(self, request):
+        '''
+        Handles request to link page
+        '''
+        response = self._templates.get_template("hotlinks-v1.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_ptbr_hotlinks(self, request):
+        '''
+        Handles request to link page
+        '''
+        response = self._templates.get_template("ptbr/hotlinks-v1.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_about(self, request):
+        '''
+        Handles requests to About page
+        '''
+        response = self._templates.get_template("about.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_ptbr_about(self, request):
+        '''
+        Handles requests to About page
+        '''
+        response = self._templates.get_template("ptbr/about.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_resume(self, request):
+        '''
+        Handles resume page
+        '''
+        response = self._templates.get_template("resume.tmpl")
+        return Response(response, mimetype='text/html')
+
+    def _on_search(self, request):
+        '''
+        Handles internal searches using DuckDuckGo
+        '''
+        if request.method != 'POST':
+            return self._on_index(request)
+
+        query = re.sub(r'[^0-9A-Za-z-+., ]',
+                       r' ',
+                       request.form['search'],
+                       flags=re.UNICODE)
+
+        if len(query) > 25:
+            query = query[:25]
+
+        search_q = 'https://duckduckgo.com/?q=site:ziviani.net %s' % query
+        search_q+= '&kae=dark&kj=%23455a64&k7=%23eceff1&k5=1&kx=%231565c0'
+        search_q+= '&kt=n&k5=1&t=ziviani.net&km=l&kn=0&kae=dark&kh=1&kg=p'
+
+        return redirect(url_fix(search_q))
+
+    def _not_found(self):
+        '''
+        Handles 404 - page not found!
+        '''
+        response = self._templates.get_template("notfound.tmpl")
+        return Response(response, mimetype='text/html', status=404)
+
+    def _dispatch(self, request):
+        '''
+        Maps the request to the appropriate method
+        '''
+        adapter = self._urls.bind_to_environ(request.environ)
+
+        try:
+            endpoint, values = adapter.match()
+            return getattr(self, '_on_' + endpoint)(request, **values)
+
+        # show the spacial page not found
+        except NotFound, e:
+            return self._not_found()
+
+        # go back do index if any other isse
+        except HTTPException, e:
+            self._logger.error(str(e))
+            return self._on_index(request)
+
+    def wsgi_app(self, environ, start_response):
+        '''
+        Abstracts request/response calls in a couple of lines
+        '''
+        request = Request(environ)
+        response = self._dispatch(request)
+
+        return response(environ, start_response)
+
+    def __call__(self, environ, start_response):
+        '''
+        Main method
+        '''
+        return self.wsgi_app(environ, start_response)
+# class Blog()
diff --git a/pool/shard001/Python/0012968_filters.py b/pool/shard001/Python/0012968_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b8b4df97d5c3a620c04a4781dfb606c095ff384
--- /dev/null
+++ b/pool/shard001/Python/0012968_filters.py
@@ -0,0 +1,34 @@
+'''
+Created on May 31, 2015
+
+@author: isdal
+'''
+import running_median
+from collections import deque
+
+class MedianFilter:
+    """Simple class for calculating the median over a window of temperature measurements."""
+    def __init__(self, window):
+        self.window = window
+        self.skiplist = running_median.IndexableSkiplist(expected_size=window)
+        self.queue = deque()
+        self.sum = 0.0
+        
+    def add(self, temperature):
+        if len(self.queue) == self.window:
+            to_remove = self.queue.popleft()
+            self.skiplist.remove(to_remove)
+            self.sum -= to_remove
+        self.queue.append(temperature)
+        self.skiplist.insert(temperature)
+        self.sum += temperature
+        
+    def getMedian(self):
+        if len(self.queue) < self.window:
+            return None
+        return self.skiplist[len(self.queue) // 2]
+
+    def getAverage(self):
+        if len(self.queue) < self.window:
+            return None
+        return self.sum / self.window
diff --git a/pool/shard001/Python/0012970_ical.py b/pool/shard001/Python/0012970_ical.py
new file mode 100644
index 0000000000000000000000000000000000000000..c10112c7474885b10ba590e75f7984a44ed60e6e
--- /dev/null
+++ b/pool/shard001/Python/0012970_ical.py
@@ -0,0 +1,33 @@
+#
+# Ryan Burns
+#
+
+from icalendar import Calendar, Event
+import urllib2
+
+try:
+    import pytz
+except ImportError:
+    print "Requires pytz"
+    print "pip install pytz"
+    sys.exit(1)
+
+
+
+def test():
+    url = 'https://www.google.com/calendar/ical/events%40a2geeks.org/public/basic.ics'
+    req = urllib2.Request(url)
+    response = urllib2.urlopen(req)
+    data = response.read()
+
+    cal = Calendar.from_ical(data)
+
+    for event in cal.walk('vevent'):
+        date = event.get('dtstart').dt.astimezone(pytz.timezone('America/Detroit'))
+        desc = event.get('description')
+        summary = event.get('summary')
+        location = event.get('location')
+        print summary
+        print desc
+        print date
+        print location
diff --git a/pool/shard001/Python/0012972_tst_Unsigned.py b/pool/shard001/Python/0012972_tst_Unsigned.py
new file mode 100644
index 0000000000000000000000000000000000000000..e23ed8dc382f2c4631fc8bb1594e93ca2b07f13e
--- /dev/null
+++ b/pool/shard001/Python/0012972_tst_Unsigned.py
@@ -0,0 +1,45 @@
+import unittest
+import netCDF4
+from numpy.testing import assert_array_equal
+import numpy as np
+
+class Test_Unsigned(unittest.TestCase):
+    """
+    Test autoconversion to unsigned ints when _Unsigned attribute is True.
+    This attribute is is set by netcdf-java to designate unsigned
+    integer data stored with a signed integer type in netcdf-3.
+    If _Unsigned=True, a view to the data as unsigned integers is returned.
+    set_autoscale can be used to turn this off (default is on)
+    See issue #656 (pull request #658).
+    """
+    def test_unsigned(self):
+        f = netCDF4.Dataset("ubyte.nc")
+        data = f['ub'][:]
+        assert data.dtype.str[1:] == 'u1'
+        assert_array_equal(data,np.array([0,255],np.uint8))
+        f.set_auto_scale(False)
+        data2 = f['ub'][:]
+        assert data2.dtype.str[1:] == 'i1'
+        assert_array_equal(data2,np.array([0,-1],np.int8))
+        f.close()
+        # issue 671
+        f = netCDF4.Dataset('issue671.nc')
+        data1 = f['soil_moisture'][:]
+        assert(np.ma.isMA(data1))
+        f.set_auto_scale(False)
+        data2 = f['soil_moisture'][:]
+        assert(data1.mask.sum() == data2.mask.sum())
+        f.close()
+        # issue 794
+        # test that valid_min/valid_max/_FillValue are
+        # treated as unsigned integers.
+        f=netCDF4.Dataset('20171025_2056.Cloud_Top_Height.nc')
+        data = f['HT'][:]
+        assert(data.mask.sum() == 57432)
+        assert(int(data.max()) == 15430)
+        assert(int(data.min()) == 0)
+        assert(data.dtype == np.float32)
+        f.close()
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/pool/shard001/Python/0012975_chart_components.py b/pool/shard001/Python/0012975_chart_components.py
new file mode 100644
index 0000000000000000000000000000000000000000..c46dc8623fd5d8f8a8277b49233e901a76092b1f
--- /dev/null
+++ b/pool/shard001/Python/0012975_chart_components.py
@@ -0,0 +1,59 @@
+from copy import deepcopy
+
+class ggtitle(object):
+    def __init__(self, title):
+        self.title = title
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        gg.title = self.title
+        return gg
+
+class xlab(object):
+    def __init__(self, xlab):
+        self.xlab = xlab
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        gg.xlab = self.xlab
+        return gg
+
+class xlim(object):
+    def __init__(self, low, high):
+        self.low, self.high = low, high
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        gg.xlimits = [self.low, self.high]
+        return gg
+
+class ylim(object):
+    def __init__(self, low, high):
+        self.low, self.high = low, high
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        gg.ylimits = [self.low, self.high]
+        return gg
+
+class ylab(object):
+    def __init__(self, ylab):
+        self.ylab = ylab
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        gg.ylab = self.ylab
+        return gg
+
+class labs(object):
+    def __init__(self, xlab=None, ylab=None):
+        self.xlab = xlab
+        self.ylab = ylab
+
+    def __radd__(self, gg):
+        gg = deepcopy(gg)
+        if self.xlab:
+            gg.xlab = self.xlab
+        if self.ylab:
+            gg.ylab = self.ylab
+        return gg
diff --git a/pool/shard001/Python/0012976_0002_add_initial_profiles.py b/pool/shard001/Python/0012976_0002_add_initial_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4aeb41ba6903cdcc7dbfbbd76ccfa2407028670
--- /dev/null
+++ b/pool/shard001/Python/0012976_0002_add_initial_profiles.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.20 on 2019-02-26 21:15
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def add_initial_profiles(apps, schema_editor):
+    User = apps.get_model("auth", "User")
+    WombleProfile = apps.get_model("wombles", "WombleProfile")
+    for user in User.objects.all():
+        try:
+            WombleProfile.objects.create(user=user)
+        except:
+            pass
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [("wombles", "0001_initial")]
+
+    operations = [
+        migrations.RunPython(add_initial_profiles, migrations.RunPython.noop)
+    ]
diff --git a/pool/shard001/Python/0012978_utility_widgets.py b/pool/shard001/Python/0012978_utility_widgets.py
new file mode 100644
index 0000000000000000000000000000000000000000..9337f51c60f3044a14d575e2e8ad9cf099491916
--- /dev/null
+++ b/pool/shard001/Python/0012978_utility_widgets.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLabel
+from PyQt5.QtGui import QPixmap
+
+
+class LabelWithOkCancelIcon(QWidget):
+    """
+    Displays small icon with ok/cancel icon and a text to the right.
+    """
+    def __init__(self, parent: QWidget = None):
+        super(LabelWithOkCancelIcon, self).__init__(parent)
+        self.layout = QHBoxLayout()
+        self.layout.setSpacing(2)
+        self.layout.setContentsMargins(2, 2, 2, 2)
+        self.setLayout(self.layout)
+        self.icon_label = QLabel(self)
+        self.label = QLabel(self)
+        self.layout.addWidget(self.icon_label)
+        self.layout.addWidget(self.label)
+        self.layout.addStretch()
+        self.pixmap = QPixmap()
+        self._ok_status = False
+
+    def set_ok_status(self, ok_status: bool):
+        self._ok_status = ok_status
+        if ok_status:
+            self.pixmap.load('img/ok_icon.png')
+        else:
+            self.pixmap.load('img/cancel_icon.png')
+        self.icon_label.setPixmap(self.pixmap.scaled(32, 32))
+
+    def ok_status(self) -> bool:
+        return self._ok_status
+
+    def set_text(self, text: str):
+        self.label.setText(text)
+
+    def text(self) -> str:
+        return str(self.label.text())
+
diff --git a/pool/shard001/Python/0012980_init__.py b/pool/shard001/Python/0012980_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdc5483656dc9f570ba8dcfd6209b6a4046ad69b
--- /dev/null
+++ b/pool/shard001/Python/0012980_init__.py
@@ -0,0 +1,24 @@
+import pkgutil
+
+# Set up a list of triggers and functions to execute.
+plugin_pairs = []
+
+# Find all packages in the current directory.
+for loader, name, ispkg \
+    in pkgutil.walk_packages(__path__):
+    module = loader.find_module(name).load_module(name)
+
+    # Try to access the module's trigger and execute functions.
+    try:
+        plugin_pairs.append((name, module.trigger, module.execute))
+    except Exception as e:
+        print("Skipping module {}: {}".format(name, e))
+
+# Define a convenience function for running all plugins if their
+# trigger function returns true.
+def execute(**songinfo):
+    for pair in plugin_pairs:
+        try:
+            if pair[1](**songinfo): pair[2](**songinfo)
+        except Exception as e:
+            print("Module {} caused: {}".format(pair[0], e))
diff --git a/pool/shard001/Python/0012984_graph.py b/pool/shard001/Python/0012984_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca136aabf65cddb5f428e46b121acd9391f59c8d
--- /dev/null
+++ b/pool/shard001/Python/0012984_graph.py
@@ -0,0 +1,132 @@
+""" A simple graph class """
+from __future__ import division, print_function, absolute_import
+
+
+class Graph(object):
+    ''' A simple graph class
+
+    '''
+
+    def __init__(self):
+        ''' A graph class with nodes and edges :-)
+
+        This class allows us to:
+
+        1. find the shortest path
+        2. find all paths
+        3. add/delete nodes and edges
+        4. get parent & children nodes
+
+        Examples
+        --------
+        >>> from dipy.core.graph import Graph
+        >>> g=Graph()
+        >>> g.add_node('a',5)
+        >>> g.add_node('b',6)
+        >>> g.add_node('c',10)
+        >>> g.add_node('d',11)
+        >>> g.add_edge('a','b')
+        >>> g.add_edge('b','c')
+        >>> g.add_edge('c','d')
+        >>> g.add_edge('b','d')
+        >>> g.up_short('d')
+        ['d', 'b', 'a']
+
+        '''
+
+        self.node = {}
+        self.pred = {}
+        self.succ = {}
+
+    def add_node(self, n, attr=None):
+        self.succ[n] = {}
+        self.pred[n] = {}
+        self.node[n] = attr
+
+    def add_edge(self, n, m, ws=True, wp=True):
+        self.succ[n][m] = ws
+        self.pred[m][n] = wp
+
+    def parents(self, n):
+        return self.pred[n].keys()
+
+    def children(self, n):
+        return self.succ[n].keys()
+
+    def up(self, n):
+        return self.all_paths(self.pred, n)
+
+    def down(self, n):
+        return self.all_paths(self.succ, n)
+
+    def up_short(self, n):
+        return self.shortest_path(self.pred, n)
+
+    def down_short(self, n):
+        return self.shortest_path(self.succ, n)
+
+    def all_paths(self, graph, start, end=None, path=[]):
+        path = path + [start]
+        if start == end or graph[start] == {}:
+            return [path]
+        if start not in graph:
+            return []
+        paths = []
+        for node in graph[start]:
+            if node not in path:
+                newpaths = self.all_paths(graph, node, end, path)
+                for newpath in newpaths:
+                    paths.append(newpath)
+        return paths
+
+    def shortest_path(self, graph, start, end=None, path=[]):
+        path = path + [start]
+        if graph[start] == {} or start == end:
+            return path
+        if start not in graph:
+            return []
+        shortest = None
+        for node in graph[start]:
+            if node not in path:
+                newpath = self.shortest_path(graph, node, end, path)
+                if newpath:
+                    if not shortest or len(newpath) < len(shortest):
+                        shortest = newpath
+        return shortest
+
+    def del_node_and_edges(self, n):
+        try:
+            del self.node[n]
+        except KeyError:
+            raise KeyError('node not in the graph')
+
+        for s in self.succ[n]:
+            del self.pred[s][n]
+        del self.succ[n]
+
+        for p in self.pred[n]:
+            del self.succ[p][n]
+        del self.pred[n]
+
+    def del_node(self, n):
+        try:
+            del self.node[n]
+        except KeyError:
+            raise KeyError('node not in the graph')
+
+        for s in self.succ[n]:
+            for p in self.pred[n]:
+                self.succ[p][s] = self.succ[n][s]
+                self.pred[s][p] = self.pred[s][n]
+        for s in self.succ.keys():
+            try:
+                del self.succ[s][n]
+            except KeyError:
+                pass
+        for p in self.pred.keys():
+            try:
+                del self.pred[p][n]
+            except KeyError:
+                pass
+        del self.succ[n]
+        del self.pred[n]
diff --git a/pool/shard001/Python/0012989_login.py b/pool/shard001/Python/0012989_login.py
new file mode 100644
index 0000000000000000000000000000000000000000..e675f8461b8f4ba646812a17dfaa7edb10daff75
--- /dev/null
+++ b/pool/shard001/Python/0012989_login.py
@@ -0,0 +1,70 @@
+from flask import Blueprint
+from flask import current_app, jsonify, render_template, request
+
+from passlib.hash import pbkdf2_sha256
+
+from sqlalchemy.orm.exc import NoResultFound
+
+from trexmo.core.db.models import User
+from trexmo.core.utils.auth import make_auth_token
+from trexmo.core.utils.time import utcnow
+
+
+bp = Blueprint('login', __name__)
+
+
+@bp.route('/auth/tokens/', methods=['POST'])
+def create_token():
+    """
+    .. http:post:: /auth/tokens/
+
+        Create a new authentication token.
+
+        :json username:
+            The username of the user.
+        :json password:
+            The password of the user.
+
+        :return:
+            The created token and its estimated expiration date.
+
+        :note:
+            The extimated expiration date returned with the token is merely an
+            indication for the client to know when it should expect to ask for
+            a new token. However, it is possible that the token expires before
+            the given date.
+    """
+    post_data = request.get_json(force=True)
+
+    # Check if required fields have been provided.
+    if not post_data.get('username'):
+        return jsonify({'message': 'Missing username.'}), 403
+    if not post_data.get('password'):
+        return jsonify({'message': 'Missing password.'}), 403
+
+    # Get the credentials.
+    username = post_data['username']
+    password = post_data['password']
+
+    # Search for the user identified by the given username.
+    try:
+        user = User.query.filter(User.username == username).one()
+    except NoResultFound:
+        return jsonify({'message': 'Invalid username or password.'}), 403
+
+    # Check the user password.
+    if not pbkdf2_sha256.verify(password, user.password):
+        return jsonify({'message': 'Invalid username or password.'}), 403
+
+    # Generate a new token for the authenticated user.
+    token = make_auth_token(user)
+
+    return jsonify({
+        'token': token,
+        'expires_at': utcnow().timestamp() + current_app.config['AUTH_TOKEN_DURATION']
+    }), 201
+
+
+@bp.route('/login')
+def login():
+    return render_template('app.html')
diff --git a/pool/shard001/Python/0012991_0002_auto_20160827_2159.py b/pool/shard001/Python/0012991_0002_auto_20160827_2159.py
new file mode 100644
index 0000000000000000000000000000000000000000..16d9274744a7b6fecfafb0ebdbcafa4039f666da
--- /dev/null
+++ b/pool/shard001/Python/0012991_0002_auto_20160827_2159.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9 on 2016-08-27 21:59
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+import django_extensions.db.fields
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('player', '0023_auto_20160612_1804'),
+        ('game', '0001_initial'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='MatchCard',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('card_type', models.CharField(choices=[(b'B', b'Bomb'), (b'1', b'One'), (b'2', b'Two'), (b'4', b'Four'), (b'8', b'Eight'), (b'S', b'Special')], max_length=1)),
+                ('flipped', models.BooleanField(default=False)),
+                ('position', models.IntegerField(default=0)),
+            ],
+        ),
+        migrations.CreateModel(
+            name='MatchGame',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('date_created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True)),
+                ('state', models.CharField(choices=[(b'PLAY', b'Playing'), (b'WIN', b'Win'), (b'LOSE', b'Lose')], default=b'PLAY', max_length=3)),
+                ('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='player.Player')),
+            ],
+        ),
+        migrations.AddField(
+            model_name='matchcard',
+            name='game',
+            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='game.MatchGame'),
+        ),
+    ]
diff --git a/pool/shard001/Python/0012992_selection_sort.py b/pool/shard001/Python/0012992_selection_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a52fdf31bf32c3cd3a042a4b8cf56ebcd8be458
--- /dev/null
+++ b/pool/shard001/Python/0012992_selection_sort.py
@@ -0,0 +1,27 @@
+import random
+from console import ConsolePrinter
+from sorter import Sorter
+
+class SelectionSort(Sorter):
+    def sort(self):
+        for curstep in range(0, len(self.data)-1):
+            lowest = curstep
+            for i in range(curstep+1, len(self.data)):
+                self.notify(self.data, [i], [curstep, len(self.data) - 1])
+                if self.data[i] < self.data[lowest]:
+                    lowest = i
+        
+            if i != curstep:
+                self.data[curstep], self.data[lowest] = self.data[lowest], self.data[curstep]
+
+        self.notify(self.data)
+
+if __name__ == '__main__':
+    num_list = range(0, 100)
+    samples = random.sample(num_list, 40)
+
+    printer = ConsolePrinter()
+    selection = SelectionSort(samples)
+    selection.registerObserver(printer)
+    selection.sort()
+
diff --git a/pool/shard001/Python/0012993_common.py b/pool/shard001/Python/0012993_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ebd1da698e421e21715b5da7bb9ee9a27e50c23
--- /dev/null
+++ b/pool/shard001/Python/0012993_common.py
@@ -0,0 +1,54 @@
+# -*- coding: utf-8 -*-
+
+import docker
+import os
+import sys
+import requests
+
+
+DEFAULT_TIMEOUT_SECONDS = 600
+
+
+def docker_client():
+    # Default timeout 10 minutes
+    try:
+        timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
+    except ValueError as e:
+        print("Provided timeout value: %s cannot be parsed as integer, exiting." %
+              os.getenv('DOCKER_TIMEOUT'))
+        sys.exit(1)
+
+    if not timeout > 0:
+        print(
+            "Provided timeout value needs to be greater than zero, currently: %s, exiting." % timeout)
+        sys.exit(1)
+
+    # Default base url for the connection
+    base_url = os.getenv('DOCKER_CONNECTION', 'unix://var/run/docker.sock')
+
+    try:
+        client = docker.AutoVersionClient(base_url=base_url, timeout=timeout)
+    except docker.errors.DockerException as e:
+        print("Error while creating the Docker client: %s" % e)
+        print(
+            "Please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
+        sys.exit(1)
+
+    if client and valid_docker_connection(client):
+        return client
+    else:
+        print(
+            "Could not connect to the Docker daemon, please make sure the Docker daemon is running.")
+
+        if os.environ.get('DOCKER_CONNECTION'):
+            print(
+                "If Docker daemon is running, please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
+
+        sys.exit(1)
+
+
+def valid_docker_connection(client):
+    try:
+        return client.ping()
+    except requests.exceptions.ConnectionError:
+        return False
diff --git a/pool/shard001/Python/0012996_fields.py b/pool/shard001/Python/0012996_fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4e7430aea0ac9c280d5647680501305d681cd36
--- /dev/null
+++ b/pool/shard001/Python/0012996_fields.py
@@ -0,0 +1,48 @@
+from django.db import models
+
+class IntegerListField(models.Field):
+    """
+    IntegerListField keeps a list of int as a comma-separated string.
+
+    >>> g = IntegerListField()
+    >>> g.get_db_prep_value([1,2,-1,20,30,40,-100])
+    '1,2,-1,20,30,40,-100'
+
+    >>> g.to_python('1,2,-10,3,4,-100,7')
+    [1,2,-10,3,4,-100,7]
+    """
+
+    description = "A list of integers"
+
+    __metaclass__ = models.SubfieldBase
+
+    def db_type(self,connection):
+        return 'text'
+
+    def to_python(self, value):
+        if isinstance(value, list):
+            return value
+
+        if value==None or value=='':
+            return []
+        else:
+            if value[0]=='[':
+                value = value[1:]
+            if value[-1]==']':
+                value = value[:-1]
+            return [ int(r) for r in value.split(',') ]
+
+    def get_prep_value(self, value):
+        return ','.join([str(r) for r in value])
+
+
+# south introspection
+from south.modelsinspector import add_introspection_rules
+add_introspection_rules(
+    [(
+            [IntegerListField],
+            [],
+            {},
+            ),
+     ], ["^application\.fields\.IntegerListField"])
+
diff --git a/pool/shard001/Python/0013014_custom_assistant.py b/pool/shard001/Python/0013014_custom_assistant.py
new file mode 100644
index 0000000000000000000000000000000000000000..29411f8486c8c625ae27e07236111fe0ac75a05a
--- /dev/null
+++ b/pool/shard001/Python/0013014_custom_assistant.py
@@ -0,0 +1,213 @@
+import subprocess
+import json
+from urllib import request as urllib
+import traceback
+import pexpect
+import atexit
+from gtts import gTTS
+import os
+import re
+import helpers
+import getpass
+from actions import actions
+from dictionary import dictionary
+""" Add custom commands for google assistant
+    If success there won't be feedback from google asssistant
+    Anyways, CustomAssistant has a function called _feedback which can be used to play an audio feedback
+"""
+import settings
+
+class CustomAssistant():
+    def __init__(self, assistant):
+        self.action = None
+        self.args = None
+        self.function = None
+        self.assistant = assistant
+        self.playshell = pexpect.spawn("mpsyt")
+        self.playing_music = False  # When music is paused is considered as playing
+        self.music_paused = False
+        self.delete_file = None
+        self.FNULL = open(os.devnull, 'w')  # needed to avoid output from subprocess.Popen
+        self.user = getpass.getuser()
+        # says wellcome message when the assistant starts
+        tts = gTTS(text=settings.wellcome_txt, lang='en')
+        if os.path.isfile("responses/wellcome.mp3"):
+            pass
+        else:
+            tts.save("responses/wellcome.mp3")
+        subprocess.Popen(["mpv", "responses/wellcome.mp3"], stdout=self.FNULL, shell=False)
+
+    """Reset some values
+    """
+    def clean(self):
+        self.args = None
+        self.action = None
+        self.function = None
+        if settings.DEBUG:
+            print("args cleaned")
+            print("action cleaned")
+            print("function cleaned")
+
+    """Play audio feedback when there is no other answer
+    """
+    def _feedback(self):
+        subprocess.Popen(["mpv", settings.audio_feedback], stdout=self.FNULL, shell=False)
+
+    """Run  in the shell
+       If shell in self.args killall will be added to the beginning
+    """
+    def run_command(self):  # run params
+        if "close" in self.args:
+            if self.args["command"] == "google-chrome":
+                self.args["command"] = "chrome"
+            command = helpers.append_helper(["killall"], self.args["command"])
+            subprocess.Popen(command, stdout=self.FNULL, shell=False)
+        else:
+            command = helpers.append_helper([], self.args["command"])
+            subprocess.Popen(command, stdout=self.FNULL, shell=False)
+    """Open  in browser
+    """
+    def open_in_browser(self):  # run params
+        subprocess.Popen(["xdg-open", "http://" + self.args["url"]], stdout=self.FNULL, shell=False)
+
+    """Search for 
+       The url for the search motor is loaded from settings.search_query
+       The browser where the search results will be shown is loaded from settings.browser
+    """
+    def search_for(self):
+        query = settings.search_query.format(urllib.quote(self.args["query"]))
+        subprocess.Popen(["xdg-open", query], stdout=self.FNULL, shell=False)
+
+    """Try action one by one and check if the pattern match the speech
+       and then start to process
+    """
+    def analice_text(self, text):
+        for action in actions.keys():
+            regex = re.compile(action)
+            m = regex.search(text)
+            if m:  # if there was a match
+                self.action = actions[action].copy()  # copy the action so the original dictionary is not modificated by accident
+                self.args = m.groupdict()  # get all variables from the speech
+
+                # check if a variable has a value in dictionary.py
+                # if there is a match the value of the variable will be changed for the one in the dictionary
+                for key in self.args.keys():
+                    if key in dictionary:
+                        for word in dictionary[key].keys():
+                            if self.args[key] == word:
+                                self.args[key] = dictionary[key][word]
+
+                if "additional_args" in self.action:
+                    for arg in self.action["additional_args"]:
+                        self.args.update({arg[0]:arg[1]})
+                break
+        if settings.DEBUG:
+            print("args: \n" + str(self.args))
+
+    """Search for something in mpsyt and play all the results
+    """
+    def play_music(self):
+        if not "query" in self.args and self.music_paused:
+            self.music_paused = False
+        else:
+            if self.playing_music:
+                self.playshell.sendcontrol("c")
+            self.playshell.sendline('/' + self.args["query"])
+            self.playshell.sendline("all")
+            self.playshell.send(" ")
+        self.playing_music = True
+
+    """Play next song
+    """
+    def next_song(self):
+        self.playshell.send('>')
+        self.playshell.send(' ')
+        self.playing_music = True
+
+    """Play previous song"""
+    def previous_song(self):
+        self.playshell.send('<')
+        self.playshell.send(' ')
+        self.playing_music = True
+
+    """Pause music"""
+    def stop_music(self):
+        if self.playing_music:
+            self.playing_music = False
+            self.music_paused = True
+
+    """Do something before process a new event"""
+    def before_do(self):
+        if self.delete_file:
+            os.remove(self.delete_file)
+            self.delete_file = None
+        if self.playing_music and not self.music_paused:
+            self.playshell.send(' ')
+
+    """Do something after process the event"""
+    def after_do(self):
+        if self.playing_music and not self.music_paused:
+            self.playshell.send(' ')
+
+    """If there is a success or error response for the action the assistant will talk the corresponding one
+    """
+    def play_response(self, filename, error=False):
+        if error:
+            response = "response_error"
+        else:
+            response = "response_success"
+        if response in self.action:
+            for key in self.args.keys():
+                try:
+                    self.action[response] = self.action[response].replace("<{key}>".format(key=key), self.args[key])
+                except TypeError:
+                    pass
+            tts = gTTS(text=self.action[response], lang='en')
+            file_name = "responses/{file_name}_{response}.mp3".format(file_name=filename.replace(" ", "_"), response=response)
+            if "cache_response" in self.action and self.action["cache_response"]:
+                if os.path.isfile(file_name):
+                    pass
+                else:
+                    tts.save(file_name)
+                subprocess.Popen(["mpv", file_name], stdout=self.FNULL, shell=False)
+            else:
+                tts.save(file_name)
+                subprocess.Popen(["mpv", file_name], stdout=self.FNULL, shell=False)
+                self.delete_file = file_name
+        elif not error:
+            self._feedback()
+        else:
+            pass
+
+    """The most useless function in the world"""
+    def no_action(self):
+        pass
+
+    """Make everithing work.
+       This will call analice_text, if there is an action that match the speech
+       the default response from the assistant will be ignored, the action
+       executed with the parameters and the sound feedback or success/error response played
+    """
+    def process(self, text):
+        self.analice_text(text)
+        try:
+            self.__getattribute__(self.action["action"])() # this will call the function
+            if settings.DEBUG:
+                print("CUSTOM ACTION")
+            error = False
+        except:
+            error = True
+            if settings.DEBUG:
+                traceback.print_exc()
+        if self.action:
+            self.assistant.stop_conversation()
+            self.play_response(text, error=error)
+        self.clean()
+    """What to do before exit"""
+    def exit(self):
+        self.playshell.close()
+        os.remove(self.delete_file)
+
+    """Register exit function"""
+    def at_exit(self):
+        atexit.register(self)
diff --git a/pool/shard001/Python/0013015_get_github_project_issues.py b/pool/shard001/Python/0013015_get_github_project_issues.py
new file mode 100644
index 0000000000000000000000000000000000000000..de2c5a98b42b26ecdf290b42230d7f53fb24a673
--- /dev/null
+++ b/pool/shard001/Python/0013015_get_github_project_issues.py
@@ -0,0 +1,118 @@
+
+"""
+This script uses GitHub APIs to fetch a list of issues associated with a project.
+It outputs issue numbers and titles for all cards in all columns of the project.
+The output is particularly useful for putting into the GitHub release notes.
+You can store your github token in the settings.secret.yml file, if you wish, as GITHUB_TOKEN
+"""
+
+import requests
+from requests.auth import HTTPBasicAuth
+import json
+import os
+import yaml
+import sys
+import re
+import getpass
+import argparse
+
+headers = {'Accept': 'application/vnd.github.inertia-preview+json'}
+
+parser = argparse.ArgumentParser(description='Parse a .po file')
+parser.add_argument('--column', help='the column name of the tickets you want to extract')
+parser.add_argument('--closeissues', action='store_true', help='Close all of the issues in the column')
+args = parser.parse_args()
+
+project_name = input('Enter the project name: ')
+print('\nEnter 1 to use GitHub token authorization (https://github.com/settings/tokens)')
+print('Enter 2 to use GitHub username and password: ')
+auth_pref = input('Enter 1 or 2: ')
+if auth_pref == '1':
+    CONFIG_PATH = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir, os.pardir, 'config', 'settings.secret.yml'))
+    with open(CONFIG_PATH, 'r') as fh:
+        app_settings = yaml.full_load(fh)
+    try:
+        token = app_settings['GITHUB_TOKEN']
+        print('Found your GitHub key in the settings file\n')
+    except KeyError:
+        token = getpass.getpass('GitHub token: ')
+    headers['Authorization'] = 'token %s' % token
+    auth = ''
+elif auth_pref == '2':
+    username = input('GitHub username: ')
+    password = getpass.getpass('GitHub password: ')
+    auth = HTTPBasicAuth(username, password)
+else:
+    print (type(auth_pref))
+    print('You must choose either 1 or 2.  You chose %s. Exiting.' % auth_pref)
+    sys.exit()
+
+projects_url = 'https://api.github.com/repos/mercycorps/TolaActivity/projects'
+columns_template = 'https://api.github.com/projects/%s/columns'
+cards_template = 'https://api.github.com/projects/columns/{}/cards'
+issue_template = 'https://api.github.com/repos/mercycorps/TolaActivity/issues/{}'
+
+# Get the project id
+print('Fetching data')
+response = requests.get(projects_url, headers=headers, auth=auth)
+projects = json.loads(response.text)
+project_id = ''
+columnn_ids = []
+for project in projects:
+    try:
+        pname = project['name'].strip()
+    except TypeError:
+        print('Exiting, failed to process this project:')
+        print(project)
+        sys.exit()
+    if project_name == pname:
+        project_id = project['id']
+        break
+else:
+    print("The project you entered couldn't be found in the list of your available projects. Exiting.")
+    sys.exit()
+
+# Get the columns ids associated with the project
+columns_url = columns_template % project_id
+response = requests.get(columns_url, headers=headers, auth=auth)
+cols_to_fetch = ['Done', 'Ready for Deploy']
+if args.column:
+    cols_to_fetch = [args.column]
+
+column_ids = [col['id'] for col in json.loads(response.text) if col['name'] in cols_to_fetch]
+issues = []
+for col_id in column_ids:
+
+    # Loop through each card in each column and the the issue data associated
+    # with the card
+    cards_url_partial = cards_template.format(col_id) + '?page={}'
+    page_num = 1
+    has_next = True
+    while has_next:
+        cards_url = cards_url_partial.format(page_num)
+        cards_response = requests.get(cards_url, headers=headers, auth=auth)
+        for card in json.loads(cards_response.text):
+            # If there is a note in the column, it will not have a content url and can be skipped
+            try:
+                match = re.search('(\d+)$', card['content_url'])
+            except KeyError:
+                continue
+            issue_num = match.group(1)
+            issue_url = issue_template.format(issue_num)
+            issue_response = requests.get(issue_url, headers=headers, auth=auth)
+            issues.append((issue_num, json.loads(issue_response.text)['title']))
+            if args.closeissues:
+                response = requests.patch(issue_url, headers=headers, auth=auth, json={'state': 'closed'})
+
+        if 'next' in cards_response.links:
+            page_num += 1
+        else:
+            has_next = False
+
+if issues:
+    issues.sort(key=lambda k: int(k[0]), reverse=True)
+    print('')
+    for i in issues:
+        print('#%s - %s' % i)
+else:
+    print("No cards in the column(s)", ', '.join(cols_to_fetch))
diff --git a/pool/shard001/Python/0013017_run_shell_cmd.py b/pool/shard001/Python/0013017_run_shell_cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ff3c78afcb97c5c7434cb75041d1ae0b0971071
--- /dev/null
+++ b/pool/shard001/Python/0013017_run_shell_cmd.py
@@ -0,0 +1,16 @@
+import subprocess
+
+def run_shell_cmd(cmd,cwd=[],echo=False):
+    """ run a command in the shell using Popen
+    """
+    stdout_holder=[]
+    if cwd:
+        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,cwd=cwd)
+    else:
+        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
+    for line in process.stdout:
+             if echo:
+                 print line.strip()
+             stdout_holder.append(line.strip())
+    process.wait()
+    return stdout_holder
diff --git a/pool/shard001/Python/0013023_test_subunit_tags.py b/pool/shard001/Python/0013023_test_subunit_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..a16edc1159113251c699048eeb76c1e155501b6e
--- /dev/null
+++ b/pool/shard001/Python/0013023_test_subunit_tags.py
@@ -0,0 +1,85 @@
+#
+#  subunit: extensions to python unittest to get test results from subprocesses.
+#  Copyright (C) 2005  Robert Collins 
+#
+#  Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
+#  license at the users choice. A copy of both licenses are available in the
+#  project source as Apache-2.0 and BSD. You may not use this file except in
+#  compliance with one of these two licences.
+#  
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
+#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+#  license you chose for the specific language governing permissions and
+#  limitations under that license.
+#
+
+"""Tests for subunit.tag_stream."""
+
+from io import BytesIO
+
+import testtools
+from testtools.matchers import Contains
+
+import subunit
+import subunit.test_results
+
+
+class TestSubUnitTags(testtools.TestCase):
+
+    def setUp(self):
+        super(TestSubUnitTags, self).setUp()
+        self.original = BytesIO()
+        self.filtered = BytesIO()
+
+    def test_add_tag(self):
+        # Literal values to avoid set sort-order dependencies. Python code show
+        # derivation.
+        # reference = BytesIO()
+        # stream = subunit.StreamResultToBytes(reference)
+        # stream.status(
+        #     test_id='test', test_status='inprogress', test_tags=set(['quux', 'foo']))
+        # stream.status(
+        #     test_id='test', test_status='success', test_tags=set(['bar', 'quux', 'foo']))
+        reference = [
+            b'\xb3)\x82\x17\x04test\x02\x04quux\x03foo\x05\x97n\x86\xb3)'
+                b'\x83\x1b\x04test\x03\x03bar\x04quux\x03fooqn\xab)',
+            b'\xb3)\x82\x17\x04test\x02\x04quux\x03foo\x05\x97n\x86\xb3)'
+                b'\x83\x1b\x04test\x03\x04quux\x03foo\x03bar\xaf\xbd\x9d\xd6',
+            b'\xb3)\x82\x17\x04test\x02\x04quux\x03foo\x05\x97n\x86\xb3)'
+                b'\x83\x1b\x04test\x03\x04quux\x03bar\x03foo\x03\x04b\r',
+            b'\xb3)\x82\x17\x04test\x02\x04quux\x03foo\x05\x97n\x86\xb3)'
+                b'\x83\x1b\x04test\x03\x03bar\x03foo\x04quux\xd2\x18\x1bC',
+            b'\xb3)\x82\x17\x04test\x02\x03foo\x04quux\xa6\xe1\xde\xec\xb3)'
+                b'\x83\x1b\x04test\x03\x03foo\x04quux\x03bar\x08\xc2X\x83',
+            b'\xb3)\x82\x17\x04test\x02\x03foo\x04quux\xa6\xe1\xde\xec\xb3)'
+                b'\x83\x1b\x04test\x03\x03bar\x03foo\x04quux\xd2\x18\x1bC',
+            b'\xb3)\x82\x17\x04test\x02\x03foo\x04quux\xa6\xe1\xde\xec\xb3)'
+                b'\x83\x1b\x04test\x03\x03foo\x03bar\x04quux:\x05e\x80',
+            ]
+        stream = subunit.StreamResultToBytes(self.original)
+        stream.status(
+            test_id='test', test_status='inprogress', test_tags=set(['foo']))
+        stream.status(
+            test_id='test', test_status='success', test_tags=set(['foo', 'bar']))
+        self.original.seek(0)
+        self.assertEqual(
+            0, subunit.tag_stream(self.original, self.filtered, ["quux"]))
+        self.assertThat(reference, Contains(self.filtered.getvalue()))
+
+    def test_remove_tag(self):
+        reference = BytesIO()
+        stream = subunit.StreamResultToBytes(reference)
+        stream.status(
+            test_id='test', test_status='inprogress', test_tags=set(['foo']))
+        stream.status(
+            test_id='test', test_status='success', test_tags=set(['foo']))
+        stream = subunit.StreamResultToBytes(self.original)
+        stream.status(
+            test_id='test', test_status='inprogress', test_tags=set(['foo']))
+        stream.status(
+            test_id='test', test_status='success', test_tags=set(['foo', 'bar']))
+        self.original.seek(0)
+        self.assertEqual(
+            0, subunit.tag_stream(self.original, self.filtered, ["-bar"]))
+        self.assertEqual(reference.getvalue(), self.filtered.getvalue())
diff --git a/pool/shard001/Python/0013026_ActivityMonitor.py b/pool/shard001/Python/0013026_ActivityMonitor.py
new file mode 100644
index 0000000000000000000000000000000000000000..e99301593782e6605c081a542d6964c477b9dd26
--- /dev/null
+++ b/pool/shard001/Python/0013026_ActivityMonitor.py
@@ -0,0 +1,112 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE
+#
+##############################################################################
+"""ZODB transfer activity monitoring
+
+$Id$"""
+
+import threading
+import time
+
+
+class ActivityMonitor:
+    """ZODB load/store activity monitor
+
+    This simple implementation just keeps a small log in memory
+    and iterates over the log when getActivityAnalysis() is called.
+
+    It assumes that log entries are added in chronological sequence.
+    """
+
+    def __init__(self, history_length=3600):
+        self.history_length = history_length  # Number of seconds
+        self.log = []                     # [(time, loads, stores)]
+        self.trim_lock = threading.Lock()
+
+    def closedConnection(self, conn):
+        log = self.log
+        now = time.time()
+        loads, stores = conn.getTransferCounts(1)
+        log.append((now, loads, stores))
+        self.trim(now)
+
+    def trim(self, now):
+        self.trim_lock.acquire()
+        
+        log = self.log
+        cutoff = now - self.history_length
+        n = 0
+        loglen = len(log)
+        while n < loglen and log[n][0] < cutoff:
+            n = n + 1
+        if n:
+            del log[:n]
+        
+        self.trim_lock.release()
+
+    def setHistoryLength(self, history_length):
+        self.history_length = history_length
+        self.trim(time.time())
+
+    def getHistoryLength(self):
+        return self.history_length
+
+    def getActivityAnalysis(self, start=0, end=0, divisions=10):
+        res = []
+        now = time.time()
+        if start == 0:
+            start = now - self.history_length
+        if end == 0:
+            end = now
+        for n in range(divisions):
+            res.append({
+                'start': start + (end - start) * n / divisions,
+                'end': start + (end - start) * (n + 1) / divisions,
+                'loads': 0,
+                'stores': 0,
+                'connections': 0,
+                })
+
+        div = res[0]
+        div_end = div['end']
+        div_index = 0
+        connections = 0
+        total_loads = 0
+        total_stores = 0
+        for t, loads, stores in self.log:
+            if t < start:
+                # We could use a binary search to find the start.
+                continue
+            elif t > end:
+                # We could use a binary search to find the end also.
+                break
+            while t > div_end:
+                div['loads'] = total_loads
+                div['stores'] = total_stores
+                div['connections'] = connections
+                total_loads = 0
+                total_stores = 0
+                connections = 0
+                div_index = div_index + 1
+                if div_index < divisions:
+                    div = res[div_index]
+                    div_end = div['end']
+            connections = connections + 1
+            total_loads = total_loads + loads
+            total_stores = total_stores + stores
+
+        div['stores'] = div['stores'] + total_stores
+        div['loads'] = div['loads'] + total_loads
+        div['connections'] = div['connections'] + connections
+
+        return res
diff --git a/pool/shard001/Python/0013027_libs_drupe.py b/pool/shard001/Python/0013027_libs_drupe.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4928c616dab002f2187c4ebbd5efeb9ed67ffd6
--- /dev/null
+++ b/pool/shard001/Python/0013027_libs_drupe.py
@@ -0,0 +1,232 @@
+from __future__ import print_function
+from builtins import str
+from builtins import bytes
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+import os
+import time
+from builtins import input
+from datetime import datetime
+tmp_file_location = '/dev/shm/'
+
+
+def fyi(text):
+    print('    ' + text)
+
+
+def info(text):
+    print('>>> ' + text)
+
+
+def get_config_real():
+    from configobj import ConfigObj
+    if not os.path.exists(os.path.join(os.getenv('HOME'), '.config')):
+        os.makedirs(os.path.join(os.getenv('HOME'), '.config'))
+    config_filename = os.path.join(os.getenv('HOME'), '.config',
+                                   'drupebox')
+    if not path_exists(config_filename):
+        config = ConfigObj()
+        config.filename = config_filename
+        import dropbox
+
+        # Get your app key and secret from the Dropbox developer website
+
+        app_key = '1skff241na3x0at'
+        app_secret = 'srd8w4mvppiq9vg'
+
+        flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key,
+                app_secret)
+        authorize_url = flow.start()
+        print(('1. Go to: ' + authorize_url))
+        print('2. Click "Allow" (you might have to log in first)')
+        print('3. Copy the authorization code.')
+        code = input('Enter the authorization code here: ').strip()
+        result = flow.finish(code)
+        (config['access_token'], config['user_id']) = result.access_token, result.user_id
+        config['dropbox_local_path'] = \
+            input('Enter dropbox local path (or press enter for '
+                      + os.path.join(os.getenv('HOME'), 'Dropbox')
+                      + '/) ').strip()
+        if config['dropbox_local_path'] == '':
+            config['dropbox_local_path'] = os.path.join(os.getenv('HOME'
+                    ), 'Dropbox') + '/'
+        if config['dropbox_local_path'][-1] != "/":
+            config['dropbox_local_path'] = config['dropbox_local_path']+"/"
+        if not path_exists(config['dropbox_local_path']):
+            os.makedirs(config['dropbox_local_path'])    
+        config['max_file_size'] = 10000000
+        config['excluded_paths'] = ["\"/home/pi/SUPER SECRET LOCATION 1\"", "\"/home/pi/SUPERSECRET LOCATION 2\""]
+        config.write()
+
+    config = ConfigObj(config_filename)
+    return config
+
+
+def get_config():
+    if get_config.cache == '': #First run
+        get_config.cache = get_config_real()
+    return get_config.cache
+
+
+get_config.cache = ''
+
+
+def dump(text, name):
+    text = str(text)
+    with open(tmp_file_location + name, 'wb') as f:
+        f.write(bytes(text.encode()))
+
+
+def get_tree():
+    tree = []
+    for (root, dirs, files) in os.walk(get_config()['dropbox_local_path'],
+            topdown=True, followlinks=True):
+        for name in files:
+            tree.append(os.path.join(root, name))
+        for name in dirs:
+            tree.append(os.path.join(root, name))
+    tree.sort(key = lambda s: -len(s)) #sort longest to smallest so that later files get deleted before the folders that they are in
+    return tree
+
+
+def store_tree(tree):
+    tree = '\n'.join(tree)
+    dump(tree, 'drupebox_last_seen_files')
+
+
+def load_tree():
+    try:
+        last_tree = open(tmp_file_location + 'drupebox_last_seen_files', 'r').read()
+    except:
+        last_tree = ''
+    last_tree = last_tree.split('\n')
+
+    return last_tree
+
+
+def determine_deleted_files(tree_now, tree_last):
+    deleted = []
+    if tree_last == ['']:
+        return []
+    for element in tree_last:
+        if not element in tree_now:
+            deleted.append(element)
+    return deleted
+
+
+def upload(client, local_file_path, remote_file_path):
+    print('uuu', local_file_path)
+    f = open(local_file_path, 'rb')
+    import dropbox #FIXME this must not be necessary
+    client.files_upload(f.read(), remote_file_path, mute=True, mode=dropbox.files.WriteMode("overwrite",None))
+    #response = client.put_file(remote_file_path, f, overwrite=True)
+
+
+def download(client, remote_file_path, local_file_path):
+    print('ddd', remote_file_path)
+    client.files_download_to_file(local_file_path, remote_file_path)
+    #(f, metadata) = client.get_file_and_metadata(remote_file_path)
+    #out = open(local_file_path, 'wb')
+    #out.write(f.read())
+    #out.close()
+
+
+    # print metadata
+
+def unix_time(timer):
+    return time.mktime(timer.timetuple()) # time.mktime(datetime.strptime(timer, '%a, %d %b %Y %H:%M:%S +0000').timetuple())
+
+
+def readable_time(timepoint):
+    return datetime.fromtimestamp(float(timepoint)).strftime('%a, %d %b %Y %H:%M:%S +0000'
+            )
+
+
+def path_exists(path):
+    try:
+        os.stat(path)
+        return True
+    except:
+        return False
+
+
+def local_item_modified_time(local_file_path):
+    return os.path.getmtime(local_file_path)
+
+def fp(path):
+	#Fix path function as dropbox root folder is "" not "/"
+	if path == "":
+		return path
+	if path == "/":
+		return ""
+	else:
+		if path[0] != "/":
+			return "/" + path
+		else:
+			return path
+
+def fix_local_time(client, remote_file_path):
+    remote_path = remote_file_path
+    extra_path = '/'.join(remote_path.split('/')[0:-1])
+    info('fix local time on ' + remote_file_path)
+
+    tmp_folder = client.files_list_folder(fp(extra_path)).entries #client.metadata('/' + extra_path)['contents']
+    for tmp_item in tmp_folder:
+        if tmp_item.path_display == remote_path:
+            break  # found it
+    tmp_time = tmp_item.client_modified
+    os.utime(get_config()['dropbox_local_path'] + remote_path,
+             (int(unix_time(tmp_time)), int(unix_time(tmp_time))))
+
+
+def skip(local_file_path):
+    local_item = local_file_path.split('/')[-1]
+    if local_item[0:len('.fuse_hidden')] == '.fuse_hidden':
+        fyi('ignore fuse hidden files')
+        return True
+    if local_item[-len('.pyc'):] == '.pyc':
+        fyi('ignore .pyc files')
+        return True
+    if local_item[-len('__pycache__'):] == '__pycache__':
+        fyi('ignore __pycache__')
+        return True
+    else:
+        try:
+            local_time = local_item_modified_time(local_file_path)
+        except:
+            print(('crash on local time check on', local_item))
+            return True
+        return False
+
+
+def local_item_not_found_at_remote(remote_folder, remote_file_path):
+    remote_path = remote_file_path
+    extra_path = '/'.join(remote_path.split('/')[0:-1])
+    remote_folder_path = extra_path
+
+    # remote_folder = client.metadata('/'+remote_folder_path)['contents']
+
+    unnaccounted_local_file = True
+    for tmp_item in remote_folder:
+        if tmp_item.path_display == remote_file_path:
+            unnaccounted_local_file = False
+    return unnaccounted_local_file
+
+
+def remote_item_modified_with_deleted(client, remote_file_path):
+    remote_path = remote_file_path
+    extra_path = '/'.join(remote_path.split('/')[0:-1])
+    remote_folder_path = extra_path
+    remote_folder_with_deleted = client.files_list_folder(fp(remote_folder_path),include_deleted=True).entries # client.metadata('/' + remote_folder_path, include_deleted=True)['contents']
+    folder_with_deleted = remote_folder_with_deleted
+    remote_time = 0
+    import dropbox #FIXME this must not be necessary
+    for unn_item in folder_with_deleted:
+        print(unn_item)
+        if unn_item.path_display == remote_file_path:
+            if isinstance(unn_item, dropbox.files.DeletedMetadata): # unn_item.tag == "deleted": #'is_deleted' in unn_item and unn_item['is_deleted'] == True:
+                remote_time = unix_time(unn_item.client_modified)
+                break
+    return remote_time
+
+
diff --git a/pool/shard001/Python/0013042_api.py b/pool/shard001/Python/0013042_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..955eaa32a7dc99f63881a21623d89edb7597f9cb
--- /dev/null
+++ b/pool/shard001/Python/0013042_api.py
@@ -0,0 +1,86 @@
+#
+# $Id: api.py 194 2007-04-05 15:31:53Z cameron $
+#
+
+from defines import *
+
+class api:
+    def __init__(self, parent=None):
+        self.attributes = {}                    # initialize attributes
+        
+        self.attributes["Match"] = 1            # Match attribute set to 1 tells the main program we can be used to match 
+        self.attributes["Diff"] = 1             # Diff  attribute set to 1 tells the main program we can be used to diff
+        self.attributes["Level"] = FUNCTION_LEVEL | BASIC_BLOCK_LEVEL   # these flags indicated we can diff/match both functions and basic blocks
+        self.parent = parent                    # set up the parent
+        
+        self.module_name = "API"                # give the module a name
+        self.author      = "Peter Silberman"    # author name
+        self.description = "API module uses the api calls as a signature"
+        self.date        = "09/22/06"
+        self.homepage    = "http://www.openrce.org"
+        self.contact     = "peter.silberman@gmail.com"
+        self.accuracy    = ACCURACY_LOW
+        
+        self.parent.register_match_function(    self.match_function_by_api,    self )   # register a function matching routine
+        self.parent.register_match_basic_block( self.match_basic_block_by_api, self )   # register a basic block matching routine
+        self.parent.register_diff_function(     self.diff_function_by_api,     self )   # register a function diffing routine
+        self.parent.register_module(self)                                               # register our module in the module table
+        
+    def match_function_by_api(self, function_a, function_b):
+        if len(function_a.ext["PAIMEIDiffFunction"].refs_api) <= 1 or len(function_b.ext["PAIMEIDiffFunction"].refs_api) <= 1:
+            return 0
+        if len(function_a.ext["PAIMEIDiffFunction"].refs_api) != len(function_b.ext["PAIMEIDiffFunction"].refs_api):
+            return 0
+            
+        matched = 0
+        for call_a in function_a.ext["PAIMEIDiffFunction"].refs_api:
+            ea, api_call_a = call_a
+            for call_b in function_b.ext["PAIMEIDiffFunction"].refs_api:
+                ea, api_call_b = call_b
+                if api_call_a == api_call_b:
+                    matched = 1
+                    break
+            if not matched:
+                return 0
+            matched = 0
+        return 1
+        
+    def match_basic_block_by_api(self, bb_a, bb_b):
+        if len(bb_a.ext["PAIMEIDiffBasicBlock"].refs_api) != len(bb_b.ext["PAIMEIDiffBasicBlock"].refs_api):
+            return 0
+            
+        if len(bb_a.ext["PAIMEIDiffBasicBlock"].refs_api) <= 0 or len(bb_b.ext["PAIMEIDiffBasicBlock"].refs_api) <= 0:
+            return 0
+
+        matched = 0
+        for call_a in bb_a.ext["PAIMEIDiffBasicBlock"].refs_api:
+            ea, api_call_a = call_a
+            for call_b in bb_b.ext["PAIMEIDiffBasicBlock"].refs_api:
+                ea, api_call_b = call_b
+                if api_call_a == api_call_b:
+                    matched = 1
+                    break
+            if not matched:
+                return 0
+            matched = 0
+        return 1    
+        
+    def diff_function_by_api(self, function_a, function_b):
+        if len(function_a.ext["PAIMEIDiffFunction"].refs_api) <= 1 or len(function_b.ext["PAIMEIDiffFunction"].refs_api) <= 1:
+            return 0
+        
+        if len(function_a.ext["PAIMEIDiffFunction"].refs_api) != len(function_b.ext["PAIMEIDiffFunction"].refs_api):
+            return 1
+        matched = 0
+        for call_a in function_a.ext["PAIMEIDiffFunction"].refs_api:
+            ea, api_call_a = call_a
+            for call_b in function_b.ext["PAIMEIDiffFunction"].refs_api:
+                ea, api_call_b = call_b
+                if api_call_a == api_call_b:
+                    matched = 1
+                    break
+            if not matched:
+                return 1
+            matched = 0
+        return 0
+        
diff --git a/pool/shard001/Python/0013043_texture_compression_rgtc.py b/pool/shard001/Python/0013043_texture_compression_rgtc.py
new file mode 100644
index 0000000000000000000000000000000000000000..4303aa9a0792e588b7547b146e08f44bcd06b372
--- /dev/null
+++ b/pool/shard001/Python/0013043_texture_compression_rgtc.py
@@ -0,0 +1,18 @@
+'''Autogenerated by xml_generate script, do not edit!'''
+from OpenGL import platform as _p, arrays
+# Code generation uses this
+from OpenGL.raw.GL import _types as _cs
+# End users want this...
+from OpenGL.raw.GL._types import *
+from OpenGL.raw.GL import _errors
+from OpenGL.constant import Constant as _C
+
+import ctypes
+_EXTENSION_NAME = 'GL_ARB_texture_compression_rgtc'
+def _f( function ):
+    return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_texture_compression_rgtc',error_checker=_errors._error_checker)
+GL_COMPRESSED_RED_RGTC1=_C('GL_COMPRESSED_RED_RGTC1',0x8DBB)
+GL_COMPRESSED_RG_RGTC2=_C('GL_COMPRESSED_RG_RGTC2',0x8DBD)
+GL_COMPRESSED_SIGNED_RED_RGTC1=_C('GL_COMPRESSED_SIGNED_RED_RGTC1',0x8DBC)
+GL_COMPRESSED_SIGNED_RG_RGTC2=_C('GL_COMPRESSED_SIGNED_RG_RGTC2',0x8DBE)
+
diff --git a/pool/shard001/Python/0013046_process_thickness_qsub.py b/pool/shard001/Python/0013046_process_thickness_qsub.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e7aafab8bf542ddd2ea7122f4ffc33a82570041
--- /dev/null
+++ b/pool/shard001/Python/0013046_process_thickness_qsub.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+"""
+Created on Thu Apr 27 12:16:26 2017
+
+@author: Anand A Joshi, Divya Varadarajan
+"""
+
+import sys
+from os import system
+from os.path import isfile, split
+from multiprocessing import Pool
+from contextlib import closing
+import configparser
+import glob
+#config_file = '/big_disk/ajoshi/coding_ground/\
+#brainsuite-workflows/data/sample_data/thickness.cfg'
+
+config_file = sys.argv[1]
+Config = configparser.ConfigParser()
+Config.read(config_file)
+Config.sections()
+
+STUDY_DIR = Config.get('CSESVREG', 'STUDY_DIR')
+NPROC = int(Config.get('CSESVREG', 'NPROC'))
+BST_INSTALL = Config.get('CSESVREG', 'BST_INSTALL')
+SVREG_ATLAS = Config.get('CSESVREG', 'SVREG_ATLAS')
+THICKNESSPVC_EXE = Config.get('THICKNESS', 'THICKNESSPVC_EXE')
+GENERATE_STATS_EXE = Config.get('THICKNESS', 'GENERATE_STATS_EXE')
+SMOOTHNESS = Config.get('THICKNESS', 'SMOOTHNESS')
+SMOOTHNESS_EXE = Config.get('THICKNESS', 'SMOOTHNESS_EXE')
+
+sublist = lst = glob.glob(STUDY_DIR+'/*')
+
+
+ind = 0
+cmdln1 = []
+cmdln2 = []
+cmdln3 = []
+cmdln4 = []
+
+for sub in sublist:
+
+    img = sub + '/anat/t1.nii.gz'
+
+    if not isfile(img):
+        continue
+# Check if the workflow has already been run
+    subpath, filename = split(img)
+    fname = subpath + '/atlas.pvc-thickness_0-6mm.right.\
+smooth_' + SMOOTHNESS + 'mm.dfs'
+    if isfile(fname):
+        continue
+
+    surfname = subpath + '/atlas.left.mid.cortex.svreg.dfs'
+    if not isfile(surfname): 
+        cmdln1.append('qsub -q long.q -l h_vmem=23G -cwd ' + THICKNESSPVC_EXE +
+                  ' ' + img[:-7])
+    cmdln2.append('qsub -q long.q -l h_vmem=23G -cwd ' + GENERATE_STATS_EXE +
+                  ' ' + img[:-7])
+    outsurfname = subpath + '/atlas.pvc-thickness_0-6mm.left.\
+smooth_' + SMOOTHNESS + 'mm.dfs'
+
+    if not isfile(outsurfname): 
+        cmdln3.append('qsub -q long.q -l h_vmem=23G -cwd ' + SMOOTHNESS_EXE +
+                      ' ' + surfname + ' ' + surfname + ' \
+' + outsurfname)
+    surfname = subpath + '/atlas.right.mid.cortex.svreg.dfs'
+    outsurfname = subpath + '/atlas.pvc-thickness_0-6mm.right.\
+smooth_' + SMOOTHNESS + 'mm.dfs'
+
+    if not isfile(outsurfname): 
+        cmdln4.append('qsub -q long.q -l h_vmem=23G -cwd ' +
+                      SMOOTHNESS_EXE + ' ' + surfname + ' ' + surfname + ' \
+' + outsurfname)
+
+    print(cmdln1)
+    ind += 1
+
+with closing(Pool(NPROC)) as p:
+    p.map(system, cmdln1)
+    p.terminate()
+
+with closing(Pool(NPROC)) as p:
+    p.map(system, cmdln2)
+    p.terminate()
+
+with closing(Pool(NPROC)) as p:
+    p.map(system, cmdln3)
+    p.terminate()
+
+with closing(Pool(NPROC)) as p:
+    p.map(system, cmdln4)
+    p.terminate()
+
+print("Thickness Computations Done")
diff --git a/pool/shard001/Python/0013050_PreferencesRfcSearchDialog.py b/pool/shard001/Python/0013050_PreferencesRfcSearchDialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..b52f37e9a6a8ea644469ba4ac0f13e5bc412a582
--- /dev/null
+++ b/pool/shard001/Python/0013050_PreferencesRfcSearchDialog.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+### BEGIN LICENSE
+# Copyright (C) 2010 hemanth.hm hemanth.hm@gmail.com
+# This program is free software: you can redistribute it and/or modify it 
+# under the terms of the GNU General Public License version 3, as published 
+# by the Free Software Foundation.
+# 
+# This program is distributed in the hope that it will be useful, but 
+# WITHOUT ANY WARRANTY; without even the implied warranties of 
+# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
+# PURPOSE.  See the GNU General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License along 
+# with this program.  If not, see .
+### END LICENSE
+
+from desktopcouch.records.server import CouchDatabase
+from desktopcouch.records.record import Record
+import gtk
+
+from rfc_search.helpers import get_builder
+
+import gettext
+from gettext import gettext as _
+gettext.textdomain('rfc-search')
+
+class PreferencesRfcSearchDialog(gtk.Dialog):
+    __gtype_name__ = "PreferencesRfcSearchDialog"
+    preferences = {}
+
+    def __new__(cls):
+        """Special static method that's automatically called by Python when 
+        constructing a new instance of this class.
+        
+        Returns a fully instantiated PreferencesRfcSearchDialog object.
+        """
+        builder = get_builder('PreferencesRfcSearchDialog')
+        new_object = builder.get_object("preferences_rfc_search_dialog")
+        new_object.finish_initializing(builder)
+        return new_object
+
+    def finish_initializing(self, builder):
+        """Called while initializing this instance in __new__
+
+        finish_initalizing should be called after parsing the ui definition
+        and creating a PreferencesRfcSearchDialog object with it in order to
+        finish initializing the start of the new PerferencesRfcSearchDialog
+        instance.
+        
+        Put your initialization code in here and leave __init__ undefined.
+        """
+
+        # Get a reference to the builder and set up the signals.
+        self.builder = builder
+        self.builder.connect_signals(self)
+
+        # Set up couchdb and the preference info.
+        self._db_name = "rfc-search"
+        self._database = CouchDatabase(self._db_name, create=True)
+        self._preferences = None
+        self._key = None
+
+        # Set the record type and then initalize the preferences.
+        self._record_type = (
+            "http://wiki.ubuntu.com/Quickly/RecordTypes/RfcSearch/"
+            "Preferences")
+        self._preferences = self.get_preferences()
+        # TODO: code for other initialization actions should be added here
+
+    def get_preferences(self):
+        """Return a dict of preferences for rfc-search.
+
+        Creates a couchdb record if necessary.
+        """
+        if self._preferences == None:
+            # The dialog is initializing.
+            self._load_preferences()
+
+        # If there were no saved preference, this.
+        return self._preferences
+
+    def _load_preferences(self):
+        # TODO: add preferences to the self._preferences dict default
+        # preferences that will be overwritten if some are saved
+        self._preferences = {"record_type": self._record_type}
+
+        results = self._database.get_records(
+            record_type=self._record_type, create_view=True)
+
+        if len(results.rows) == 0:
+            # No preferences have ever been saved, save them before returning.
+            self._key = self._database.put_record(Record(self._preferences))
+        else:
+            self._preferences = results.rows[0].value
+            del self._preferences['_rev']
+            self._key = results.rows[0].value["_id"]
+
+    def _save_preferences(self):
+        self._database.update_fields(self._key, self._preferences)
+
+    def ok(self, widget, data=None):
+        """The user has elected to save the changes.
+
+        Called before the dialog returns gtk.RESONSE_OK from run().
+        """
+
+        # Make any updates to self._preferences here. e.g.
+        #self._preferences["preference1"] = "value2"
+        self._save_preferences()
+
+    def cancel(self, widget, data=None):
+        """The user has elected cancel changes.
+
+        Called before the dialog returns gtk.RESPONSE_CANCEL for run()
+        """
+        # Restore any changes to self._preferences here.
+        pass
+
+if __name__ == "__main__":
+    dialog = PreferencesRfcSearchDialog()
+    dialog.show()
+    gtk.main()
diff --git a/pool/shard001/Python/0013052_ops_command.py b/pool/shard001/Python/0013052_ops_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0354ba126cc050f19c8eeacdc99b6bcc951fead
--- /dev/null
+++ b/pool/shard001/Python/0013052_ops_command.py
@@ -0,0 +1,166 @@
+#!/usr/bin/python
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible.  If not, see .
+#
+
+DOCUMENTATION = """
+---
+module: ops_command
+version_added: "2.1"
+author: "Peter sprygada (@privateip)"
+short_description: Run arbitrary commands on OpenSwitch devices.
+description:
+  - Sends arbitrary commands to an OpenSwitch node and returns the results
+    read from the device. The M(ops_command) module includes an
+    argument that will cause the module to wait for a specific condition
+    before returning or timing out if the condition is not met.
+extends_documentation_fragment: openswitch
+options:
+  commands:
+    description:
+      - List of commands to send to the remote ops device over the
+        configured provider. The resulting output from the command
+        is returned. If the I(waitfor) argument is provided, the
+        module is not returned until the condition is satisfied or
+        the number of retires as expired.
+    required: true
+  waitfor:
+    description:
+      - List of conditions to evaluate against the output of the
+        command. The task will wait for a each condition to be true
+        before moving forward. If the conditional is not true
+        within the configured number of retries, the task fails.
+        See examples.
+    required: false
+    default: null
+  retries:
+    description:
+      - Specifies the number of retries a command should by tried
+        before it is considered failed. The command is run on the
+        target device every retry and evaluated against the
+        waitfor conditions.
+    required: false
+    default: 10
+  interval:
+    description:
+      - Configures the interval in seconds to wait between retries
+        of the command. If the command does not pass the specified
+        conditions, the interval indicates how long to wait before
+        trying the command again.
+    required: false
+    default: 1
+"""
+
+EXAMPLES = """
+- ops_command:
+    commands:
+      - show version
+  register: output
+
+- ops_command:
+    commands:
+      - show version
+    waitfor:
+      - "result[0] contains OpenSwitch"
+
+- ops_command:
+  commands:
+    - show version
+    - show interfaces
+"""
+
+RETURN = """
+stdout:
+  description: the set of responses from the commands
+  returned: always
+  type: list
+  sample: ['...', '...']
+
+stdout_lines:
+  description: The value of stdout split into a list
+  returned: always
+  type: list
+  sample: [['...', '...'], ['...'], ['...']]
+
+failed_conditions:
+  description: the conditionals that failed
+  retured: failed
+  type: list
+  sample: ['...', '...']
+"""
+
+import time
+
+def to_lines(stdout):
+    for item in stdout:
+        if isinstance(item, basestring):
+            item = str(item).split('\n')
+        yield item
+
+def main():
+    spec = dict(
+        commands=dict(type='list'),
+        waitfor=dict(type='list'),
+        retries=dict(default=10, type='int'),
+        interval=dict(default=1, type='int'),
+        transport=dict(default='cli', choices=['cli'])
+    )
+
+    module = get_module(argument_spec=spec,
+                        supports_check_mode=True)
+
+    commands = module.params['commands']
+
+    retries = module.params['retries']
+    interval = module.params['interval']
+
+    try:
+        queue = set()
+        for entry in (module.params['waitfor'] or list()):
+            queue.add(Conditional(entry))
+    except AttributeError:
+        exc = get_exception()
+        module.fail_json(msg=exc.message)
+
+    result = dict(changed=False)
+
+    while retries > 0:
+        response = module.execute(commands)
+        result['stdout'] = response
+
+        for item in list(queue):
+            if item(response):
+                queue.remove(item)
+
+        if not queue:
+            break
+
+        time.sleep(interval)
+        retries -= 1
+    else:
+        failed_conditions = [item.raw for item in queue]
+        module.fail_json(msg='timeout waiting for value', failed_conditions=failed_conditions)
+
+    result['stdout_lines'] = list(to_lines(result['stdout']))
+    return module.exit_json(**result)
+
+from ansible.module_utils.basic import *
+from ansible.module_utils.shell import *
+from ansible.module_utils.netcfg import *
+from ansible.module_utils.openswitch import *
+if __name__ == '__main__':
+        main()
+
diff --git a/pool/shard001/Python/0013053_jsdatetime.py b/pool/shard001/Python/0013053_jsdatetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0d7d8b6a38d47a0e78c7f42f621bb3f6a3bf69e
--- /dev/null
+++ b/pool/shard001/Python/0013053_jsdatetime.py
@@ -0,0 +1,58 @@
+"""
+Collection of functions that transform javascript date objects into python
+datetime objects and vice versa.
+"""
+
+
+import datetime as dt
+
+
+JS_EPOCH = dt.datetime(1970, 1, 1)
+
+
+def todaystr():
+    return dt.datetime.now().strftime('%d-%m-%Y')
+
+
+def now_iso():
+    """
+    The date-timestamp of the moment now is called in ISO 8601 format.
+    """
+    return dt.datetime.now().isoformat().split('.')[0] + 'Z'
+
+
+def round_js_to_date(js_datetime):
+    date_time = js_to_datetime(js_datetime)
+    round_datetime = dt.datetime.combine(date_time.date(),
+                                         dt.datetime.min.time())
+    return datetime_to_js(round_datetime)
+
+
+def datetime_to_js(date_time):
+    if date_time is not None:
+        return int((date_time - JS_EPOCH).total_seconds() * 1000)
+
+
+def js_to_datetime(date_time):
+    if date_time is not None:
+        return JS_EPOCH + dt.timedelta(seconds=date_time/1000)
+
+
+def js_to_datestring(js_date, iso=False):
+    date_time = js_to_datetime(js_date)
+    return datetime_to_datestring(date_time, iso)
+
+
+def datetime_to_datestring(date_time, iso=False):
+    if iso:
+        return date_time.strftime('%Y-%m-%d')
+    else:
+        return date_time.strftime('%d-%m-%Y')
+
+
+def datestring_to_js(date_string, iso=False):
+    if iso:
+        date_time = dt.datetime.strptime(date_string, '%Y-%m-%d')
+    else:
+        date_time = dt.datetime.strptime(date_string, '%d-%m-%Y')
+    return datetime_to_js(date_time)
diff --git a/pool/shard001/Python/0013055_fastest_test.py b/pool/shard001/Python/0013055_fastest_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..282629b3ceba19c57bfe9063851b5eb06dd0eca4
--- /dev/null
+++ b/pool/shard001/Python/0013055_fastest_test.py
@@ -0,0 +1,26 @@
+#! /usr/bin/env python
+###############################################################################
+##
+## fastest_test.py -- part of the bypasser program
+##
+## Copyright (c) 2014 Riccardo Sven Risuleo 
+##
+## This software may be modified and distributed under the terms
+## of the MIT license.  See the LICENSE file for details.
+##
+###############################################################################
+
+import cv2
+from behaviours.fastest import Fastest
+
+cv2.namedWindow('test')
+cv2.waitKey(20)
+
+fast = Fastest('test')
+
+fast.push((1,100))
+print(fast.condition()) # Returns true... is the fastest
+fast.push((1,49))
+print(fast.condition()) # Returns false... speed lower than before!
+fast.show()
+
diff --git a/pool/shard001/Python/0013057_DocumentationComment.py b/pool/shard001/Python/0013057_DocumentationComment.py
new file mode 100644
index 0000000000000000000000000000000000000000..6517183b15d3ef99a95616ddd17f3b2de4d4ea9d
--- /dev/null
+++ b/pool/shard001/Python/0013057_DocumentationComment.py
@@ -0,0 +1,77 @@
+import inspect
+from collections import OrderedDict
+
+from coalib.misc.Enum import enum
+
+
+class DocumentationComment:
+    _ParseMode = enum("DESCRIPTION", "PARAM", "RETVAL")
+
+    def __init__(self, desc, param_dict, retval_desc):
+        """
+        Represents a documentation comment of a python class or function.
+
+        :param desc:        A description as string.
+        :param param_dict:  A dictionary containing parameter names as key and
+                            their description as value. To preserve the order,
+                            use OrderedDict.
+        :param retval_desc: A string describing the return value.
+        """
+        self.desc = desc
+        self.param_dict = param_dict
+        self.retval_desc = retval_desc
+
+    @classmethod
+    def from_docstring(cls, docstring):
+        """
+        Parses a python docstring. Usable attributes are:
+        :param
+        @param
+        :return
+        @return
+        """
+        lines = inspect.cleandoc(docstring).split("\n")
+
+        parse_mode = cls._ParseMode.DESCRIPTION
+        cur_param = ""
+
+        desc = ""
+        param_dict = OrderedDict()
+        retval_desc = ""
+        for line in lines:
+            line = line.strip()
+
+            if line.startswith(":param ") or line.startswith("@param "):
+                parse_mode = cls._ParseMode.PARAM
+                splitted = line[7:].split(":", 1)
+                cur_param = splitted[0]
+                param_dict[cur_param] = splitted[1].strip()
+
+                continue
+
+            if line.startswith(":return: ") or line.startswith("@return: "):
+                parse_mode = cls._ParseMode.RETVAL
+                retval_desc = line[9:].strip()
+
+                continue
+
+            def concat_doc_parts(old: str, new: str):
+                if new != '' and not old.endswith('\n'):
+                    return old + ' ' + new
+
+                return old + (new if new != '' else '\n')
+
+            if parse_mode == cls._ParseMode.RETVAL:
+                retval_desc = concat_doc_parts(retval_desc, line)
+            elif parse_mode == cls._ParseMode.PARAM:
+                param_dict[cur_param] = concat_doc_parts(param_dict[cur_param],
+                                                         line)
+            else:
+                desc = concat_doc_parts(desc, line)
+
+        return (cls(desc=desc.strip(),
+                    param_dict=param_dict,
+                    retval_desc=retval_desc.strip()))
+
+    def __str__(self):
+        return str(self.desc)
diff --git a/pool/shard001/Python/0013064_vote.py b/pool/shard001/Python/0013064_vote.py
new file mode 100644
index 0000000000000000000000000000000000000000..b064f64bdcb224673df0e348b19950395b072bc8
--- /dev/null
+++ b/pool/shard001/Python/0013064_vote.py
@@ -0,0 +1,135 @@
+# Copyright (c) 2014 by Ecreall under licence AGPL terms 
+# available on http://www.gnu.org/licenses/agpl.html
+
+# licence: AGPL
+# author: Amen Souissi
+
+import colander
+import deform
+from pyramid.view import view_config
+
+from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
+from dace.objectofcollaboration.entity import Entity
+from pontus.form import FormView
+from pontus.view_operation import MultipleView
+from pontus.view import BasicView
+from pontus.schema import Schema
+from pontus.widget import Select2Widget
+from pontus.default_behavior import Cancel
+
+from novaideo.content.processes.ballot_processes.fptp.behaviors import  Vote
+from novaideo.content.proposal import Proposal
+from novaideo import _
+
+
+class VoteViewStudyReport(BasicView):
+    title = _('FPTP vote')
+    name = 'votefptp'
+    template = 'novaideo:views/ballot_processes/fptp/templates/fptp_vote.pt'
+
+    def update(self):
+        result = {}
+        ballot_report = None
+        try:
+            voteform_view = self.parent.validated_children[1]
+            voteform_actions = list(voteform_view.behaviors_instances.values())
+            ballot_report = voteform_actions[0].process.ballot.report
+        except Exception:
+            pass
+
+        values = {'context': self.context, 'ballot_report': ballot_report}
+        body = self.content(args=values, template=self.template)['body']
+        item = self.adapt_item(body, self.viewid)
+        result['coordinates'] = {self.coordinates:[item]}
+        return result
+
+
+def subjects_choice(ballot_report):
+    subjects = ballot_report.subjects
+    group_values = getattr(ballot_report.ballottype, 'group_values', None)
+
+    def get_title(ob):
+        if isinstance(ob, Entity):
+            return ob.title
+        else:
+            return _(ob)
+
+    if group_values:
+        values = group_values
+    else:
+        values = [(i, get_title(i)) for i in subjects]
+
+    return Select2Widget(values=values)
+
+
+class CandidatesSchema(Schema):
+
+    elected = colander.SchemaNode(
+            colander.String(),
+            default="Ten minutes",
+            title=_('Choices'),
+        )
+
+
+class VoteFormView(FormView):
+    title = _('Vote')
+    name = 'voteform'
+    formid = 'formvote'
+    behaviors = [Vote]
+    validate_behaviors = False
+    schema = CandidatesSchema()
+
+    def before_update(self):
+        ballot_report = None
+        try:
+            vote_actions = list(self.behaviors_instances.values())
+            ballot_report = vote_actions[0].process.ballot.report
+        except Exception:
+            return
+
+        subjects_widget = subjects_choice(ballot_report)
+        elected_node = self.schema.get('elected')
+        elected_node.title = getattr(ballot_report.ballottype,
+                                     'group_title', _('Choices'))
+        group_default = getattr(ballot_report.ballottype, 'group_default', None)
+        if group_default:
+            elected_node.default = group_default
+
+        elected_node.widget = subjects_widget
+        self.schema.view = self
+        self.action = self.request.resource_url(
+            self.context, 'novaideoapi',
+            query={'op': 'update_action_view',
+                   'node_id': Vote.node_definition.id,
+                   'action_uid': getattr(vote_actions[0], '__oid__', '')})
+        self.schema.widget = deform.widget.FormWidget(
+            css_class='deform vote-form')
+
+
+@view_config(
+    name='votefptp',
+    context=Proposal,
+    renderer='pontus:templates/views_templates/grid.pt',
+    )
+class VoteViewMultipleView(MultipleView):
+    title = _('Vote')
+    name = 'votefptp'
+    viewid = 'votefptp'
+    template = 'pontus:templates/views_templates/simple_multipleview.pt'
+    wrapper_template = 'novaideo:views/ballot_processes/templates/panel_item.pt'
+    views = (VoteViewStudyReport, VoteFormView)
+    validators = [Vote.get_validator()]
+
+    def get_message(self):
+        ballot_report = None
+        try:
+            voteform_view = self.validated_children[1]
+            voteform_actions = list(voteform_view.behaviors_instances.values())
+            ballot_report = voteform_actions[0].process.ballot.report
+        except Exception:
+            pass
+
+        return ballot_report.ballot.title
+
+
+DEFAULTMAPPING_ACTIONS_VIEWS.update({Vote:VoteViewMultipleView})
diff --git a/pool/shard001/Python/0013067_extract_strings_qt.py b/pool/shard001/Python/0013067_extract_strings_qt.py
new file mode 100644
index 0000000000000000000000000000000000000000..b72a24c49dbbb70d9f0baba6e6a152b196ba1f7f
--- /dev/null
+++ b/pool/shard001/Python/0013067_extract_strings_qt.py
@@ -0,0 +1,78 @@
+#!/usr/bin/python
+'''
+Extract _("...") strings for translation and convert to Qt4 stringdefs so that
+they can be picked up by Qt linguist.
+'''
+from subprocess import Popen, PIPE
+import glob
+import operator
+import os
+import sys
+
+OUT_CPP="qt/pandapaystrings.cpp"
+EMPTY=['""']
+
+def parse_po(text):
+    """
+    Parse 'po' format produced by xgettext.
+    Return a list of (msgid,msgstr) tuples.
+    """
+    messages = []
+    msgid = []
+    msgstr = []
+    in_msgid = False
+    in_msgstr = False
+
+    for line in text.split('\n'):
+        line = line.rstrip('\r')
+        if line.startswith('msgid '):
+            if in_msgstr:
+                messages.append((msgid, msgstr))
+                in_msgstr = False
+            # message start
+            in_msgid = True
+
+            msgid = [line[6:]]
+        elif line.startswith('msgstr '):
+            in_msgid = False
+            in_msgstr = True
+            msgstr = [line[7:]]
+        elif line.startswith('"'):
+            if in_msgid:
+                msgid.append(line)
+            if in_msgstr:
+                msgstr.append(line)
+
+    if in_msgstr:
+        messages.append((msgid, msgstr))
+
+    return messages
+
+files = sys.argv[1:]
+
+# xgettext -n --keyword=_ $FILES
+XGETTEXT=os.getenv('XGETTEXT', 'xgettext')
+child = Popen([XGETTEXT,'--output=-','-n','--keyword=_'] + files, stdout=PIPE)
+(out, err) = child.communicate()
+
+messages = parse_po(out)
+
+f = open(OUT_CPP, 'w')
+f.write("""
+
+#include 
+
+// Automatically generated by extract_strings.py
+#ifdef __GNUC__
+#define UNUSED __attribute__((unused))
+#else
+#define UNUSED
+#endif
+""")
+f.write('static const char UNUSED *pandapay_strings[] = {\n')
+messages.sort(key=operator.itemgetter(0))
+for (msgid, msgstr) in messages:
+    if msgid != EMPTY:
+        f.write('QT_TRANSLATE_NOOP("pandapay-core", %s),\n' % ('\n'.join(msgid)))
+f.write('};\n')
+f.close()
diff --git a/pool/shard001/Python/0013070_generate_website.py b/pool/shard001/Python/0013070_generate_website.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ab905a17abe31fb32f0b9b770eb460fb9505f2c
--- /dev/null
+++ b/pool/shard001/Python/0013070_generate_website.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+
+import os
+
+import markdown2
+
+from solarized256 import Solarized256Style
+from pygments import highlight
+from pygments.lexers import PythonLexer
+from pygments.formatters import HtmlFormatter
+
+
+def rel(path):
+    scripts_dir = os.path.dirname(__file__)
+    return os.path.join(scripts_dir, path)
+
+
+def read(filename):
+    contents = ''
+    with open(filename, 'r') as f:
+        contents = f.read()
+    return contents
+
+
+def python_highlight(output, offset=0):
+    start_needle = '```python'
+    highlight_offset = output.find(start_needle, offset)
+    if highlight_offset == -1:
+        return (False, output)
+
+
+    end_needle = '```'
+    highlight_finish = output.find(end_needle,
+                                   highlight_offset + len(start_needle))
+
+    if highlight_finish == -1:
+        return (False, output)
+
+    formatter = HtmlFormatter(style=Solarized256Style)
+    code = output[highlight_offset + len(start_needle):highlight_finish]
+    code = highlight(code, PythonLexer(), formatter)
+
+    highlight_finish += len(end_needle)
+    highlighted = '{before}{code}{after}'.format(
+        before=output[:highlight_offset],
+        code=code,
+        after=output[highlight_finish:],
+    )
+    highlight_offset += len(start_needle)
+    return (highlight_finish, highlighted)
+
+
+def syntax_highlight(output):
+    highlight_offset = 0
+    while True:
+        highlight_offset, output = python_highlight(output,
+                                                    offset=highlight_offset)
+        if not highlight_offset:
+            break
+
+    return output
+
+
+def inject_markdown(template, md):
+    return template.replace('{{{MARKDOWN}}}', md)
+
+
+def main():
+    readme = read(rel('../README.md'))
+    readme = syntax_highlight(readme)
+    readme = markdown2.markdown(readme)
+
+    template = read(rel('data/website_template.html'))
+    output = inject_markdown(template, readme)
+    with open(rel('../website/index.html'), 'w') as f:
+        f.write(output)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/pool/shard001/Python/0013073_utils.py b/pool/shard001/Python/0013073_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..11c9c4e740407e1a9d57966659806c5ffc9e1396
--- /dev/null
+++ b/pool/shard001/Python/0013073_utils.py
@@ -0,0 +1,27 @@
+"""
+Utility functions for communication app
+"""
+
+# Django
+from django.core.validators import ValidationError
+
+# MuckRock
+from muckrock.communication.models import EmailAddress, PhoneNumber
+
+
+def get_email_or_fax(email_or_fax):
+    """Convert a string into either an email or phone number model"""
+
+    # fetch validates the email
+    email = EmailAddress.objects.fetch(email_or_fax)
+    if email is not None:
+        return email
+
+    # not a valid email, try fax
+    # fetch validates the phone number
+    fax = PhoneNumber.objects.fetch(email_or_fax)
+    if fax is not None:
+        return fax
+
+    # neither is valid, raise an error
+    raise ValidationError("Invalid email or fax")
diff --git a/pool/shard001/Python/0013074_zxjdbc.py b/pool/shard001/Python/0013074_zxjdbc.py
new file mode 100644
index 0000000000000000000000000000000000000000..94d8f821956f627e9dba2ced6f5ba4b354ca2765
--- /dev/null
+++ b/pool/shard001/Python/0013074_zxjdbc.py
@@ -0,0 +1,218 @@
+# oracle/zxjdbc.py
+# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors 
+#
+# This module is part of SQLAlchemy and is released under
+# the MIT License: http://www.opensource.org/licenses/mit-license.php
+
+"""
+.. dialect:: oracle+zxjdbc
+    :name: zxJDBC for Jython
+    :dbapi: zxjdbc
+    :connectstring: oracle+zxjdbc://user:pass@host/dbname
+    :driverurl: http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.
+
+"""
+import decimal
+import re
+
+from sqlalchemy import sql, types as sqltypes, util
+from sqlalchemy.connectors.zxJDBC import ZxJDBCConnector
+from sqlalchemy.dialects.oracle.base import OracleCompiler, OracleDialect, OracleExecutionContext
+from sqlalchemy.engine import result as _result
+from sqlalchemy.sql import expression
+import collections
+
+SQLException = zxJDBC = None
+
+
+class _ZxJDBCDate(sqltypes.Date):
+
+    def result_processor(self, dialect, coltype):
+        def process(value):
+            if value is None:
+                return None
+            else:
+                return value.date()
+        return process
+
+
+class _ZxJDBCNumeric(sqltypes.Numeric):
+
+    def result_processor(self, dialect, coltype):
+        #XXX: does the dialect return Decimal or not???
+        # if it does (in all cases), we could use a None processor as well as
+        # the to_float generic processor
+        if self.asdecimal:
+            def process(value):
+                if isinstance(value, decimal.Decimal):
+                    return value
+                else:
+                    return decimal.Decimal(str(value))
+        else:
+            def process(value):
+                if isinstance(value, decimal.Decimal):
+                    return float(value)
+                else:
+                    return value
+        return process
+
+
+class OracleCompiler_zxjdbc(OracleCompiler):
+
+    def returning_clause(self, stmt, returning_cols):
+        self.returning_cols = list(expression._select_iterables(returning_cols))
+
+        # within_columns_clause=False so that labels (foo AS bar) don't render
+        columns = [self.process(c, within_columns_clause=False, result_map=self.result_map)
+                   for c in self.returning_cols]
+
+        if not hasattr(self, 'returning_parameters'):
+            self.returning_parameters = []
+
+        binds = []
+        for i, col in enumerate(self.returning_cols):
+            dbtype = col.type.dialect_impl(self.dialect).get_dbapi_type(self.dialect.dbapi)
+            self.returning_parameters.append((i + 1, dbtype))
+
+            bindparam = sql.bindparam("ret_%d" % i, value=ReturningParam(dbtype))
+            self.binds[bindparam.key] = bindparam
+            binds.append(self.bindparam_string(self._truncate_bindparam(bindparam)))
+
+        return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds)
+
+
+class OracleExecutionContext_zxjdbc(OracleExecutionContext):
+
+    def pre_exec(self):
+        if hasattr(self.compiled, 'returning_parameters'):
+            # prepare a zxJDBC statement so we can grab its underlying
+            # OraclePreparedStatement's getReturnResultSet later
+            self.statement = self.cursor.prepare(self.statement)
+
+    def get_result_proxy(self):
+        if hasattr(self.compiled, 'returning_parameters'):
+            rrs = None
+            try:
+                try:
+                    rrs = self.statement.__statement__.getReturnResultSet()
+                    rrs.next()
+                except SQLException, sqle:
+                    msg = '%s [SQLCode: %d]' % (sqle.getMessage(), sqle.getErrorCode())
+                    if sqle.getSQLState() is not None:
+                        msg += ' [SQLState: %s]' % sqle.getSQLState()
+                    raise zxJDBC.Error(msg)
+                else:
+                    row = tuple(self.cursor.datahandler.getPyObject(rrs, index, dbtype)
+                                for index, dbtype in self.compiled.returning_parameters)
+                    return ReturningResultProxy(self, row)
+            finally:
+                if rrs is not None:
+                    try:
+                        rrs.close()
+                    except SQLException:
+                        pass
+                self.statement.close()
+
+        return _result.ResultProxy(self)
+
+    def create_cursor(self):
+        cursor = self._dbapi_connection.cursor()
+        cursor.datahandler = self.dialect.DataHandler(cursor.datahandler)
+        return cursor
+
+
+class ReturningResultProxy(_result.FullyBufferedResultProxy):
+
+    """ResultProxy backed by the RETURNING ResultSet results."""
+
+    def __init__(self, context, returning_row):
+        self._returning_row = returning_row
+        super(ReturningResultProxy, self).__init__(context)
+
+    def _cursor_description(self):
+        ret = []
+        for c in self.context.compiled.returning_cols:
+            if hasattr(c, 'name'):
+                ret.append((c.name, c.type))
+            else:
+                ret.append((c.anon_label, c.type))
+        return ret
+
+    def _buffer_rows(self):
+        return collections.deque([self._returning_row])
+
+
+class ReturningParam(object):
+
+    """A bindparam value representing a RETURNING parameter.
+
+    Specially handled by OracleReturningDataHandler.
+    """
+
+    def __init__(self, type):
+        self.type = type
+
+    def __eq__(self, other):
+        if isinstance(other, ReturningParam):
+            return self.type == other.type
+        return NotImplemented
+
+    def __ne__(self, other):
+        if isinstance(other, ReturningParam):
+            return self.type != other.type
+        return NotImplemented
+
+    def __repr__(self):
+        kls = self.__class__
+        return '<%s.%s object at 0x%x type=%s>' % (kls.__module__, kls.__name__, id(self),
+                                                   self.type)
+
+
+class OracleDialect_zxjdbc(ZxJDBCConnector, OracleDialect):
+    jdbc_db_name = 'oracle'
+    jdbc_driver_name = 'oracle.jdbc.OracleDriver'
+
+    statement_compiler = OracleCompiler_zxjdbc
+    execution_ctx_cls = OracleExecutionContext_zxjdbc
+
+    colspecs = util.update_copy(
+        OracleDialect.colspecs,
+        {
+            sqltypes.Date: _ZxJDBCDate,
+            sqltypes.Numeric: _ZxJDBCNumeric
+        }
+    )
+
+    def __init__(self, *args, **kwargs):
+        super(OracleDialect_zxjdbc, self).__init__(*args, **kwargs)
+        global SQLException, zxJDBC
+        from java.sql import SQLException
+        from com.ziclix.python.sql import zxJDBC
+        from com.ziclix.python.sql.handler import OracleDataHandler
+
+        class OracleReturningDataHandler(OracleDataHandler):
+            """zxJDBC DataHandler that specially handles ReturningParam."""
+
+            def setJDBCObject(self, statement, index, object, dbtype=None):
+                if type(object) is ReturningParam:
+                    statement.registerReturnParameter(index, object.type)
+                elif dbtype is None:
+                    OracleDataHandler.setJDBCObject(
+                        self, statement, index, object)
+                else:
+                    OracleDataHandler.setJDBCObject(
+                        self, statement, index, object, dbtype)
+        self.DataHandler = OracleReturningDataHandler
+
+    def initialize(self, connection):
+        super(OracleDialect_zxjdbc, self).initialize(connection)
+        self.implicit_returning = connection.connection.driverversion >= '10.2'
+
+    def _create_jdbc_url(self, url):
+        return 'jdbc:oracle:thin:@%s:%s:%s' % (url.host, url.port or 1521, url.database)
+
+    def _get_server_version_info(self, connection):
+        version = re.search(r'Release ([\d\.]+)', connection.connection.dbversion).group(1)
+        return tuple(int(x) for x in version.split('.'))
+
+dialect = OracleDialect_zxjdbc
diff --git a/pool/shard001/Python/0013075_utils.py b/pool/shard001/Python/0013075_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fd56c32025c07420fd446ba4252454f6de1de61
--- /dev/null
+++ b/pool/shard001/Python/0013075_utils.py
@@ -0,0 +1,230 @@
+from __future__ import print_function
+
+import locale
+import os
+import platform
+import re
+import sys
+
+import six
+import yaml
+try:
+    from yaml import CDumper as Dumper
+except ImportError:
+    from yaml import Dumper
+
+try:  # ugly hack for using imp instead of importlib on Python <= 2.6
+    import importlib
+    import importlib.machinery
+except ImportError:
+    import devassistant
+    import imp as importlib
+    importlib.machinery = None
+
+    def import_module(name):
+        # attempt to fix #326 - load modules dot by dot
+        path = sys.path
+        for part in name.split('.'):
+            fp, pathname, description = importlib.find_module(part, path)
+            module = importlib.load_module(name, fp, pathname, description)
+            path = module.__path__
+        return module
+    importlib.import_module = import_module
+    del import_module
+
+from devassistant import settings
+
+
+def import_module(module):
+    return importlib.import_module(module)
+
+
+def import_by_path(modname, path):
+    if importlib.machinery:  # Python >= 3.3
+        loader = importlib.machinery.SourceFileLoader(modname, path)
+        return loader.load_module()
+    else:  # Python 2.6, 2.7
+        return importlib.load_source(modname, path)
+
+
+def get_system_name():
+    return platform.system().lower()
+
+
+def get_system_version():
+    return platform.release().lower()
+
+
+def get_distro_name():
+    system = get_system_name()
+    if system == 'linux':
+        return platform.linux_distribution(full_distribution_name=False)[0].lower() \
+            or _get_os_release_content('ID')
+    elif system == 'darwin':
+        return 'darwin'
+    else:
+        return ''
+
+
+def get_distro_version():
+    return platform.linux_distribution()[1].lower() or _get_os_release_content('VERSION_ID')
+
+
+def _get_os_release_content(line_start):
+    os_release = '/etc/os-release'
+    if not os.path.exists(os_release):
+        return ''
+
+    with open(os_release) as osrel:
+        for l in osrel.readlines():
+            if l.startswith(line_start):
+                found = l.split('=')[-1].strip()
+    return found.lower()
+
+
+def get_cwd_or_homedir():
+    try:
+        return os.getcwd()
+    except:
+        return os.path.expanduser('~')
+
+
+def cl_string_for_da_eval(section, context=None):
+    if context is None:
+        context = {}
+    # filter variables that we don't want to pass from context
+    unwanted = ['__assistant__', '__section__']
+    ctxt_to_dump = dict(filter(lambda i: i[0] not in unwanted, context.items()))
+
+    dumped = yaml.dump({'ctxt': ctxt_to_dump, 'run': section}, stream=None, Dumper=Dumper)
+    dumped_in_heredoc = '\n'.join(['\VERY_LONG_RANDOM_EOF', dumped, 'VERY_LONG_RANDOM_EOF'])
+
+    cl_string = ' '.join([sys.executable,
+                          '-m devassistant.cli.cli_runner',
+                          'eval - <<',
+                          dumped_in_heredoc])
+    return cl_string
+
+
+def find_file_in_load_dirs(relpath):
+    """If given relative path exists in one of DevAssistant load paths,
+    return its full path.
+
+    Args:
+        relpath: a relative path, e.g. "assitants/crt/test.yaml"
+
+    Returns:
+        absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml
+        or None if file is not found
+    """
+    if relpath.startswith(os.path.sep):
+        relpath = relpath.lstrip(os.path.sep)
+
+    for ld in settings.DATA_DIRECTORIES:
+        possible_path = os.path.join(ld, relpath)
+        if os.path.exists(possible_path):
+            return possible_path
+
+
+def add_no_cache_argument(parser):
+    # This really only stores the True/False value. We need to set
+    # settings.USE_CACHE before we create the parser, but for creating
+    # the parser, we need to load assistants. That means we set
+    # settings.USE_CACHE in cli_runner and gui/__init__ according to sys.argv.
+    parser.add_argument('--no-cache',
+                        help='Don\'t use assistants cache (useful for debugging).',
+                        action='store_true',
+                        dest='da_no_cache',
+                        default=False)
+
+
+_exithandlers = []
+
+
+def atexit(func, *targs, **kargs):
+    _exithandlers.append((func, targs, kargs))
+    return func
+
+
+def run_exitfuncs():
+    """Function that behaves exactly like Python's atexit, but runs atexit functions
+    in the order in which they were registered, not reversed.
+    """
+    exc_info = None
+    for func, targs, kargs in _exithandlers:
+        try:
+            func(*targs, **kargs)
+        except SystemExit:
+            exc_info = sys.exc_info()
+        except:
+            exc_info = sys.exc_info()
+
+    if exc_info is not None:
+        six.reraise(exc_info[0], exc_info[1], exc_info[2])
+
+
+defenc = locale.getpreferredencoding()
+defenc = 'utf-8' if defenc.lower() in ['ascii', 'us-ascii'] else defenc
+
+
+def exc_as_decoded_string(e):
+    """Generate decoded string from an exception
+    For now on, this just calls six.text_type(e) (meaning str(e) or unicode(e))
+
+    In the future, this should be more sophisticated and return
+    a string with both name of the exception and the message.
+    """
+    return six.text_type(e)
+
+
+def bold(message):
+    """Adds shell bold formatting to the message"""
+    return '\033[1m{m}\033[0m'.format(m=message)
+
+
+def unexpanduser(path):
+    """Replaces expanded ~ back with ~"""
+    return path.replace(os.path.expanduser('~'), '~')
+
+
+def strip_prefix(string, prefix, regex=False):
+    """Strip the prefix from the string
+
+    If 'regex' is specified, prefix is understood as a regular expression."""
+    if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types):
+        msg = 'Arguments to strip_prefix must be string types. Are: {s}, {p}'\
+              .format(s=type(string), p=type(prefix))
+        raise TypeError(msg)
+
+    if not regex:
+        prefix = re.escape(prefix)
+    if not prefix.startswith('^'):
+        prefix = '^({s})'.format(s=prefix)
+    return _strip(string, prefix)
+
+
+def strip_suffix(string, suffix, regex=False):
+    """Strip the suffix from the string.
+
+    If 'regex' is specified, suffix is understood as a regular expression."""
+    if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types):
+        msg = 'Arguments to strip_suffix must be string types. Are: {s}, {p}'\
+              .format(s=type(string), p=type(suffix))
+        raise TypeError(msg)
+
+    if not regex:
+        suffix = re.escape(suffix)
+    if not suffix.endswith('$'):
+        suffix = '({s})$'.format(s=suffix)
+    return _strip(string, suffix)
+
+
+def _strip(string, pattern):
+    """Return complement of pattern in string"""
+    m = re.compile(pattern).search(string)
+
+    if m:
+        return string[0:m.start()] + string[m.end():len(string)]
+    else:
+        return string
+
diff --git a/pool/shard001/Python/0013076_0009_delete_enable_scopes_waffle_switch.py b/pool/shard001/Python/0013076_0009_delete_enable_scopes_waffle_switch.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd4cef97b166b4e1d81f25f82c197ce5c9fe277b
--- /dev/null
+++ b/pool/shard001/Python/0013076_0009_delete_enable_scopes_waffle_switch.py
@@ -0,0 +1,37 @@
+# Generated by Django 1.11.28 on 2020-03-04 15:19
+
+"""
+Deletes the ENFORCE_JWT_SCOPES waffle switch that has already been deprecated and removed.
+
+See https://github.com/edx/edx-platform/pull/23188 for the removal
+"""
+
+from django.db import migrations
+
+ENFORCE_JWT_SCOPES = 'oauth2.enforce_jwt_scopes'
+
+
+def delete_switch(apps, schema_editor):
+    """ Delete the switch. """
+    Switch = apps.get_model('waffle', 'Switch')
+    try:
+        Switch.objects.filter(name=ENFORCE_JWT_SCOPES).delete()
+    except Switch.DoesNotExist:
+        pass
+
+
+def create_switch(apps, schema_editor):
+    """ Create the switch if it does not already exist. """
+    Switch = apps.get_model('waffle', 'Switch')
+    Switch.objects.update_or_create(name=ENFORCE_JWT_SCOPES, defaults={'active': True})
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('oauth_dispatch', '0008_applicationaccess_filters'),
+    ]
+
+    operations = [
+        migrations.RunPython(delete_switch, reverse_code=create_switch),
+    ]
diff --git a/pool/shard001/Python/0013077_PacbioMapping.py b/pool/shard001/Python/0013077_PacbioMapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b9aa79259a24935df984a4ea4fec6547a12f6af
--- /dev/null
+++ b/pool/shard001/Python/0013077_PacbioMapping.py
@@ -0,0 +1,44 @@
+#Re-written by Dan Browne on 04/05/16
+
+from AbstractAlignment import AbstractAlignment
+from datetime import datetime
+import matplotlib
+import matplotlib.pyplot as plt
+
+class PacbioMapping:
+
+    def __init__(self, fileName, fileFormat="m4"):
+        print "Entering PacbioMapping module:", str(datetime.now())
+        #Read and parse alignments into dictionary of reads (keys) and  alignment objects (values)
+        self.readToContig = {}
+        self.alignments = open(fileName, "rU").read().split('\n')
+        self.alignments = self.alignments[1:-1] if "score" in self.alignments[0] else self.alignments[0:-1]
+        self.alignments = set([AbstractAlignment(x.split(' '), fileFormat) for x in self.alignments])
+        self.readToContig = {x.qName: set([]) for x in self.alignments if x.qName not in self.readToContig}
+        for x in self.alignments:
+            self.readToContig[x.qName].add(x)
+        print "Number of unfiltered reads:", len(self.readToContig)
+        print "Number of unfiltered alignments:", len(self.alignments)
+        #Filter out reads with only 1 alignment
+        print "Filtering out reads with only 1 alignment"
+        self.filter_reads()
+        print "Number of filtered reads:", len(self.readToContig)
+        print "Number of filtered alignments:", len(self.alignments)
+        print "Leaving PacbioMapping module:", str(datetime.now())
+
+    def filter_reads(self):
+        filtered_reads = set([])
+        for k,v in self.readToContig.items():
+            if len(v) == 1:
+                filtered_reads.add(k)
+                del self.readToContig[k]
+        self.alignments = set([x for x in self.alignments if x.qName not in filtered_reads])
+
+    def read_mapping_frequency(self, title, bins=50):
+        x_axis = [len(x) for x in self.readToContig.values()]
+        plt.hist(x_axis, bins)
+        plt.xlabel("Alignments per read")
+        plt.ylabel("Number of reads")
+        plt.savefig(title+".png")
+        plt.clf()
+
diff --git a/pool/shard001/Python/0013079_deploy.py b/pool/shard001/Python/0013079_deploy.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b641d375a9a6ca2ea40828042c94d10e4aba8d
--- /dev/null
+++ b/pool/shard001/Python/0013079_deploy.py
@@ -0,0 +1,86 @@
+# Copyright (C) 2013 eNovance SAS 
+#
+# 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 argparse
+import glob
+from subprocess import Popen, PIPE
+import sys
+import os
+
+
+class HostAgent(object):
+
+    def __init__(self):
+        self.callback_url = None
+        self.host_id = None
+
+    def execCmd(self, command):
+        p = Popen(command, stdin=PIPE, stdout=PIPE,
+                  stderr=PIPE, close_fds=True)
+        (stdout, stderr) = p.communicate()
+        rc = p.returncode
+        return (rc, stdout, stderr)
+
+    def callback(self, file=None, error=None):
+        pass
+
+    def copy_locally(self, file_path, local_store):
+        pass
+
+    def find_file(self, filename, task=None):
+        if task:
+            filename = '/tmp/sosreport*%s' % task
+        path = glob.glob('%s*' % filename)
+        return path
+
+    def daemonize(self):
+        try:
+            pid = os.fork()
+            if pid > 0:
+                # Exit parent process
+                sys.exit(0)
+        except OSError, e:
+            err = "Failed to fork: %d (%s)" % (e.errno, e.strerror)
+            self.callback(error=err)
+            sys.exit(1)
+
+    def main(self, args=None, filename=None):
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--command',
+            help='Command to start the log collectoin process.')
+        parser.add_argument('--callback_url',
+            help='URL of the controller to communicate comletion.')
+        parser.add_argument('--filename',
+            help='Filename for the logs archive.')
+        parser.add_argument('--host_id',
+            help='ID of the host.')
+        (options, args) = parser.parse_known_args(sys.argv[1:])
+        self.callback_url = args.callback_url
+        self.host_id = args.host_id
+
+        if args.callback_url:
+            self.daemonize()
+
+            rc, out, err = self.execCmd(args.command.split())
+            if rc != 0:
+                self.callback(error=err)
+            else:
+                filePath = self.find_file(args.filename)
+                self.callback(file=filePath)
+        else:
+            cmd_args = args if args else args.command.split()
+            return self.execCmd(cmd_args)
+
+if __name__ == "__main__":
+    HostAgent().main()
diff --git a/pool/shard001/Python/0013082_models.py b/pool/shard001/Python/0013082_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..720207a0d451db8d5805b93897e4ab6139f4520e
--- /dev/null
+++ b/pool/shard001/Python/0013082_models.py
@@ -0,0 +1,92 @@
+"""
+Models for configuration of the feature flags
+controlling persistent grades.
+"""
+from config_models.models import ConfigurationModel
+from django.conf import settings
+from django.db.models import BooleanField, IntegerField, TextField
+from opaque_keys.edx.django.models import CourseKeyField
+from six import text_type
+
+from openedx.core.lib.cache_utils import request_cached
+
+
+class PersistentGradesEnabledFlag(ConfigurationModel):
+    """
+    Enables persistent grades across the platform.
+    When this feature flag is set to true, individual courses
+    must also have persistent grades enabled for the
+    feature to take effect.
+
+    .. no_pii:
+    """
+    # this field overrides course-specific settings to enable the feature for all courses
+    enabled_for_all_courses = BooleanField(default=False)
+
+    @classmethod
+    @request_cached()
+    def feature_enabled(cls, course_id=None):
+        """
+        Looks at the currently active configuration model to determine whether
+        the persistent grades feature is available.
+
+        If the flag is not enabled, the feature is not available.
+        If the flag is enabled and the provided course_id is for an course
+            with persistent grades enabled, the feature is available.
+        If the flag is enabled and no course ID is given,
+            we return True since the global setting is enabled.
+        """
+        if settings.FEATURES.get('PERSISTENT_GRADES_ENABLED_FOR_ALL_TESTS'):
+            return True
+        if not PersistentGradesEnabledFlag.is_enabled():
+            return False
+        elif not PersistentGradesEnabledFlag.current().enabled_for_all_courses and course_id:
+            effective = CoursePersistentGradesFlag.objects.filter(course_id=course_id).order_by('-change_date').first()
+            return effective.enabled if effective is not None else False
+        return True
+
+    class Meta(object):
+        app_label = "grades"
+
+    def __unicode__(self):
+        current_model = PersistentGradesEnabledFlag.current()
+        return u"PersistentGradesEnabledFlag: enabled {}".format(
+            current_model.is_enabled()
+        )
+
+
+class CoursePersistentGradesFlag(ConfigurationModel):
+    """
+    Enables persistent grades for a specific
+    course. Only has an effect if the general
+    flag above is set to True.
+
+    .. no_pii:
+    """
+    KEY_FIELDS = ('course_id',)
+
+    class Meta(object):
+        app_label = "grades"
+
+    # The course that these features are attached to.
+    course_id = CourseKeyField(max_length=255, db_index=True)
+
+    def __unicode__(self):
+        not_en = "Not "
+        if self.enabled:
+            not_en = ""
+        return u"Course '{}': Persistent Grades {}Enabled".format(text_type(self.course_id), not_en)
+
+
+class ComputeGradesSetting(ConfigurationModel):
+    """
+    .. no_pii:
+    """
+    class Meta(object):
+        app_label = "grades"
+
+    batch_size = IntegerField(default=100)
+    course_ids = TextField(
+        blank=False,
+        help_text="Whitespace-separated list of course keys for which to compute grades."
+    )
diff --git a/pool/shard001/Python/0013083_UpdateThread_Test.py b/pool/shard001/Python/0013083_UpdateThread_Test.py
new file mode 100644
index 0000000000000000000000000000000000000000..e478b4daef488937878c10477dd4ec7e36313aa6
--- /dev/null
+++ b/pool/shard001/Python/0013083_UpdateThread_Test.py
@@ -0,0 +1,61 @@
+''' 
+@date Apr 17, 2010
+@author: Matthew A. Todd
+
+This file is part of Test Parser
+by Matthew A. Todd
+
+Test Parser is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Test Parser is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Test Parser.  If not, see .
+'''
+import unittest
+
+from TestParser.Common.UpdateJobPool import UpdateJobPool
+from TestParser.Common.Constants import CONSTANTS
+
+import io
+
+class UpdateThread_Test(unittest.TestCase):
+    '''
+    Since UpdateThread is something of a private/helper class, which
+    isn't to be used by the outside world, we're going to test most
+    of its functionality through UpdateThreadPool
+    '''
+
+    def setUp(self):
+        '''
+        Setup errStream last so that no garbage gets in during
+        other initialization procedures.
+        '''
+        self.jobPool = UpdateJobPool()
+        self.jobPool.createPool(1)
+        
+        CONSTANTS.errStream = io.StringIO()        
+
+
+    def tearDown(self):
+        CONSTANTS.resetErrStream()
+        del self.jobPool
+    
+    
+    def test_runNone(self):
+        '''
+        Test that nothing explodes when we have a None job.
+        '''
+        self.jobPool.addJob(None)
+        self.jobPool.waitUntilJobsFinished_Raise()
+
+
+if __name__ == "__main__":
+    #import sys;sys.argv = ['', 'Test.testName']
+    unittest.main()
diff --git a/pool/shard001/Python/0013086_toolbar.py b/pool/shard001/Python/0013086_toolbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..823f1c7c273e3e15cdf38b848bdfe618ca27456c
--- /dev/null
+++ b/pool/shard001/Python/0013086_toolbar.py
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+# This file is part of Shuup.
+#
+# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
+#
+# This source code is licensed under the AGPLv3 license found in the
+# LICENSE file in the root directory of this source tree.
+from __future__ import unicode_literals
+
+from django.utils.translation import ugettext_lazy as _
+
+from shuup.admin.toolbar import DropdownItem, URLActionButton
+
+
+class MockContactToolbarButton(URLActionButton):
+    def __init__(self, contact, **kwargs):
+
+        kwargs["icon"] = "fa fa-user"
+        kwargs["text"] = _("Hello") + contact.full_name
+        kwargs["extra_css_class"] = "btn-info"
+        kwargs["url"] = "/#mocktoolbarbutton"
+
+        self.contact = contact
+
+        super(MockContactToolbarButton, self).__init__(**kwargs)
+
+
+class MockContactToolbarActionItem(DropdownItem):
+    def __init__(self, object, **kwargs):
+        kwargs["icon"] = "fa fa-hand-peace-o"
+        kwargs["text"] = _("Hello %(name)s") % {"name": object.full_name}
+        kwargs["url"] = "/#mocktoolbaractionitem"
+        super(MockContactToolbarActionItem, self).__init__(**kwargs)
+
+    @staticmethod
+    def visible_for_object(object):
+        return True
+
+
+class MockProductToolbarActionItem(DropdownItem):
+    def __init__(self, object, **kwargs):
+        kwargs["icon"] = "fa fa-female"
+        kwargs["text"] = _("This is %(sku)s") % {"sku": object.sku}
+        kwargs["url"] = "#%(sku)s" % {"sku": object.sku}
+        super(MockProductToolbarActionItem, self).__init__(**kwargs)
diff --git a/pool/shard001/Python/0013089_DNSspoof.py b/pool/shard001/Python/0013089_DNSspoof.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ba8dfbf2fb92ba15ebb6a8fb1cb60e21db43a90
--- /dev/null
+++ b/pool/shard001/Python/0013089_DNSspoof.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+
+# Copyright (C) 2015-2016 xtr4nge [_AT_] gmail.com
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see .
+#
+
+import os
+
+try:
+    from mitmproxy import controller, proxy # mitmproxy 0.17
+    from mitmproxy.proxy.server import ProxyServer # mitmproxy 0.17
+    from mitmproxy.models import decoded # mitmproxy 0.17
+except:
+    from libmproxy import controller, proxy # mitmproxy 0.15
+    from libmproxy.proxy.server import ProxyServer # mitmproxy 0.15
+    from libmproxy.models import decoded # mitmproxy 0.15
+
+import logging
+from configobj import ConfigObj
+from plugins.plugin import Plugin
+
+logger = logging.getLogger("fruityproxy")
+
+class DNSspoof(Plugin):
+    name = "DNSspoof"
+    version = "1.1"
+    
+    def request(self, flow):
+        
+        request_pretty_host = flow.request.pretty_host
+        request_host = flow.request.host
+        
+        for item, v in self.config[self.name]['domains'].iteritems():
+            domainRedirect = v.split("|")
+            wild_card = ""
+            
+            if len(domainRedirect[0]) > 1:
+                wild_card = domainRedirect[0].split(".")[0]
+                wild_domain = domainRedirect[0].replace("*.","").replace("*","")
+            
+            if domainRedirect[0] == "*":
+                flow.request.host = domainRedirect[1]
+                logger.debug("["+self.name+"] " + request_pretty_host + " to " + domainRedirect[1])
+                break
+                '''
+                elif flow.request.pretty_host.endswith(wild_domain) and wild_card == "*":
+                    flow.request.host = domainRedirect[1]
+                    logger.debug("["+self.name+"] " + request_pretty_host + " to " + domainRedirect[1])
+                    break
+                '''
+            
+            elif flow.request.pretty_host.endswith(domainRedirect[0]):
+                #elif flow.request.pretty_host(hostheader=True).endswith(domainRedirect[0]): # mitmproxy 0.15 [remove]
+                flow.request.host = domainRedirect[1]
+                #print flow.request.path
+                logger.debug("["+self.name+"] " + request_pretty_host + " to " + domainRedirect[1])
+                #flow.request.update_host_header() # mitmproxy 0.15 [remove]
+                break
+    
+    def response(self, flow):
+        pass
+    
\ No newline at end of file
diff --git a/pool/shard001/Python/0013091_agent.py b/pool/shard001/Python/0013091_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb5a74da3f7d0a04a027dfbd120686fc7a25c244
--- /dev/null
+++ b/pool/shard001/Python/0013091_agent.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2013 PolyBeacon, Inc.
+
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from payloadclient.common import base
+from payloadclient.common import exception
+
+CREATE_ATTRIBUTES = [
+    'uuid',
+]
+
+
+class Agent(base.Resource):
+    def __repr__(self):
+        return '' % self._info
+
+
+class AgentManager(base.Manager):
+
+    resource_class = Agent
+
+    def __create(self, attributes, path, **kwargs):
+        keys = {}
+        for (key, value) in kwargs.items():
+            if key in attributes:
+                keys[key] = value
+            else:
+                raise exception.InvalidAttribute()
+
+        return self._create(path, keys)
+
+    @staticmethod
+    def _path(uuid=None):
+        return '/v1/agents/%s' % uuid if uuid else '/v1/agents'
+
+    def create(self, **kwargs):
+        path = self._path()
+
+        return self.__create(
+            attributes=CREATE_ATTRIBUTES, path=path, **kwargs)
+
+    def delete(self, uuid):
+        return self._delete(self._path(uuid=uuid))
+
+    def get(self, uuid):
+        try:
+            return self._list(self._path(uuid=uuid))[0]
+        except IndexError:
+            return None
+
+    def list(self):
+        return self._list(self._path())
diff --git a/pool/shard001/Python/0013096_transformer.py b/pool/shard001/Python/0013096_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..44471e04dccfa348263d26bf3a8328cfe3ad5e40
--- /dev/null
+++ b/pool/shard001/Python/0013096_transformer.py
@@ -0,0 +1,188 @@
+from typing import Any
+
+from flax import linen as nn
+import jax
+import jax.numpy as jnp
+
+from core.modules.ipagnn import encoder
+from core.modules.ipagnn import spans
+from third_party.flax_examples import transformer_modules
+
+
+class Transformer(nn.Module):
+
+  config: Any
+  info: Any
+  transformer_config: transformer_modules.TransformerConfig
+
+  def setup(self):
+    config = self.config
+    vocab_size = self.info.vocab_size
+    max_tokens = config.max_tokens
+    max_num_nodes = config.max_num_nodes
+    max_num_edges = config.max_num_edges
+    self.token_embedder = spans.NodeAwareTokenEmbedder(
+        transformer_config=self.transformer_config,
+        num_embeddings=vocab_size,
+        features=config.hidden_size,
+        max_tokens=max_tokens,
+        max_num_nodes=max_num_nodes,
+    )
+    self.encoder = encoder.TransformerEncoder(
+        self.transformer_config)
+
+  @nn.compact
+  def __call__(self, x):
+    tokens = x['tokens']
+    # tokens.shape: batch_size, max_tokens
+    tokens_mask = tokens > 0
+    # tokens_mask.shape: batch_size, max_tokens
+    encoder_mask = nn.make_attention_mask(tokens_mask, tokens_mask, dtype=jnp.float32)
+    # encoder_mask.shape: batch_size, 1, max_tokens, max_tokens
+    encoded_inputs = self.token_embedder(
+        tokens, x['node_token_span_starts'], x['node_token_span_ends'],
+        x['num_nodes'])
+    # encoded_inputs.shape: batch_size, max_tokens, hidden_size
+    encoding = self.encoder(encoded_inputs, encoder_mask=encoder_mask)
+    # encoding.shape: batch_size, max_tokens, hidden_size
+
+    # Mean pooling.
+    tokens_mask_ext = tokens_mask[:, :, None]
+    x = (
+        jnp.sum(encoding * tokens_mask_ext, axis=1)
+        / jnp.maximum(1, jnp.sum(tokens_mask_ext, axis=1))
+    )
+    # x.shape: batch_size, hidden_size
+    x = nn.Dense(features=self.info.num_classes)(x)
+    # x.shape: batch_size, num_classes
+    return x, None
+
+
+class MILTransformer(nn.Module):
+  """Multiple instance learning Transformer.
+
+  NodeSpanEncoder can give contextual or non-contextual span embeddings.
+  Then from each span embedding, we predict P(class|span,input).
+  We then aggregate these into P(class|input) predictions.
+  And we return overall predictions, as well as localization_logits.
+  """
+
+  config: Any
+  info: Any
+  transformer_config: transformer_modules.TransformerConfig
+
+  def setup(self):
+    config = self.config
+    max_tokens = config.max_tokens
+    max_num_nodes = config.max_num_nodes
+    self.node_span_encoder = spans.NodeSpanEncoder(
+        info=self.info,
+        config=config,
+        transformer_config=self.transformer_config,
+        max_tokens=max_tokens,
+        max_num_nodes=max_num_nodes,
+        use_span_index_encoder=False,
+        use_span_start_indicators=False,
+    )
+
+  @nn.compact
+  def __call__(self, x):
+    config = self.config
+    info = self.info
+    tokens = x['tokens']
+    # tokens.shape: batch_size, max_tokens
+    batch_size = tokens.shape[0]
+    encoded_inputs = self.node_span_encoder(
+        tokens, x['node_token_span_starts'], x['node_token_span_ends'],
+        x['num_nodes'])
+    # encoded_inputs.shape: batch_size, max_num_nodes, hidden_size
+    max_num_nodes = encoded_inputs.shape[1]
+
+    num_classes = info.num_classes
+    per_line_logits = nn.Dense(
+        features=num_classes, name='per_line_output'
+    )(encoded_inputs)
+    # per_line_logits.shape: batch_size, max_num_nodes, num_classes
+
+    aux = {}
+    if config.mil_pool == 'logsumexp':
+      # logits = phi(c) = logsumexp_{l} phi(l, c)
+      logits = jax.scipy.special.logsumexp(per_line_logits, axis=1)
+      # logits.shape: batch_size, num_classes
+      # probs = p(c) \propto exp(phi(c))
+
+      # phi(l) = logsumexp_{c \in errors} phi(l, c)
+      if len(info.no_error_ids) == 1:
+        no_error_id = info.no_error_ids[0]
+        per_line_error_logits = per_line_logits.at[:, :, no_error_id].set(-jnp.inf)
+        # per_line_error_logits.shape: batch_size, max_num_nodes, num_classes
+        aux['localization_logits'] = jax.scipy.special.logsumexp(
+            per_line_error_logits, axis=2)
+        # aux['localization_logits'].shape: batch_size, max_num_nodes
+      elif len(info.no_error_ids) > 1:
+        if len(info.error_ids) > 1:
+          raise NotImplementedError('Multiple error classes and multiple no-error classes.')
+        assert len(info.error_ids) == 1
+        error_id = info.error_ids[0]
+        per_line_error_logits = per_line_logits.at[:, :, error_id]
+        # per_line_error_logits.shape: batch_size, max_num_nodes
+        aux['localization_logits'] = per_line_error_logits
+        # aux['localization_logits'].shape: batch_size, max_num_nodes
+      else:
+        raise ValueError('Tried using MILTransformer on data with no errors.')
+    else:
+      per_line_probs = jax.nn.softmax(per_line_logits, axis=-1)
+      # per_line_probs.shape: batch_size, max_num_nodes, num_classes
+
+      # Compute localization_logits:
+      if len(info.no_error_ids) == 1:
+        no_error_id = info.no_error_ids[0]
+        per_line_no_error_probs = per_line_probs[:, :, no_error_id]
+        # per_line_no_error_probs.shape: batch_size, max_num_nodes
+        per_line_error_probs = 1 - per_line_no_error_probs
+        # per_line_error_probs.shape: batch_size, max_num_nodes
+        # Normalization assumes uniform prior over lines.
+        normalized_error_probs = per_line_error_probs / jnp.sum(per_line_error_probs, axis=-1, keepdims=True)
+        # normalized_error_probs.shape: batch_size, max_num_nodes
+        aux['localization_logits'] = jnp.log(normalized_error_probs)
+        # aux['localization_logits'].shape: batch_size, max_num_nodes
+        assert aux['localization_logits'].shape == (batch_size, max_num_nodes)
+      elif len(info.no_error_ids) > 1:
+        if len(info.error_ids) > 1:
+          raise NotImplementedError('Multiple error classes and multiple no-error classes.')
+        assert len(info.error_ids) == 1
+        error_id = info.error_ids[0]
+        per_line_error_probs = per_line_probs[:, :, error_id]
+        # per_line_error_probs.shape: batch_size, max_num_nodes
+        # Normalization assumes uniform prior over lines.
+        normalized_error_probs = per_line_error_probs / jnp.sum(per_line_error_probs, axis=-1, keepdims=True)
+        # normalized_error_probs.shape: batch_size, max_num_nodes
+        aux['localization_logits'] = jnp.log(normalized_error_probs)
+        # aux['localization_logits'].shape: batch_size, max_num_nodes
+        assert aux['localization_logits'].shape == (batch_size, max_num_nodes)
+      else:
+        raise ValueError('Tried using MILTransformer on data with no errors.')
+
+      # Compute overall logits using pooling:
+      if config.mil_pool == 'max':
+        max_probs = jnp.max(per_line_probs, axis=1)
+        # max_probs.shape: batch_size, num_classes
+        logits = jnp.log(max_probs)
+        # logits.shape: batch_size, num_classes
+      elif config.mil_pool == 'mean':
+        mean_probs = jnp.mean(per_line_probs, axis=1)
+        # mean_probs.shape: batch_size, num_classes
+        logits = jnp.log(mean_probs)
+        # logits.shape: batch_size, num_classes
+      elif config.mil_pool == 'noisy-or':
+        # NOTE: I leave noisy-or unfinished because we are operating in the
+        # at-most-one error setting.
+        per_line_neg_probs = 1 - per_line_probs
+        # per_line_neg_probs.shape: batch_size, max_num_nodes, num_classes
+        class_probs = x = 1 - jnp.product(per_line_neg_probs, axis=1)
+        # x.shape: batch_size, num_classes
+        raise NotImplementedError()
+      else:
+        raise ValueError('Unexpected mil_pool parameter', config.mil_pool)
+
+    return logits, aux
diff --git a/pool/shard001/Python/0013099_logger_conf.py b/pool/shard001/Python/0013099_logger_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..533359705230b2de50b42bebf2b3664bfc23082f
--- /dev/null
+++ b/pool/shard001/Python/0013099_logger_conf.py
@@ -0,0 +1,36 @@
+import logging
+from sys import stdout
+
+
+class Log:
+    # On crée un logger : c'est pour gérer les logs de l'application
+    # On peux utiliser logger.debug(), logger.info(), logger.warning(), logger.error()
+    # Permet la mise en page des logs, leur lecture sur un fichier même sans console (si lancé en .exe par exemple)
+
+    # On crée le logger
+    logger = logging.getLogger(__name__)
+    # On définit quel niveau de log créer (si on met INFO ça ignore les debug)
+    logger.setLevel(logging.DEBUG)
+
+    # On crée un "handler" qui va gérer afficher dans la console si elle existe
+    # Le handler traite les données du logger
+    ch = logging.StreamHandler(stdout)
+    ch.setLevel(logging.DEBUG)
+
+    # On crée un "handler" qui va écrire dans un fichier les logs, réécrit à chaque lancement
+    f = logging.FileHandler("twysn.log", mode="w")
+    f.setLevel(logging.DEBUG)
+
+    # On définit le format des messages : HEURE [NIVEAU] [fonction in fichier] : message
+    formatter = logging.Formatter("%(asctime)s [%(levelname)s] [%(funcName)s in %(filename)s] : %(message)s")
+    formatter.datefmt = "%H:%M:%S"
+
+    # On définit ce format pour les 2 handlers
+    ch.setFormatter(formatter)
+    f.setFormatter(formatter)
+
+    # On ajouter les handlers au logger
+    logger.addHandler(ch)
+    logger.addHandler(f)
+
+    logger.info("Démarrage du logger.")
diff --git a/pool/shard001/Python/0013102_condition.py b/pool/shard001/Python/0013102_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..445c91277bcd5fc3e770cce621eb53f91b3086c8
--- /dev/null
+++ b/pool/shard001/Python/0013102_condition.py
@@ -0,0 +1,94 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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 typing import Optional
+
+from cproton import pn_condition_clear, pn_condition_set_name, pn_condition_set_description, pn_condition_info, \
+    pn_condition_is_set, pn_condition_get_name, pn_condition_get_description
+
+from ._data import Data, dat2obj
+
+
+class Condition:
+    """
+    An AMQP Condition object. Conditions hold exception information
+    pertaining to the closing of an AMQP endpoint such as a :class:`Connection`,
+    :class:`Session`, or :class:`Link`. Conditions also hold similar information
+    pertaining to deliveries that have reached terminal states.
+    Connections, Sessions, Links, and Deliveries may all have local and
+    remote conditions associated with them.
+
+    The local condition may be modified by the local endpoint to signal
+    a particular condition to the remote peer. The remote condition may
+    be examined by the local endpoint to detect whatever condition the
+    remote peer may be signaling. Although often conditions are used to
+    indicate errors, not all conditions are errors *per/se*, e.g.
+    conditions may be used to redirect a connection from one host to
+    another.
+
+    Every condition has a short symbolic name, a longer description,
+    and an additional info map associated with it. The name identifies
+    the formally defined condition, and the map contains additional
+    information relevant to the identified condition.
+
+    :ivar ~.name: The name of the condition.
+    :vartype ~.name: ``str``
+    :ivar ~.description: A description of the condition.
+    :vartype ~.description: ``str``
+    :ivar ~.info: A data object that holds the additional information associated
+        with the condition. The data object may be used both to access and to
+        modify the additional information associated with the condition.
+    :vartype ~.info: :class:`Data`
+    """
+
+    def __init__(self, name, description=None, info=None):
+        self.name = name
+        self.description = description
+        self.info = info
+
+    def __repr__(self) -> str:
+        return "Condition(%s)" % ", ".join([repr(x) for x in
+                                            (self.name, self.description, self.info)
+                                            if x])
+
+    def __eq__(self, o: 'Condition') -> bool:
+        if not isinstance(o, Condition):
+            return False
+        return self.name == o.name and \
+            self.description == o.description and \
+            self.info == o.info
+
+
+def obj2cond(obj, cond: Condition) -> None:
+    pn_condition_clear(cond)
+    if obj:
+        pn_condition_set_name(cond, str(obj.name))
+        pn_condition_set_description(cond, obj.description)
+        info = Data(pn_condition_info(cond))
+        if obj.info:
+            info.put_object(obj.info)
+
+
+def cond2obj(cond) -> Optional[Condition]:
+    if pn_condition_is_set(cond):
+        return Condition(pn_condition_get_name(cond),
+                         pn_condition_get_description(cond),
+                         dat2obj(pn_condition_info(cond)))
+    else:
+        return None
diff --git a/pool/shard001/Python/0013103_brillouin_gui.py b/pool/shard001/Python/0013103_brillouin_gui.py
new file mode 100644
index 0000000000000000000000000000000000000000..66f141a22768bfb1b0bf7eb391acc929e9cfb988
--- /dev/null
+++ b/pool/shard001/Python/0013103_brillouin_gui.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+"""
+description: GUI for folder processing script. Takes folder, spacing and bool
+peak crossed value and runs folder process to output csv
+author: Rohan Isaac
+"""
+import Tkinter as tk
+import tkFileDialog
+import ttk
+from brillouin_folder import process_folder
+
+
+def process(*args):
+    try:
+        output.set('Processing folder...')
+        folder_value = str(folder.get())
+        spacing_value = float(spacing.get())
+        crossed_value = bool(crossed.get())
+        process_folder(folder_value, spacing_value, crossed_value)
+        output.set('Done.')
+    except:
+        output.set('Error! Check paramters and try again')
+
+
+def askdirectory(*args):
+    folder.set(tkFileDialog.askdirectory())
+    output.set('')
+
+root = tk.Tk()
+root.title("Brillouin data processing")
+
+mainframe = ttk.Frame(root, padding="3 5 12 12")
+mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))
+mainframe.columnconfigure(0, weight=1)
+mainframe.rowconfigure(0, weight=1)
+
+folder = tk.StringVar()
+spacing = tk.StringVar()
+crossed = tk.StringVar()
+output = tk.StringVar()
+
+folder_entry = ttk.Entry(mainframe, width=20, textvariable=folder)
+spacing_entry = ttk.Entry(mainframe, width=7, textvariable=spacing)
+
+
+folder_entry.grid(column=2, row=1, sticky=(tk.W, tk.E))
+spacing_entry.grid(column=2, row=2, sticky=(tk.W, tk.E))
+
+ttk.Label(mainframe, textvariable=output).grid(
+    column=2, row=4, sticky=(tk.W, tk.E))
+ttk.Checkbutton(mainframe, text="Peaks crossed?",
+                variable=crossed).grid(column=2, row=3, stick=tk.E)
+ttk.Label(mainframe, text="Folder").grid(column=1, row=1, sticky=tk.E)
+ttk.Label(mainframe, text="Spacing").grid(column=1, row=2, sticky=tk.E)
+ttk.Label(mainframe, text="Status").grid(column=1, row=4, sticky=tk.E)
+ttk.Label(mainframe, text="cm").grid(column=3, row=2, sticky=tk.W)
+ttk.Button(mainframe, text="Browse", command=askdirectory).grid(
+    column=3, row=1, sticky=tk.E)
+ttk.Button(mainframe, text="Process", command=process).grid(
+    column=3, row=5, sticky=tk.W)
+
+
+for child in mainframe.winfo_children():
+    child.grid_configure(padx=5, pady=5)
+
+folder_entry.focus()
+root.bind('', process)
+
+root.mainloop()
diff --git a/pool/shard001/Python/0013104_utils.py b/pool/shard001/Python/0013104_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b4693fbe178436d3f71eb87bf16d0a9b02ac63f
--- /dev/null
+++ b/pool/shard001/Python/0013104_utils.py
@@ -0,0 +1,136 @@
+import sys
+import shlex
+from io import BytesIO, TextIOWrapper
+from os import WEXITSTATUS, listdir, system
+from subprocess import Popen, PIPE
+from os.path import isfile, join
+from unittest.mock import patch
+
+import self as grader
+
+
+def list_files(path, extension=''):
+    return [f for f in listdir(path) if isfile(join(path, f)) and f.endswith(extension)]
+
+
+class CaptureOutput:
+    def __init__(self):
+        self.patcher = patch('lib.print.println')
+        self.output = ''
+        self.loud_output = ''
+        self.combined_output = ''
+
+    def println(self, msg='', end='\n', loud=False):
+        self.combined_output = self.combined_output + msg + end
+
+        if loud:
+            self.loud_output = self.loud_output + msg + end
+        else:
+            self.output = self.output + msg + end
+
+    def __enter__(self):
+        self.mock = self.patcher.start()
+        self.mock.side_effect = self.println
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_trace):
+        self.output = ''
+        self.loud_output = ''
+        self.combined_output = ''
+        self.patcher.stop()
+
+    def get_quiet_output(self):
+        return self.output
+
+    def get_loud_output(self):
+        return self.loud_output
+
+    def get_output(self):
+        return self.combined_output
+
+
+class Console():
+    def __init__(self):
+        self.console_output = TextIOWrapper(BytesIO(), sys.stdout.encoding)
+
+    def __enter__(self):
+        sys.stdout = self.console_output
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.console_output.close()
+        sys.stdout = sys.__stdout__
+
+    def get_output(self):
+        self.console_output.seek(0)
+        return self.console_output.read()
+
+
+def assemble_for_selfie(file):
+    system('riscv64-linux-gnu-as tests/' + file + ' -o .instruction.o')
+    system('riscv64-linux-gnu-ld .instruction.o -o .instruction.bin >/dev/null 2>&1')
+    system('cat tests/elf-header.m .instruction.bin > .tmp.bin')
+    system('rm .instruction.o .instruction.bin')
+
+
+def compile_with_gcc(file):
+    return_value = WEXITSTATUS(system(
+        'gcc -w -D\'uint64_t=unsigned long long\' ' + file + ' -o .prog >/dev/null 2>&1'))
+
+    if return_value != 0:
+        system('rm -rf ./.prog')
+
+    return return_value
+
+
+def compile_with_gcc_and_run(file):
+    system('gcc -w -D\'uint64_t=unsigned long long\' ' + file + ' -o .prog')
+
+    process = Popen(shlex.split('./.prog'), stdout=PIPE, stderr=PIPE)
+
+    stdoutdata, stderrdata = process.communicate()
+
+    output = stdoutdata.decode(sys.stdout.encoding)
+    error_output = stderrdata.decode(sys.stderr.encoding)
+
+    system('rm ./.prog')
+
+    return (process.returncode, output, error_output)
+
+
+not_compilable = [
+    'assembler-parser',
+    'self-assembler',
+    'processes',
+    'lock',
+    'threads',
+    'treiber-stack'
+]
+
+compilable_assignments = [
+    a for a in grader.assignments if a.name not in not_compilable]
+
+
+def run_compilable_assignments(prev=None, after=None):
+    for assignment in compilable_assignments:
+        if prev != None:
+            prev(assignment)
+
+        with CaptureOutput() as capture:
+            grader.main([sys.argv[0], assignment.name])
+
+            output = capture.get_output()
+
+            if after != None:
+                after(output)
+
+
+def for_all_test_results(output, function):
+    failed = '\033[91m[FAILED]\033[0m'
+    passed = '\033[92m[PASSED]\033[0m'
+
+    for line in output.splitlines():
+        if line.startswith(failed):
+            function(False, line.split(failed)[1])
+        elif line.startswith(passed):
+            function(True, line.split(passed)[1])
diff --git a/pool/shard001/Python/0013106_web_client_test.py b/pool/shard001/Python/0013106_web_client_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fec45c6442d29a1de4987b19cafd8e008d0e4ce
--- /dev/null
+++ b/pool/shard001/Python/0013106_web_client_test.py
@@ -0,0 +1,34 @@
+import os
+
+from tests import web_client_test
+
+setUpModule = web_client_test.setUpModule
+tearDownModule = web_client_test.tearDownModule
+
+
+class WebClientTestCase(web_client_test.WebClientTestCase):
+
+    def setUp(self):
+        super(WebClientTestCase, self).setUp()
+
+        admin = self.model('user').findOne({'login': 'admin'})
+        item = self.model('item').findOne({'name': 'four_states.geojson'})
+        self.request(path='/minerva_dataset/' +
+                     str(item['_id']) + '/item', method='POST', user=admin)
+
+        item = self.model('item').findOne({'name': 'three_states.geojson'})
+        self.request(path='/minerva_dataset/' +
+                     str(item['_id']) + '/item', method='POST', user=admin)
+
+        item = self.model('item').findOne({'name': 'three_states.geojson'})
+        minervaMeta = item['meta']['minerva']
+        # simulate that dataset is postgres dataset
+        del minervaMeta['bounds']
+        self.model('item').setMetadata(item, item['meta'])
+
+        item = self.model('item').findOne({'name': 'raster.tiff'})
+        self.request(path='/minerva_dataset/' +
+                     str(item['_id']) + '/item', method='POST', user=admin)
+
+        # Create the user group for sharing feature
+        self.request(path='/minerva_dataset/prepare_sharing', method='POST', user=admin)
diff --git a/pool/shard001/Python/0013108_init__.py b/pool/shard001/Python/0013108_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..69ca8e23a73c8c99a9eeab245eeba58637f4dc9e
--- /dev/null
+++ b/pool/shard001/Python/0013108_init__.py
@@ -0,0 +1,98 @@
+"""The BleBox devices integration."""
+import logging
+
+from blebox_uniapi.error import Error
+from blebox_uniapi.products import Products
+from blebox_uniapi.session import ApiHost
+
+from homeassistant.config_entries import ConfigEntry
+from homeassistant.const import CONF_HOST, CONF_PORT
+from homeassistant.core import HomeAssistant, callback
+from homeassistant.exceptions import ConfigEntryNotReady
+from homeassistant.helpers.aiohttp_client import async_get_clientsession
+from homeassistant.helpers.entity import Entity
+
+from .const import DEFAULT_SETUP_TIMEOUT, DOMAIN, PRODUCT
+
+_LOGGER = logging.getLogger(__name__)
+
+PLATFORMS = ["cover", "sensor", "switch", "air_quality", "light", "climate"]
+
+PARALLEL_UPDATES = 0
+
+
+async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
+    """Set up BleBox devices from a config entry."""
+
+    websession = async_get_clientsession(hass)
+
+    host = entry.data[CONF_HOST]
+    port = entry.data[CONF_PORT]
+    timeout = DEFAULT_SETUP_TIMEOUT
+
+    api_host = ApiHost(host, port, timeout, websession, hass.loop)
+
+    try:
+        product = await Products.async_from_host(api_host)
+    except Error as ex:
+        _LOGGER.error("Identify failed at %s:%d (%s)", api_host.host, api_host.port, ex)
+        raise ConfigEntryNotReady from ex
+
+    domain = hass.data.setdefault(DOMAIN, {})
+    domain_entry = domain.setdefault(entry.entry_id, {})
+    product = domain_entry.setdefault(PRODUCT, product)
+
+    hass.config_entries.async_setup_platforms(entry, PLATFORMS)
+
+    return True
+
+
+async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
+    """Unload a config entry."""
+    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
+
+    if unload_ok:
+        hass.data[DOMAIN].pop(entry.entry_id)
+
+    return unload_ok
+
+
+@callback
+def create_blebox_entities(
+    hass, config_entry, async_add_entities, entity_klass, entity_type
+):
+    """Create entities from a BleBox product's features."""
+
+    product = hass.data[DOMAIN][config_entry.entry_id][PRODUCT]
+
+    entities = []
+    if entity_type in product.features:
+        for feature in product.features[entity_type]:
+            entities.append(entity_klass(feature))
+
+    async_add_entities(entities, True)
+
+
+class BleBoxEntity(Entity):
+    """Implements a common class for entities representing a BleBox feature."""
+
+    def __init__(self, feature):
+        """Initialize a BleBox entity."""
+        self._feature = feature
+        self._attr_name = feature.full_name
+        self._attr_unique_id = feature.unique_id
+        product = feature.product
+        self._attr_device_info = {
+            "identifiers": {(DOMAIN, product.unique_id)},
+            "name": product.name,
+            "manufacturer": product.brand,
+            "model": product.model,
+            "sw_version": product.firmware_version,
+        }
+
+    async def async_update(self):
+        """Update the entity state."""
+        try:
+            await self._feature.async_update()
+        except Error as ex:
+            _LOGGER.error("Updating '%s' failed: %s", self.name, ex)
diff --git a/pool/shard001/Python/0013118_init__.py b/pool/shard001/Python/0013118_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01edc0975b22cc814acede4f5645e3442a88c8cd
--- /dev/null
+++ b/pool/shard001/Python/0013118_init__.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+###############################################################################
+#  Copyright Kitware Inc.
+#
+#  Licensed under the Apache License, Version 2.0 ( the "License" );
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+###############################################################################
+
+import datetime
+import hashlib
+
+from girder import events
+from girder.api import access
+from girder.api.describe import Description, autoDescribeRoute
+from girder.api.rest import boundHandler
+from girder.api.v1.collection import Collection
+from girder.constants import AccessType, TokenScope
+from girder.exceptions import RestException
+from girder.models.collection import Collection as CollectionModel
+from girder.models.user import User
+from girder.plugin import GirderPlugin
+
+
+@access.user(scope=TokenScope.DATA_READ)
+@boundHandler
+@autoDescribeRoute(
+    Description('Accept a collection\'s Terms of Use for the current user.')
+    .modelParam('id', model=CollectionModel, level=AccessType.READ)
+    .param('termsHash', 'The SHA-256 hash of this collection\'s terms, encoded in hexadecimal.')
+)
+def acceptCollectionTerms(self, collection, termsHash):
+    if not collection.get('terms'):
+        raise RestException('This collection currently has no terms.')
+
+    # termsHash should be encoded to a bytes object, but storing bytes into MongoDB behaves
+    # differently in Python 2 vs 3. Additionally, serializing a bytes to JSON behaves differently
+    # in Python 2 vs 3. So, just keep it as a unicode (or ordinary Python 2 str).
+    realTermsHash = hashlib.sha256(collection['terms'].encode('utf-8')).hexdigest()
+    if termsHash != realTermsHash:
+        # This "proves" that the client has at least accessed the terms
+        raise RestException(
+            'The submitted "termsHash" does not correspond to the collection\'s current terms.')
+
+    User().update(
+        {'_id': self.getCurrentUser()['_id']},
+        {'$set': {
+            'terms.collection.%s' % collection['_id']: {
+                'hash': termsHash,
+                'accepted': datetime.datetime.now()
+            }
+        }}
+    )
+
+
+def afterPostPutCollection(event):
+    # This will only trigger if no exceptions (for access, invalid id, etc.) are thrown
+    extraParams = event.info['params']
+    if 'terms' in extraParams:
+        collectionResponse = event.info['returnVal']
+        collectionId = collectionResponse['_id']
+        terms = extraParams['terms']
+
+        CollectionModel().update(
+            {'_id': collectionId},
+            {'$set': {'terms': terms}}
+        )
+
+        collectionResponse['terms'] = terms
+        event.addResponse(collectionResponse)
+
+
+class TermsPlugin(GirderPlugin):
+    DISPLAY_NAME = 'Terms of Use'
+    CLIENT_SOURCE_PATH = 'web_client'
+
+    def load(self, info):
+        # Augment the collection creation and edit routes to accept a terms field
+        events.bind('rest.post.collection.after', 'terms', afterPostPutCollection)
+        events.bind('rest.put.collection/:id.after', 'terms', afterPostPutCollection)
+        for handler in [
+            Collection.createCollection,
+            Collection.updateCollection
+        ]:
+            handler.description.param(
+                'terms', 'The Terms of Use for the collection.', required=False)
+
+        # Expose the terms field on all collections
+        CollectionModel().exposeFields(level=AccessType.READ, fields={'terms'})
+
+        # Add endpoint for registered users to accept terms
+        info['apiRoot'].collection.route('POST', (':id', 'acceptTerms'), acceptCollectionTerms)
+
+        # Expose the terms field on all users
+        User().exposeFields(level=AccessType.ADMIN, fields={'terms'})
diff --git a/pool/shard001/Python/0013121_display.py b/pool/shard001/Python/0013121_display.py
new file mode 100644
index 0000000000000000000000000000000000000000..926bd315eaf31b6a0f5ee69f4b4c09e86d67eb0e
--- /dev/null
+++ b/pool/shard001/Python/0013121_display.py
@@ -0,0 +1,147 @@
+
+import curses
+import logging
+
+from datetime import datetime as datetime # lol
+from itertools import *
+
+class Display(object):
+
+    def __init__(self, screen):
+        self.time_fmt = "%d.%B.%Y %I:%M%p"
+        self.monitor = None
+        self.latest_hits = [ ]
+
+        self.screen = screen
+        self.width = curses.COLS - 1
+        self.y = 0
+
+        self._init_screen()
+
+    def _init_screen(self):
+        # clear the screen
+        self.screen.clear()
+
+        # add a row of stars on the top row of the monitor
+        self._add_full_row(self.y)
+        self.y += 1
+
+        # add a centered title for the monitor
+        self.screen.addstr(self.y, 0, "*")
+        title = "HTTP Traffic Monitor"
+        self.screen.addstr(self.y, int(self.width/2 - len(title)/2), title)
+        self.screen.addstr(self.y, self.width - 1, "*")
+        self.y += 1
+
+        # add a row of fulls below the title
+        self._add_full_row(self.y)
+        self.y += 1
+
+        # add an alerts table header
+        self._add_to_table(
+                self.y, "Alerts", "Started", "Ended", "Hits per Minute")
+        self.y += 1
+
+        # add a row of fulls below the alerts table header
+        self._add_full_row(self.y)
+        self.y += 1
+
+        # add an empty row to the table
+        self._add_to_table(self.y)
+
+        self.screen.refresh()
+
+    def _add_full_row(self, y, char="*"):
+        ''' add a row of a repeating char in row y '''
+        for x in range(0, self.width): self.screen.addstr(y, x, char)
+
+    def _add_to_table(self, y, col1='', col2='', col3='', col4=''):
+        '''
+        add elements to a row y. for any column to be written, esase what is
+        already there and replace it with a string.
+        '''
+        col_width = int(self.width / 4) - 1
+        xs = [ n + n * col_width for n in range(0, 5) ]
+
+        for x in xs: self.screen.addstr(y, x, "*")
+
+        # if column string, clear out all the column and add the string
+        if col1:
+            for x in range(xs[0] + 1, xs[1]): self.screen.addstr(y, x, " ")
+            start_x = int(((xs[0] + xs[1]) / 2) - len(col1) / 2)
+            self.screen.addstr(y, start_x, col1)
+
+        if col2:
+            for x in range(xs[1] + 1, xs[2]): self.screen.addstr(y, x, " ")
+            start_x = int(((xs[1] + xs[2]) / 2) - len(col2) / 2)
+            self.screen.addstr(y, start_x, col2)
+
+        if col3:
+            for x in range(xs[2] + 1, xs[3]): self.screen.addstr(y, x, " ")
+            start_x = int(((xs[2] + xs[3]) / 2) - len(col3) / 2)
+            self.screen.addstr(y, start_x, col3)
+
+        if col4:
+            for x in range(xs[3] + 1, xs[4]): self.screen.addstr(y, x, " ")
+            start_x = int(((xs[3] + xs[4]) / 2) - len(col4) / 2)
+            self.screen.addstr(y, start_x, col4)
+
+    def _get_popular_section(self):
+        ''' sort the latest hits by section and return the most popular one. '''
+        if len(self.latest_hits) == 0: return '  (0)'
+
+        # sort the list, group them, and find the max one
+        most_popular = ''
+        largest_size  = 0
+        for item, group in  groupby(sorted(self.latest_hits)):
+            size = len(list(group))
+            if size > largest_size:
+                largest_size = size
+                most_popular = item.get_section()
+
+        return most_popular
+
+    def _get_accumulated_size(self):
+        return sum(li.size for li in self.latest_hits)
+
+    def set_monitor(self, monitor):
+        self.monitor = monitor 
+        self.update_display()
+
+    def high_traffic_alert(self):
+        ''' durring a high traffic alert, add a new alert to the table '''
+        alert = self.monitor.get_latest_alert()
+        time = alert.start_time.strftime(self.time_fmt)
+        hpm = "{0:.4f}".format(alert.hits / alert.duration().seconds * 60)
+
+        self._add_to_table(self.y, col2=time, col3="ONGOING", col4=hpm)
+        self.update_display()
+
+    def low_traffic_alert(self):
+        '''
+        add an end time to the latest alert, increment the row index of the
+        table.
+        '''
+        alert = self.monitor.get_latest_alert()
+        time = alert.end_time.strftime(self.time_fmt)
+        hpm = "{0:.4f}".format(alert.hits / alert.duration().seconds * 60)
+
+        self._add_to_table(self.y, col3=time, col4=hpm)
+        self.y += 1
+
+        self.update_display()
+
+    def update_display(self):
+        ''' clear the bottom of the screen and update with some useful stats '''
+        popular = self._get_popular_section()
+        size = self._get_accumulated_size()
+
+        # clear the bottom of our screen
+        for row in range(1, 6): self._add_full_row(self.y + row, char=" ")
+
+        self._add_full_row(self.y + 2)
+        self.screen.addstr(self.y + 4, 0, "Popular Section: %s" % popular)
+        self.screen.addstr(self.y + 5, 0, "Total Size Downloaded: %s" % size)
+        self.screen.addstr(self.y + 6, 0, "Time: %s" % datetime.now()) 
+
+        self.screen.refresh()
diff --git a/pool/shard001/Python/0013124_lang_twig.py b/pool/shard001/Python/0013124_lang_twig.py
new file mode 100644
index 0000000000000000000000000000000000000000..28f8a61b3c904e4b96957b60c3006cda95b0c3e5
--- /dev/null
+++ b/pool/shard001/Python/0013124_lang_twig.py
@@ -0,0 +1,226 @@
+#!/usr/bin/env python
+# Copyright (c) 2006-2012 ActiveState Software Inc.
+# See LICENSE.txt for license details.
+
+"""Twig support for codeintel"""
+
+import logging
+
+from codeintel2.common import *
+from codeintel2.langintel import LangIntel
+from codeintel2.udl import UDLLexer, UDLBuffer, UDLCILEDriver, XMLParsingBufferMixin
+
+if _xpcom_:
+    from xpcom.server import UnwrapObject
+
+#---- globals
+
+lang = "Twig"
+log = logging.getLogger("codeintel.twig")
+
+
+twig_keywords = [
+    "and",
+    "as",
+    "b-and",
+    "b-or",
+    "b-xor",
+    "by",
+    "in",
+    "not",
+    "or",
+]
+twig_keywords2 = [
+    "attribute",
+    "block",
+    "constant",
+    "cycle",
+    "date",
+    "dump",
+    "parent",
+    "random",
+    "range",
+
+    "constant",
+    "defined",
+    "divisibleby",
+    "empty",
+    "even",
+    "iterable",
+    "null",
+    "odd",
+    "sameas",
+]
+twig_keywords += twig_keywords2
+
+twig_tags = [
+    "autoescape",
+    "block",
+    "do",
+    "embed",
+    "extends",
+    "filter",
+    "flush",
+    "for",
+    "from",
+    "if",
+    "import",
+    "include",
+    "macro",
+    "raw",
+    "sandbox",
+    "set",
+    "spaceless",
+    "use",
+
+    # end tags
+    "endautoescape",
+    "endblock",
+    "endcomment",
+    "endembed",
+    "endfilter",
+    "endfor",
+    "endif",
+    "endmacro",
+    "endraw",
+    "endsandbox",
+    "endspaceless",
+    "endwith",
+]
+
+twig_default_filter_names = [
+    # These are default filter names in twig
+    "capitalize",
+    "convert_encoding",
+    "date",
+    "default",
+    "escape",
+    "format",
+    "join",
+    "json_encode",
+    "keys",
+    "length",
+    "lower",
+    "merge",
+    "nl2br",
+    "number_format",
+    "raw",
+    "replace",
+    "reverse",
+    "slice",
+    "sort",
+    "striptags",
+    "title",
+    "trim",
+    "upper",
+    "url_encode",
+]
+
+
+#---- language support
+
+class TwigLexer(UDLLexer):
+    lang = lang
+
+
+class TwigBuffer(UDLBuffer, XMLParsingBufferMixin):
+    lang = lang
+    tpl_lang = lang
+    m_lang = "HTML"
+    css_lang = "CSS"
+    csl_lang = "JavaScript"
+    ssl_lang = "Twig"
+
+    # Characters that should close an autocomplete UI:
+    # - wanted for XML completion: ">'\" "
+    # - wanted for CSS completion: " ('\";},.>"
+    # - wanted for JS completion:  "~`!@#%^&*()-=+{}[]|\\;:'\",.<>?/ "
+    # - dropping ':' because I think that may be a problem for XML tag
+    #   completion with namespaces (not sure of that though)
+    # - dropping '[' because need for "" -> "?/"
+
+
+class TwigLangIntel(LangIntel):
+    lang = lang
+
+    # Used by ProgLangTriggerIntelMixin.preceding_trg_from_pos()
+    trg_chars = tuple('| ')
+    calltip_trg_chars = tuple()
+
+    def trg_from_pos(self, buf, pos, implicit=True, DEBUG=False):
+        """
+            CODE       CONTEXT      RESULT
+            '{<|>'     anywhere     tag names, i.e. {% if %}
+            'foo|<|>'  filters      filter names, i.e. {{ foo|capfirst }}
+        """
+        # DEBUG = True # not using 'logging' system, because want to be fast
+        if DEBUG:
+            print "\n----- Twig trg_from_pos(pos=%r, implicit=%r) -----"\
+                  % (pos, implicit)
+
+        if pos < 2:
+            return None
+        accessor = buf.accessor
+        last_pos = pos - 1
+        last_char = accessor.char_at_pos(last_pos)
+        if DEBUG:
+            print "  last_pos: %s" % last_pos
+            print "  last_char: %r" % last_char
+            print 'accessor.text_range(last_pos-2, last_pos): %r' % (accessor.text_range(last_pos-2, last_pos), )
+
+        if last_char == " " and \
+           accessor.text_range(last_pos-2, last_pos) == "{%":
+            if DEBUG:
+                print "  triggered: 'complete-tags'"
+            return Trigger(lang, TRG_FORM_CPLN,
+                           "complete-tags", pos, implicit)
+
+        if last_char == "|":
+            if DEBUG:
+                print "  triggered: 'complete-filters'"
+            return Trigger(lang, TRG_FORM_CPLN,
+                           "complete-filters", pos, implicit)
+
+    _twigtag_cplns = [("element", t) for t in sorted(twig_tags)]
+    _twigfilter_cplns = [("function", t) for t in sorted(
+        twig_default_filter_names)]
+
+    def async_eval_at_trg(self, buf, trg, ctlr):
+        if _xpcom_:
+            trg = UnwrapObject(trg)
+            ctlr = UnwrapObject(ctlr)
+
+        ctlr.start(buf, trg)
+
+        # Twig tag completions
+        if trg.id == (lang, TRG_FORM_CPLN, "complete-tags"):
+            ctlr.set_cplns(self._twigtag_cplns)
+            ctlr.done("success")
+            return
+        if trg.id == (lang, TRG_FORM_CPLN, "complete-filters"):
+            ctlr.set_cplns(self._twigfilter_cplns)
+            ctlr.done("success")
+            return
+
+        ctlr.done("success")
+
+
+class TwigCILEDriver(UDLCILEDriver):
+    lang = lang
+    csl_lang = "JavaScript"
+    tpl_lang = "Twig"
+
+
+#---- registration
+def register(mgr):
+    """Register language support with the Manager."""
+    mgr.set_lang_info(lang,
+                      silvercity_lexer=TwigLexer(),
+                      buf_class=TwigBuffer,
+                      langintel_class=TwigLangIntel,
+                      import_handler_class=None,
+                      cile_driver_class=TwigCILEDriver,
+                      is_cpln_lang=True)
diff --git a/pool/shard001/Python/0013126_baker.py b/pool/shard001/Python/0013126_baker.py
new file mode 100644
index 0000000000000000000000000000000000000000..430297ae0a55990eaa1b7f2a0cb1b16a9f5038c7
--- /dev/null
+++ b/pool/shard001/Python/0013126_baker.py
@@ -0,0 +1,15 @@
+from historia.pops.logic.logic_base import LogicBase
+from historia.economy.enums.resource import Good
+
+class BakerLogic(LogicBase):
+
+    def perform(self):
+        grain = self.get_good(Good.grain)
+
+        if grain is None:
+            # fine $2 for being idle
+            self.charge_idle_money()
+        else:
+            # convert all grain to bread
+            self.produce(Good.bread, grain.amount * 2)
+            self.consume(Good.grain, grain.amount)
diff --git a/pool/shard001/Python/0013133_image_mean.py b/pool/shard001/Python/0013133_image_mean.py
new file mode 100644
index 0000000000000000000000000000000000000000..170a7fe23b1af520c05ffd18b869dbee77267281
--- /dev/null
+++ b/pool/shard001/Python/0013133_image_mean.py
@@ -0,0 +1,109 @@
+# # Training Mean
+# 
+# This notebook calculates the mean (by color channel) of the training images.
+# This value is used in the keras-frcnn config.py file for network training and testing.
+
+import sys
+import os
+sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
+
+import tools.CONSTANTS as c
+import tools.IMAGEUTILS as im
+import tools.XMLUTILS as xu
+import numpy as np
+
+
+class MeanFinder():
+    """
+    calculates the mean (by color channel, RGB) of the specifed directories.
+    This value put in the keras-frcnn config.py file for network training
+    and testing. 
+    """
+    
+    def __init__(self, allowed_dirs):
+        """
+        initializes the MeanFinder, assigning allowed_dirs to an attribute
+        
+        :param allowed_dirs: the target directories that will be used
+        :type  allowed_dirs: list of strings
+        """
+        self.allowed_dirs = allowed_dirs # only include if from these dirs
+        
+    
+    def process_img_filepath(self, img_filepath):
+        """
+        computes the mean of the image at img_filepath
+        
+        :param annotation: a pascal VOC XML annotation
+        :type  annotation: Element
+
+        :param img_filepath: the filepath of the image on training machine
+        :type  img_filepath: string
+        """
+        return np.mean(im.imread(img_filepath), axis=(0,1))
+        
+            
+    def file_standards(self, file, filepath):
+        """
+        checks to make sure that the file should be processed further. In
+        this case:
+        
+        The file must be an xml file
+        The filepath must not be from xml_preds
+        One of the allowed directory names must be in the filepath
+        
+        :param file: the name of the file
+        :type  file: string
+        :param filepath: the full filepath of the file
+        :type  filepath: string
+        
+        :returns: whether or not the file/filepath should be included
+        :rtype  : bool
+        """
+        is_xml   = bool(file[-4:] == c.XML_EXT)
+        not_pred = bool('xml_preds' not in filepath)
+        allowed_dir = any([dir_ in filepath for dir_ in self.allowed_dirs])
+        return (all([is_xml, not_pred, allowed_dir]))
+        
+        
+    def format_filepath(self, filepath):
+        """
+        change from xml file to img file
+        
+        :returns: the formatted filepath
+        :rtype  : string
+        """
+        return filepath.replace('xmls', 'imgs').replace(c.XML_EXT, c.IMG_EXT)
+        
+        
+    def process_files(self):
+        """
+        walk through all files and calculate the image mean. We make sure 
+        that each image is 
+        
+        :returns: the mean of the images
+        :rtype  : ndarray
+        """
+        means = []
+        #iterate through all files
+        for root, dirs, files in os.walk(c.BASE_DIR):
+            for file in sorted(files):
+                filepath = os.path.join(root, file)
+
+                # only allow images in the standardized format that have been annotated
+                if self.file_standards(file, filepath):
+                    # open_xml_file is called here instead of in file_standards
+                    # to reduce unessessary xml processing
+                    annotation = xu.open_xml_file(filepath)
+                    
+                    # only process images that contain objects
+                    if xu.contains_objects(annotation):
+                        img_filepath = self.format_filepath(filepath)
+                        means.append(self.process_img_filepath(img_filepath))
+        
+        return(np.mean(means, axis=(0)))
+
+
+if __name__ == '__main__':
+    train_mean = MeanFinder(c.TRAIN_VID_KEYS)
+    print("Train mean: " + str(train_mean.process_files()))
diff --git a/pool/shard001/Python/0013134_main.py b/pool/shard001/Python/0013134_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..77657364bff41d58dac2bd17ca787842f4720086
--- /dev/null
+++ b/pool/shard001/Python/0013134_main.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python
+"""
+Main API handlers.
+"""
+
+
+from google.appengine.api import capabilities
+
+from . import base
+from tools import appstats_serializer
+
+
+__all__ = [
+    'AppStats',
+    'AppStatsList',
+    'Health',
+    'Version',
+]
+
+
+class AppStats(base.BaseHandler):
+  """Return output from AppStats."""
+
+  # TODO(eric): Restrict to admins only.
+  #@base.admin_required
+  def get(self, timestamp, *args, **kwargs):
+    full_proto = appstats_serializer.load_full_proto_from_timestamp(timestamp)
+    resp = appstats_serializer.request_stats_to_dict(full_proto)
+    self.render(resp)
+
+
+class AppStatsList(base.BaseHandler):
+  """Return output from AppStats."""
+
+  # TODO(eric): Restrict to admins only.
+  #@base.admin_required
+  def get(self, *args, **kwargs):
+    resp = appstats_serializer.appstats_to_dict(summaries_only=True)
+    self.render(resp)
+
+
+class Health(base.BaseHandler):
+  """Return a list of services and their status."""
+
+  def get(self, *args, **kwargs):
+    resp = {
+        'services': self.services(),
+    }
+    self.render(resp)
+
+  def services(self):
+    """Return the status and admin message list for all available services."""
+    blobstore_api = capabilities.CapabilitySet('blobstore')
+    datastore_read_api = capabilities.CapabilitySet('datastore_v3')
+    datastore_write_api = capabilities.CapabilitySet('datastore_v3', ['write'])
+    mail_api = capabilities.CapabilitySet('mail')
+    memcache_api = capabilities.CapabilitySet('memcache')
+    taskqueue_api = capabilities.CapabilitySet('taskqueue')
+    urlfetch_api = capabilities.CapabilitySet('urlfetch')
+    return [
+        {'blobstore': {
+            'enabled': blobstore_api.is_enabled(),
+            'message': blobstore_api.admin_message(),
+        }},
+        {'datastore_read': {
+            'enabled': datastore_read_api.is_enabled(),
+            'message': datastore_read_api.admin_message(),
+        }},
+        {'datastore_write': {
+            'enabled': datastore_write_api.is_enabled(),
+            'message': datastore_write_api.admin_message(),
+        }},
+        {'mail': {
+            'enabled': mail_api.is_enabled(),
+            'message': mail_api.admin_message(),
+        }},
+        {'memcache': {
+            'enabled': memcache_api.is_enabled(),
+            'message': memcache_api.admin_message(),
+        }},
+        {'taskqueue': {
+            'enabled': taskqueue_api.is_enabled(),
+            'message': taskqueue_api.admin_message(),
+        }},
+        {'urlfetch': {
+            'enabled': urlfetch_api.is_enabled(),
+            'message': urlfetch_api.admin_message(),
+        }},
+    ]
+
+
+class Version(base.BaseHandler):
+  """Returns the current app version."""
+
+  def get(self, *args, **kwargs):
+    resp = {
+        'version': base.get_version_id(),
+    }
+    self.render(resp)
diff --git a/pool/shard001/Python/0013140_movie_queue.py b/pool/shard001/Python/0013140_movie_queue.py
new file mode 100644
index 0000000000000000000000000000000000000000..7afe4ab6cf2f3123dfedbab88539e354b62022e8
--- /dev/null
+++ b/pool/shard001/Python/0013140_movie_queue.py
@@ -0,0 +1,127 @@
+from __future__ import unicode_literals, division, absolute_import
+from argparse import ArgumentParser
+
+from sqlalchemy.exc import OperationalError
+
+from flexget import options
+from flexget.event import event
+from flexget.plugin import DependencyError
+from flexget.utils import qualities
+from flexget.utils.tools import console
+
+try:
+    from flexget.plugins.filter.movie_queue import QueueError, queue_add, queue_del, queue_get, queue_forget, parse_what
+except ImportError:
+    raise DependencyError(issued_by='cli_movie_queue', missing='movie_queue')
+
+
+def do_cli(manager, options):
+    """Handle movie-queue subcommand"""
+
+    if options.queue_action == 'list':
+        queue_list(options)
+        return
+
+    # If the action affects make sure all entries are processed again next run.
+    manager.config_changed()
+
+    if options.queue_action == 'clear':
+        clear()
+        return
+
+    if options.queue_action == 'del':
+        try:
+            what = parse_what(options.movie_name, lookup=False)
+            title = queue_del(**what)
+        except QueueError as e:
+            console('ERROR: %s' % e.message)
+        else:
+            console('Removed %s from queue' % title)
+        return
+
+    if options.queue_action == 'forget':
+        try:
+            what = parse_what(options.movie_name, lookup=False)
+            title = queue_forget(**what)
+        except QueueError as e:
+            console('ERROR: %s' % e.message)
+        else:
+            console('Forgot that %s was downloaded. Movie will be downloaded again.' % title)
+        return
+
+    if options.queue_action == 'add':
+        try:
+            quality = qualities.Requirements(options.quality)
+        except ValueError as e:
+            console('`%s` is an invalid quality requirement string: %s' % (options.quality, e.message))
+            return
+
+        # Adding to queue requires a lookup for missing information
+        what = {}
+        try:
+            what = parse_what(options.movie_name)
+        except QueueError as e:
+            console('ERROR: %s' % e.message)
+
+        if not what.get('title') or not (what.get('imdb_id') or what.get('tmdb_id')):
+            console('could not determine movie')  # TODO: Rethink errors
+            return
+
+        try:
+            queue_add(quality=quality, **what)
+        except QueueError as e:
+            console(e.message)
+            if e.errno == 1:
+                # This is an invalid quality error, display some more info
+                # TODO: Fix this error?
+                #console('Recognized qualities are %s' % ', '.join([qual.name for qual in qualities.all()]))
+                console('ANY is the default and can also be used explicitly to specify that quality should be ignored.')
+        except OperationalError:
+            console('OperationalError')
+        return
+
+
+def queue_list(options):
+    """List movie queue"""
+    items = queue_get(downloaded=(options.type == 'downloaded'))
+    console('-' * 79)
+    console('%-10s %-7s %-37s %s' % ('IMDB id', 'TMDB id', 'Title', 'Quality'))
+    console('-' * 79)
+    for item in items:
+        console('%-10s %-7s %-37s %s' % (item.imdb_id, item.tmdb_id, item.title, item.quality))
+    if not items:
+        console('No results')
+    console('-' * 79)
+
+
+def clear():
+    """Deletes waiting movies from queue"""
+    items = queue_get(downloaded=False)
+    console('Removing the following movies from movie queue:')
+    console('-' * 79)
+    for item in items:
+        console(item.title)
+        queue_del(title=item.title)
+    if not items:
+        console('No results')
+    console('-' * 79)
+
+@event('options.register')
+def register_parser_arguments():
+    # Common option to be used in multiple subparsers
+    what_parser = ArgumentParser(add_help=False)
+    what_parser.add_argument('movie_name', metavar='',
+                             help='the movie (can be movie title, imdb id, or in the form `tmdb_id=XXXX`')
+    # Register subcommand
+    parser = options.register_command('movie-queue', do_cli, help='view and manage the movie queue')
+    # Set up our subparsers
+    subparsers = parser.add_subparsers(title='actions', metavar='', dest='queue_action')
+    list_parser = subparsers.add_parser('list', help='list movies from the queue')
+    list_parser.add_argument('type', nargs='?', choices=['waiting', 'downloaded'], default='waiting',
+                             help='choose to show waiting or already downloaded movies')
+    add_parser = subparsers.add_parser('add', parents=[what_parser], help='add a movie to the queue')
+    add_parser.add_argument('quality', metavar='', default='ANY', nargs='?',
+                            help='the quality requirements for getting this movie (default: %(default)s)')
+    subparsers.add_parser('del', parents=[what_parser], help='remove a movie from the queue')
+    subparsers.add_parser('forget', parents=[what_parser], help='remove the downloaded flag from a movie')
+    subparsers.add_parser('clear', help='remove all un-downloaded movies from the queue')
diff --git a/pool/shard001/Python/0013141_test_tables_sort.py b/pool/shard001/Python/0013141_test_tables_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ab60f726728b83a2feb2cb7ee9d5a82a65feaef
--- /dev/null
+++ b/pool/shard001/Python/0013141_test_tables_sort.py
@@ -0,0 +1,57 @@
+import pytest
+from utils import testgen
+from utils.version import current_version
+from cfme.web_ui import toolbar, SortTable
+from cfme.containers.project import Project
+from cfme.containers.replicator import Replicator
+from cfme.containers.service import Service
+from cfme.containers.route import Route
+from cfme.containers.provider import ContainersProvider
+from utils.appliance.implementations.ui import navigate_to
+from utils.blockers import BZ
+
+
+pytestmark = [
+    pytest.mark.uncollectif(
+        lambda: current_version() < "5.6"),
+    pytest.mark.usefixtures('setup_provider'),
+    pytest.mark.tier(1)]
+pytest_generate_tests = testgen.generate([ContainersProvider], scope='function')
+
+
+TEST_OBJECTS = [
+    pytest.mark.polarion('CMP-9924')(ContainersProvider),
+    pytest.mark.polarion('CMP-9925')(Project),
+    pytest.mark.polarion('CMP-9926')(Route),
+    pytest.mark.polarion('CMP-9927')(Service),
+    pytest.mark.polarion('CMP-9928')(Replicator)
+]
+
+
+@pytest.mark.meta(blockers=[
+    BZ(1392413, unblock=lambda cls: cls != ContainersProvider),
+    BZ(1409360, unblock=lambda cls: cls != ContainersProvider)
+])
+@pytest.mark.parametrize('cls', TEST_OBJECTS)
+def test_containers_main_pages_sort(cls):
+
+    pytest.skip('This test is currently skipped due to an issue in the testing framework:'
+                ' https://github.com/ManageIQ/integration_tests/issues/4052')
+
+    navigate_to(cls, 'All')
+    toolbar.select('List View')
+    # NOTE: We must re-instantiate here sort_tbl in order to prevent StaleElementException
+    sort_tbl = SortTable(table_locator="//div[@id='list_grid']//table")
+    header_texts = [header.text for header in sort_tbl.headers]
+    for col, header_text in enumerate(header_texts):
+
+        if not header_text:
+            continue
+
+        # Checking both orders
+        sort_tbl.sort_by(header_text, 'ascending')
+        rows_ascending = [r[col].text for r in sort_tbl.rows()]
+        sort_tbl.sort_by(header_text, 'descending')
+        rows_descending = [r[col].text for r in sort_tbl.rows()]
+
+        assert rows_ascending[::-1] == rows_descending
diff --git a/pool/shard001/Python/0013142_setup.py b/pool/shard001/Python/0013142_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..c78a713c2e1fb9e0374fd6d85039c9fb393e7526
--- /dev/null
+++ b/pool/shard001/Python/0013142_setup.py
@@ -0,0 +1,47 @@
+from setuptools import setup, find_packages
+
+__title__ = 'footynews'
+__author__ = 'Usman Ehtesham Gul'
+__email__ = 'uehtesham90@gmail.com'
+__license__ = 'Apache v2.0'
+__version__ = '0.0.1'
+__url__ = 'https://github.com/footynews/fn_backend'
+
+with open('requirements.txt') as f:
+    requires = f.read().splitlines()
+
+with open("LICENSE") as f:
+    license = f.read()
+
+classifiers = [
+    # How mature is this project? Common values are
+    #   3 - Alpha
+    #   4 - Beta
+    #   5 - Production/Stablegit
+    'Development Status :: 3 - Alpha',
+
+    # Indicate who your project is intended for
+    'Intended Audience :: Developers',
+    'Topic :: Software Development :: Build Tools',
+
+    # Pick your license as you wish (should match "license" above)
+    'License :: OSI Approved :: MIT License',
+
+    # Specify the Python versions you support here. In particular, ensure
+    # that you indicate whether you support Python 2, Python 3 or both.
+    'Programming Language :: Python :: 3.4',
+]
+
+setup(
+    name=__title__,
+    version=__version__,
+    description='Aggregate football articles from various sources',
+    author=__author__,
+    license=license,
+    classifiers=classifiers,
+    keywords="python football soccer articles",
+    author_email=__email__,
+    url=__url__,
+    packages=find_packages(exclude='tests'),
+    install_requires=requires,
+)
diff --git a/pool/shard001/Python/0013145_exhaustive_one_d_agent_test.py b/pool/shard001/Python/0013145_exhaustive_one_d_agent_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..f61475eb833ab0b98e2c1867a660e6be07a6562c
--- /dev/null
+++ b/pool/shard001/Python/0013145_exhaustive_one_d_agent_test.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+# ----------------------------------------------------------------------
+# Numenta Platform for Intelligent Computing (NuPIC)
+# Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and conditions apply:
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero Public License version 3 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU Affero Public License for more details.
+#
+# You should have received a copy of the GNU Affero Public License
+# along with this program.  If not, see http://www.gnu.org/licenses.
+#
+# http://numenta.org/licenses/
+# ----------------------------------------------------------------------
+
+import unittest2 as unittest
+
+from sensorimotor.one_d_world import OneDWorld
+from sensorimotor.one_d_universe import OneDUniverse
+from sensorimotor.exhaustive_one_d_agent import ExhaustiveOneDAgent
+
+
+
+class ExhaustiveOneDAgentTest(unittest.TestCase):
+
+
+  def testChooseMotorValue(self):
+    numElements = 5
+    universe = OneDUniverse(nSensor=100, wSensor=5,
+                            nMotor=100, wMotor=5)
+    world = OneDWorld(universe, range(numElements))
+    agent = ExhaustiveOneDAgent(world, 0)
+
+    motorValues = []
+
+    for _ in range(numElements ** 2):
+      motorValue = agent.chooseMotorValue()
+      agent.move(motorValue)
+      motorValues.append(motorValue)
+
+    self.assertEqual(motorValues,
+       [1, -1, 2, -2, 3, -3, 4, -4, 1, 1, -1, 2, -2, 3, -3, 1, 1, -1, 2, -2, 1, 1, -1, 1, -4])
+
+
+  def testChooseMotorValueStartAt2(self):
+    numElements = 5
+    universe = OneDUniverse(nSensor=100, wSensor=5,
+                            nMotor=100, wMotor=5)
+    world = OneDWorld(universe, range(numElements))
+    agent = ExhaustiveOneDAgent(world, 2)
+
+    motorValues = []
+
+    for _ in range(numElements ** 2):
+      motorValue = agent.chooseMotorValue()
+      agent.move(motorValue)
+      motorValues.append(motorValue)
+
+    self.assertEqual(motorValues,
+       [-2, 2, -1, 1, 1, -1, 2, -2, -2, 1, -1, 3, -3, 4, -4, 1, 2, -2, 3, -3, 2, 1, -1, 1, -2])
+
+
+if __name__ == "__main__":
+  unittest.main()
diff --git a/pool/shard001/Python/0013147_test_utils.py b/pool/shard001/Python/0013147_test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d77e6caf92e97f030afd121dd2272b11abc75498
--- /dev/null
+++ b/pool/shard001/Python/0013147_test_utils.py
@@ -0,0 +1,16 @@
+from rest_framework_json_schema.utils import parse_include
+
+
+def test_parse_include_empty() -> None:
+    result = parse_include("")
+    assert result == {}
+
+
+def test_parse_include_single() -> None:
+    result = parse_include("a")
+    assert result == {"a": {}}
+
+
+def test_parse_include_complicated() -> None:
+    result = parse_include("a,a.b,a.c.d,e.f,g")
+    assert result == {"a": {"b": {}, "c": {"d": {}}}, "e": {"f": {}}, "g": {}}
diff --git a/pool/shard001/Python/0013148_simpExample.py b/pool/shard001/Python/0013148_simpExample.py
new file mode 100644
index 0000000000000000000000000000000000000000..f31eb69d79f956242012970871c44f7eba0d0e9d
--- /dev/null
+++ b/pool/shard001/Python/0013148_simpExample.py
@@ -0,0 +1,60 @@
+from liggghts import liggghts
+
+# Try loading in liggghts
+lmp = liggghts()
+
+# Try reading in an input file
+lmp.file("in.simpExample")
+
+
+# Try performing a command
+print("")
+print("Attempting to run simulation another 500 steps")
+lmp.command("run 500")
+
+# Try extracting a global value
+print("")
+print("Attempting to get the number of atoms in simulation")
+numAtoms = lmp.extract_global("natoms", 0)
+print("natoms =", numAtoms)
+
+# Try extracting atom's positions
+print("")
+print("Attempting to get the atom's positions")
+pos = lmp.extract_atom("x",3)
+for k in range(0,numAtoms):
+    print("Pos[%i] = [%f, %f, %f]" % (k, pos[k][0], pos[k][1], pos[k][2]))
+
+# Try extracting a compute
+print("")
+print("Attempting to get the rotational KE")
+rke = lmp.extract_compute("rke",0,0)
+print("rke = %f" % rke)
+
+# Try extracting a fix
+print("")
+print("Attempting to get the pos_z before python ran another 500 steps")
+z0 = lmp.extract_fix("z0",1,1)
+print("z0[0] = %f" % z0[0])
+
+# Try extracting a variable
+print("")
+print("Attempting to get the density variable used in simulation")
+density = lmp.extract_variable("density","all",0)
+print("density = %f" % density)
+
+# Testing get_natoms
+print("")
+print("Testing get_natoms")
+natoms = lmp.get_natoms()
+print("natoms = %i" % natoms)
+
+# Testing gather_atoms
+print("")
+print("Testing gather_atoms (NOTICE THAT IDS ARE DIFFERENT!!!)")
+x_gather_atoms = lmp.gather_atoms("x",1,3)
+for k in range(natoms):
+    x = x_gather_atoms[3*k+0]
+    y = x_gather_atoms[3*k+1]
+    z = x_gather_atoms[3*k+2]
+    print("x[%i] = [%f, %f, %f]" % (k, x, y, z))
diff --git a/pool/shard001/Python/0013151_exon2sql.py b/pool/shard001/Python/0013151_exon2sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb2f49b8a13f7bde814b491c2fad7b1319957d6
--- /dev/null
+++ b/pool/shard001/Python/0013151_exon2sql.py
@@ -0,0 +1,22 @@
+#!/usr/bin/python
+
+import sys
+import sqlite3
+
+db    = sqlite3.connect(sys.argv[1])
+dbcmd = db.cursor()
+
+table  = open(sys.argv[2])
+header = table.readline().rstrip().split("\t")
+
+dbcmd.execute('create table exom (gene, exonnum, celline, depth)')
+db.commit()
+
+for i in table:
+	fields     = i.rstrip().split()
+	gene, exon = fields[0].split(":")
+	for j in range(1, len(fields)):
+		dbcmd.execute('insert into exom values(?,?,?,?)', (gene, exon, header[j - 1], fields[j]))
+table.close()
+db.commit()
+db.close()
diff --git a/pool/shard001/Python/0013161_test_middleware.py b/pool/shard001/Python/0013161_test_middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..a71c648d427d3e6af1938ee3797d67ac7a17bb50
--- /dev/null
+++ b/pool/shard001/Python/0013161_test_middleware.py
@@ -0,0 +1,93 @@
+"""
+    Tests for middleware for comprehensive themes.
+"""
+
+from __future__ import absolute_import
+
+from django.contrib.messages.middleware import MessageMiddleware
+from django.contrib.sites.models import Site
+from django.test import RequestFactory, TestCase, override_settings
+
+from openedx.core.djangoapps.theming.middleware import CurrentSiteThemeMiddleware
+from student.tests.factories import UserFactory
+
+from ..views import set_user_preview_site_theme
+
+TEST_URL = '/test'
+TEST_THEME_NAME = 'test-theme'
+
+
+class TestCurrentSiteThemeMiddleware(TestCase):
+    """
+    Test theming middleware.
+    """
+    def setUp(self):
+        """
+        Initialize middleware and related objects
+        """
+        super(TestCurrentSiteThemeMiddleware, self).setUp()
+
+        self.site_theme_middleware = CurrentSiteThemeMiddleware()
+        self.user = UserFactory.create()
+
+    def create_mock_get_request(self):
+        """
+        Returns a mock GET request.
+        """
+        request = RequestFactory().get(TEST_URL)
+        self.initialize_mock_request(request)
+        return request
+
+    def initialize_mock_request(self, request):
+        """
+        Initialize a test request.
+        """
+        request.user = self.user
+        request.site, __ = Site.objects.get_or_create(domain='test', name='test')
+        request.session = {}
+        MessageMiddleware().process_request(request)
+
+    @override_settings(DEFAULT_SITE_THEME=TEST_THEME_NAME)
+    def test_default_site_theme(self):
+        """
+        Test that request.site_theme returns theme defined by DEFAULT_SITE_THEME setting
+        when there is no theme associated with the current site.
+        """
+        request = self.create_mock_get_request()
+        self.assertEqual(self.site_theme_middleware.process_request(request), None)
+        self.assertIsNotNone(request.site_theme)
+        self.assertEqual(request.site_theme.theme_dir_name, TEST_THEME_NAME)
+
+    @override_settings(DEFAULT_SITE_THEME=None)
+    def test_default_site_theme_2(self):
+        """
+        Test that request.site_theme returns None when there is no theme associated with
+        the current site and DEFAULT_SITE_THEME is also None.
+        """
+        request = self.create_mock_get_request()
+        self.assertEqual(self.site_theme_middleware.process_request(request), None)
+        self.assertIsNone(request.site_theme)
+
+    def test_preview_theme(self):
+        """
+        Verify that preview themes behaves correctly.
+        """
+        # First request a preview theme
+        post_request = RequestFactory().post('/test')
+        self.initialize_mock_request(post_request)
+        set_user_preview_site_theme(post_request, TEST_THEME_NAME)
+
+        # Next request a page and verify that the theme is returned
+        get_request = self.create_mock_get_request()
+        self.assertEqual(self.site_theme_middleware.process_request(get_request), None)
+        self.assertEqual(get_request.site_theme.theme_dir_name, TEST_THEME_NAME)
+
+        # Request to reset the theme
+        post_request = RequestFactory().post('/test')
+        self.initialize_mock_request(post_request)
+        set_user_preview_site_theme(post_request, None)
+
+        # Finally verify that no theme is returned
+        get_request = self.create_mock_get_request()
+        self.assertEqual(self.site_theme_middleware.process_request(get_request), None)
+        self.assertIsNone(get_request.site_theme)
diff --git a/pool/shard001/Python/0013162_blinksticklight.py b/pool/shard001/Python/0013162_blinksticklight.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6a6ef465a8f1ea64b3f81f034d1496c722c2d8c
--- /dev/null
+++ b/pool/shard001/Python/0013162_blinksticklight.py
@@ -0,0 +1,97 @@
+"""
+Support for Blinkstick lights.
+
+For more details about this platform, please refer to the documentation at
+https://home-assistant.io/components/light.blinksticklight/
+"""
+import logging
+
+import voluptuous as vol
+
+from homeassistant.components.light import (
+    ATTR_RGB_COLOR, SUPPORT_RGB_COLOR, Light, PLATFORM_SCHEMA)
+from homeassistant.const import CONF_NAME
+import homeassistant.helpers.config_validation as cv
+
+REQUIREMENTS = ['blinkstick==1.1.8']
+
+_LOGGER = logging.getLogger(__name__)
+
+CONF_SERIAL = 'serial'
+
+DEFAULT_NAME = 'Blinkstick'
+
+SUPPORT_BLINKSTICK = SUPPORT_RGB_COLOR
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
+    vol.Required(CONF_SERIAL): cv.string,
+    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
+})
+
+
+# pylint: disable=unused-argument
+def setup_platform(hass, config, add_devices, discovery_info=None):
+    """Set up Blinkstick device specified by serial number."""
+    from blinkstick import blinkstick
+
+    name = config.get(CONF_NAME)
+    serial = config.get(CONF_SERIAL)
+
+    stick = blinkstick.find_by_serial(serial)
+
+    add_devices([BlinkStickLight(stick, name)])
+
+
+class BlinkStickLight(Light):
+    """Representation of a BlinkStick light."""
+
+    def __init__(self, stick, name):
+        """Initialize the light."""
+        self._stick = stick
+        self._name = name
+        self._serial = stick.get_serial()
+        self._rgb_color = stick.get_color()
+
+    @property
+    def should_poll(self):
+        """Set up polling."""
+        return True
+
+    @property
+    def name(self):
+        """Return the name of the light."""
+        return self._name
+
+    @property
+    def rgb_color(self):
+        """Read back the color of the light."""
+        return self._rgb_color
+
+    @property
+    def is_on(self):
+        """Check whether any of the LEDs colors are non-zero."""
+        return sum(self._rgb_color) > 0
+
+    @property
+    def supported_features(self):
+        """Flag supported features."""
+        return SUPPORT_BLINKSTICK
+
+    def update(self):
+        """Read back the device state."""
+        self._rgb_color = self._stick.get_color()
+
+    def turn_on(self, **kwargs):
+        """Turn the device on."""
+        if ATTR_RGB_COLOR in kwargs:
+            self._rgb_color = kwargs[ATTR_RGB_COLOR]
+        else:
+            self._rgb_color = [255, 255, 255]
+
+        self._stick.set_color(red=self._rgb_color[0],
+                              green=self._rgb_color[1],
+                              blue=self._rgb_color[2])
+
+    def turn_off(self, **kwargs):
+        """Turn the device off."""
+        self._stick.turn_off()
diff --git a/pool/shard001/Python/0013164_generate_cifar10_tfrecords.py b/pool/shard001/Python/0013164_generate_cifar10_tfrecords.py
new file mode 100644
index 0000000000000000000000000000000000000000..841377e03bc19180835727bd5c6bb042383a8dfe
--- /dev/null
+++ b/pool/shard001/Python/0013164_generate_cifar10_tfrecords.py
@@ -0,0 +1,153 @@
+# Copyright 2019 The Google Research Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Read CIFAR-10 data from pickled numpy arrays and writes TFRecords.
+
+Generates tf.train.Example protos and writes them to TFRecord files from the
+python version of the CIFAR-10 dataset downloaded from
+https://www.cs.toronto.edu/~kriz/cifar.html.
+
+Based on script from
+https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10_estimator/generate_cifar10_tfrecords.py
+
+To run:
+  python generate_cifar10_tfrecords.py --data_dir=/tmp/cifar-tfrecord
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import argparse
+import os
+import sys
+
+import tarfile
+from six.moves import cPickle as pickle
+import tensorflow as tf
+
+CIFAR_FILENAME = 'cifar-10-python.tar.gz'
+CIFAR_DOWNLOAD_URL = 'https://www.cs.toronto.edu/~kriz/' + CIFAR_FILENAME
+CIFAR_LOCAL_FOLDER = 'cifar-10-batches-py'
+
+
+def download_and_extract(data_dir):
+  # download CIFAR-10 if not already downloaded.
+  tf.contrib.learn.datasets.base.maybe_download(CIFAR_FILENAME, data_dir,
+                                                CIFAR_DOWNLOAD_URL)
+  tarfile.open(os.path.join(data_dir, CIFAR_FILENAME),
+               'r:gz').extractall(data_dir)
+
+
+def _int64_feature(value):
+  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
+
+
+def _bytes_feature(value):
+  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
+
+
+def _get_file_names():
+  """Returns the file names expected to exist in the input_dir."""
+  file_names = {}
+  for i in range(1, 5):
+    file_names['train_%d' % i] = 'data_batch_%d' % i
+  file_names['validation'] = 'data_batch_5'
+  file_names['test'] = 'test_batch'
+  return file_names
+
+
+def read_pickle_from_file(filename):
+  with tf.gfile.Open(filename, 'rb') as f:
+    if sys.version_info >= (3, 0):
+      data_dict = pickle.load(f, encoding='bytes')
+    else:
+      data_dict = pickle.load(f)
+  return data_dict
+
+
+def convert_to_tfrecord(input_file, output_file):
+  """Converts a file to TFRecords."""
+  print('Generating %s' % output_file)
+  with tf.python_io.TFRecordWriter(output_file) as record_writer:
+    data_dict = read_pickle_from_file(input_file)
+    data = data_dict[b'data']
+    labels = data_dict[b'labels']
+    num_entries_in_batch = len(labels)
+    print('Converting %d images' % num_entries_in_batch)
+    for i in range(num_entries_in_batch):
+      example = tf.train.Example(features=tf.train.Features(
+          feature={
+              'image': _bytes_feature(data[i].tobytes()),
+              'label': _int64_feature(labels[i])
+          }))
+      record_writer.write(example.SerializeToString())
+
+
+def main(data_dir):
+  print('Download from {} and extract.'.format(CIFAR_DOWNLOAD_URL))
+  download_and_extract(data_dir)
+  file_names = _get_file_names()
+  input_dir = os.path.join(data_dir, CIFAR_LOCAL_FOLDER)
+  for mode, f in file_names.items():
+    input_file = os.path.join(input_dir, f)
+    output_file = os.path.join(data_dir, mode + '.tfrecords')
+    try:
+      os.remove(output_file)
+    except OSError:
+      pass
+    # Convert to tf.train.Example and write the to TFRecords.
+    convert_to_tfrecord(input_file, output_file)
+
+  # Save fixed batch of 100 examples (first 10 of each class sampled at the
+  # front of the validation set). Ordered by label, i.e. 10 "airplane" images
+  # followed by 10 "automobile" images...
+  images = [[] for _ in range(10)]
+  num_images = 0
+  input_file = os.path.join(input_dir, file_names['validation'])
+  data_dict = read_pickle_from_file(input_file)
+  data = data_dict[b'data']
+  labels = data_dict[b'labels']
+  for i in range(len(labels)):
+    label = labels[i]
+    if len(images[label]) < 10:
+      images[label].append(
+          tf.train.Example(features=tf.train.Features(
+              feature={
+                  'image': _bytes_feature(data[i].tobytes()),
+                  'label': _int64_feature(label)
+              })))
+      num_images += 1
+      if num_images == 100:
+        break
+
+  output_file = os.path.join(data_dir, 'sample.tfrecords')
+  print('Generating %s' % output_file)
+  with tf.python_io.TFRecordWriter(output_file) as record_writer:
+    for label_images in images:
+      for example in label_images:
+        record_writer.write(example.SerializeToString())
+  print('Done!')
+
+
+if __name__ == '__main__':
+  parser = argparse.ArgumentParser()
+  parser.add_argument(
+      '--data_dir',
+      type=str,
+      default='',
+      help='Directory to download and extract CIFAR-10 to.')
+
+  args = parser.parse_args()
+  main(args.data_dir)
diff --git a/pool/shard001/Python/0013171_test_float.py b/pool/shard001/Python/0013171_test_float.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb47db8eb087adb749e3176b89cda197cf437325
--- /dev/null
+++ b/pool/shard001/Python/0013171_test_float.py
@@ -0,0 +1,110 @@
+
+import unittest, struct
+from test import test_support
+
+class FormatFunctionsTestCase(unittest.TestCase):
+
+    def setUp(self):
+        self.save_formats = {'double':float.__getformat__('double'),
+                             'float':float.__getformat__('float')}
+
+    def tearDown(self):
+        float.__setformat__('double', self.save_formats['double'])
+        float.__setformat__('float', self.save_formats['float'])
+
+    def test_getformat(self):
+        self.assert_(float.__getformat__('double') in
+                     ['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
+        self.assert_(float.__getformat__('float') in
+                     ['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
+        self.assertRaises(ValueError, float.__getformat__, 'chicken')
+        self.assertRaises(TypeError, float.__getformat__, 1)
+
+    def test_setformat(self):
+        for t in 'double', 'float':
+            float.__setformat__(t, 'unknown')
+            if self.save_formats[t] == 'IEEE, big-endian':
+                self.assertRaises(ValueError, float.__setformat__,
+                                  t, 'IEEE, little-endian')
+            elif self.save_formats[t] == 'IEEE, little-endian':
+                self.assertRaises(ValueError, float.__setformat__,
+                                  t, 'IEEE, big-endian')
+            else:
+                self.assertRaises(ValueError, float.__setformat__,
+                                  t, 'IEEE, big-endian')
+                self.assertRaises(ValueError, float.__setformat__,
+                                  t, 'IEEE, little-endian')
+            self.assertRaises(ValueError, float.__setformat__,
+                              t, 'chicken')
+        self.assertRaises(ValueError, float.__setformat__,
+                          'chicken', 'unknown')
+
+BE_DOUBLE_INF = '\x7f\xf0\x00\x00\x00\x00\x00\x00'
+LE_DOUBLE_INF = ''.join(reversed(BE_DOUBLE_INF))
+BE_DOUBLE_NAN = '\x7f\xf8\x00\x00\x00\x00\x00\x00'
+LE_DOUBLE_NAN = ''.join(reversed(BE_DOUBLE_NAN))
+
+BE_FLOAT_INF = '\x7f\x80\x00\x00'
+LE_FLOAT_INF = ''.join(reversed(BE_FLOAT_INF))
+BE_FLOAT_NAN = '\x7f\xc0\x00\x00'
+LE_FLOAT_NAN = ''.join(reversed(BE_FLOAT_NAN))
+
+# on non-IEEE platforms, attempting to unpack a bit pattern
+# representing an infinity or a NaN should raise an exception.
+
+class UnknownFormatTestCase(unittest.TestCase):
+    def setUp(self):
+        self.save_formats = {'double':float.__getformat__('double'),
+                             'float':float.__getformat__('float')}
+        float.__setformat__('double', 'unknown')
+        float.__setformat__('float', 'unknown')
+
+    def tearDown(self):
+        float.__setformat__('double', self.save_formats['double'])
+        float.__setformat__('float', self.save_formats['float'])
+
+    def test_double_specials_dont_unpack(self):
+        for fmt, data in [('>d', BE_DOUBLE_INF),
+                          ('>d', BE_DOUBLE_NAN),
+                          ('f', BE_FLOAT_INF),
+                          ('>f', BE_FLOAT_NAN),
+                          ('d', BE_DOUBLE_INF),
+                              ('>d', BE_DOUBLE_NAN),
+                              ('f', BE_FLOAT_INF),
+                              ('>f', BE_FLOAT_NAN),
+                              (' _INOTIFY_EVENT_SIZE:
+          wd, mask, cookie, length = _INOTIFY_EVENT.unpack(
+              self._inotify_events[:_INOTIFY_EVENT_SIZE])
+          if len(self._inotify_events) < _INOTIFY_EVENT_SIZE + length:
+            break
+
+          name = self._inotify_events[
+              _INOTIFY_EVENT_SIZE:_INOTIFY_EVENT_SIZE + length]
+          name = name.rstrip('\0')
+
+          logging.debug(
+              'wd=%s, mask=%s, cookie=%s, length=%s, name=%r', wd,
+              _bit_str(mask, _ATTRIBUTE_MASK_NAMES), cookie, length, name)
+
+          self._inotify_events = self._inotify_events[
+              _INOTIFY_EVENT_SIZE + length:]
+
+          if mask & IN_IGNORED:
+            continue
+          try:
+            directory = self._watch_to_directory[wd]
+          except KeyError:
+            logging.debug('Watch deleted for watch descriptor=%d', wd)
+            continue
+
+          path = os.path.join(directory, name)
+          if os.path.isdir(path) or path in self._directory_to_watch_descriptor:
+            if mask & IN_DELETE:
+              self._remove_watch_for_path(path)
+            elif mask & IN_MOVED_FROM:
+              self._remove_watch_for_path(path)
+            elif mask & IN_CREATE:
+              self._add_watch_for_path(path)
+            elif mask & IN_MOVED_TO:
+              self._add_watch_for_path(path)
+          if path not in paths and not watcher_common.ignore_file(path):
+            paths.add(path)
+    return paths
diff --git a/pool/shard001/Python/0013184_H.py b/pool/shard001/Python/0013184_H.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dea8a641dd4503e654ebcee9e4710e60f142256
--- /dev/null
+++ b/pool/shard001/Python/0013184_H.py
@@ -0,0 +1,19 @@
+from sys import stdin
+from math import pi
+
+def readLine():
+	return stdin.readline().strip()
+
+def readInt():
+	return int(readLine())
+
+def readInts():
+	return list(map(int, readLine().split()))
+
+def main():
+    A, P1 = readInts()
+    R, P2 = readInts()
+    print('Whole pizza' if (A * 1.0 / P1) < ((pi * R * R) / P2) else 'Slice of pizza')
+
+if __name__ == '__main__':
+	main()
\ No newline at end of file
diff --git a/pool/shard001/Python/0013187_CreateEdgeList_EuclideanPolygon.py b/pool/shard001/Python/0013187_CreateEdgeList_EuclideanPolygon.py
new file mode 100644
index 0000000000000000000000000000000000000000..29cd30978c6904087843fe3069261d8fb7134c4f
--- /dev/null
+++ b/pool/shard001/Python/0013187_CreateEdgeList_EuclideanPolygon.py
@@ -0,0 +1,80 @@
+#---------------------------------------------------------------------------------
+# CreateEdgeList_EuclideanPolygon.py
+#
+# Description: Creates an edge list using Euclidean distances from patch
+#  centroids. This is much faster, but possibly less accurate than the
+#  cost distance approach.
+#
+# Inputs:   
+# Output:  {patch connected area table}
+#  
+# June 14, 2012
+# John.Fay@duke.edu
+#---------------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcpy, math
+import arcpy.sa as sa
+
+# Check out any necessary licenses
+arcpy.CheckOutExtension("spatial")
+arcpy.env.overwriteOutput = True
+
+# Input variables
+subPatchRaster = r'C:\WorkSpace\GHAT\GeoHAT_016_Squirrel\Data\SubPatches'#sys.argv[1]
+searchRadius = ''
+
+# Output variables
+edgeListFN = r'C:\WorkSpace\GHAT\GeoHAT_016_Squirrel\Scratch\PolyEdges.csv'
+
+##---FUNCTIONS---
+def msg(txt):
+    print txt
+    arcpy.AddMessage(txt)
+    return
+
+##---PROCESSES---
+# Convert raster to polygon
+msg("Converting %s to polygons" %subPatchRaster)
+tmpPoly = "in_memory/tmpPoly"
+arcpy.RasterToPolygon_conversion(subPatchRaster,tmpPoly,"NO_SIMPLIFY")
+dslvPoly =  "in_memory/dslvPoly"
+arcpy.Dissolve_management(tmpPoly,dslvPoly,"grid_code")
+
+# Generate near table
+nearTable = "in_memory/NearTable"
+arcpy.GenerateNearTable_analysis(dslvPoly,dslvPoly,nearTable,searchRadius,"LOCATION","NO_ANGLE","ALL")
+
+# Join IDs back to near table
+arcpy.JoinField_management(nearTable,"IN_FID",dslvPoly,"OBJECTID","grid_code")
+arcpy.JoinField_management(nearTable,"NEAR_FID",dslvPoly,"OBJECTID","grid_code")
+arcpy.CopyRows_management(nearTable,r'C:\WorkSpace\GHAT\GeoHAT_016_Squirrel\Scratch\scratch.gdb\nearTable')
+
+# Create the output file
+edgeFile = open(edgeListFN, 'w')
+edgeFile.write("FromID, ToID, Distance, FromX, FromY, ToX, ToY\n")
+
+# Update the fields in the PtDist Table
+msg("Writing edge list to %s" %edgeListFN)
+rows = arcpy.SearchCursor(nearTable,"grid_code < grid_code_1")
+row = rows.next()
+while row:
+    fromID = row.grid_code
+    toID = row.grid_code_1
+    fromRec = arcpy.SearchCursor(nearTable,"grid_code = %s AND grid_code_1 = %s" %(toID, fromID)).next()
+    if fromRec:
+        fromX = fromRec.NEAR_X
+        fromY = fromRec.NEAR_Y
+    else:
+        fromX = 0
+        fromY = 0
+    del fromRec
+    toX = row.NEAR_X
+    toY = row.NEAR_Y
+    distance = round(row.NEAR_DIST)
+    edgeFile.write("%d, %d, %d, %s, %s, %s, %s\n" %(fromID,toID,distance,fromX,fromY,toX,toY))
+    row = rows.next()
+edgeFile.close()
+
+   
+msg("Finished")
\ No newline at end of file
diff --git a/pool/shard001/Python/0013189_download_base_donnees_publique_medicaments_gouv_fr.py b/pool/shard001/Python/0013189_download_base_donnees_publique_medicaments_gouv_fr.py
new file mode 100644
index 0000000000000000000000000000000000000000..8db66c703b5932fd97a2c7c7b3a5ee39abb1f541
--- /dev/null
+++ b/pool/shard001/Python/0013189_download_base_donnees_publique_medicaments_gouv_fr.py
@@ -0,0 +1,116 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+# Drugs-Harvesters -- Harvesters to collect data on medications
+# By: Emmanuel Raviart 
+#
+# Copyright (C) 2013 Etalab
+# http://github.com/eraviart/drugs-harvesters
+#
+# This file is part of Drugs-Harvesters.
+#
+# Drugs-Harvesters is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Drugs-Harvesters is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program.  If not, see .
+
+
+"""Download drugs pages from http://base-donnees-publique.medicaments.gouv.fr"""
+
+
+import argparse
+import codecs
+import itertools
+import json
+import logging
+import os
+import shutil
+import sys
+import urlparse
+
+import lxml.html
+import requests
+
+
+app_name = os.path.splitext(os.path.basename(__file__))[0]
+log = logging.getLogger(app_name)
+site_url = 'http://base-donnees-publique.medicaments.gouv.fr/'
+
+
+def main():
+    parser = argparse.ArgumentParser(description = __doc__)
+    parser.add_argument('-a', '--all', action = 'store_true', help = 'download all pages')
+    parser.add_argument('-d', '--download-dir', default = 'base-donnees-publique.medicaments.gouv.fr',
+        help = 'directory where to store downloaded pages')
+    parser.add_argument('-i', '--index', action = 'store_true', help = 'download index pages')
+    parser.add_argument('-p', '--pages', action = 'store_true', help = 'download drugs pages')
+    parser.add_argument('-v', '--verbose', action = 'store_true', help = 'increase output verbosity')
+
+    args = parser.parse_args()
+    logging.basicConfig(level = logging.INFO if args.verbose else logging.WARNING, stream = sys.stdout)
+
+    if not os.path.exists(args.download_dir):
+        os.makedirs(args.download_dir)
+
+    index_path = os.path.join(args.download_dir, 'index.json')
+    if args.all or args.index:
+        drug_name_by_url_path = {}
+        form_data = dict(
+            affliste = 1,
+            affNumero = 0,
+            choixRecherche = 'medicament',
+            inClauseSubst = 0,
+            isAlphabet = 0,
+#            nomSubstances =
+            page = 1,
+            radLibelle = 2,
+            radLibelleSub = 4,
+#            txtCaracteresSub =
+#            txtCaracteres =
+            typeRecherche = 0,
+            )
+        for page_number in itertools.count(1):
+            log.info(u'Harvesting index page {}'.format(page_number))
+            form_data['page'] = page_number
+            response = requests.post(urlparse.urljoin(site_url, 'index.php'), data = form_data)
+            html_element = lxml.html.fromstring(response.content)
+            a_element_list = html_element.xpath('//table[@class="result"]//a[@class="standart"]')
+            if not a_element_list:
+                break
+            for a_element in a_element_list:
+                drug_name_by_url_path[a_element.get('href')] = a_element.text.strip()
+        with codecs.open(index_path, 'w', encoding = 'utf-8') as index_file:
+            json.dump(drug_name_by_url_path, index_file, ensure_ascii = False, indent = 2, sort_keys = True)
+    else:
+        with codecs.open(index_path, encoding = 'utf-8') as index_file:
+            drug_name_by_url_path = json.load(index_file)
+
+    if args.all or args.pages:
+        pages_dir = os.path.join(args.download_dir, 'pages')
+        if os.path.exists(pages_dir):
+            shutil.rmtree(pages_dir)
+        os.makedirs(pages_dir)
+
+        for url_path, drug_name in sorted(drug_name_by_url_path.iteritems()):
+            drug_id = url_path.rsplit('=', 1)[-1]
+            log.info(u'Harvesting drug {}: {}'.format(drug_id, drug_name))
+            response = requests.get(urlparse.urljoin(site_url, url_path))
+            drug_path = os.path.join(pages_dir, 'page-{}.html'.format(drug_id))
+            with open(drug_path, 'w') as drug_file:
+                for chunk in response.iter_content(8192):
+                    drug_file.write(chunk)
+
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/pool/shard001/Python/0013191_crypto_pricing_loader.py b/pool/shard001/Python/0013191_crypto_pricing_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..da98c988a7268827ce2681d5289724a9bfe1a183
--- /dev/null
+++ b/pool/shard001/Python/0013191_crypto_pricing_loader.py
@@ -0,0 +1,147 @@
+# Copyright 2015 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from numpy import (
+    iinfo,
+    uint32,
+)
+
+from catalyst.data.us_equity_pricing import BcolzDailyBarReader
+from catalyst.lib.adjusted_array import AdjustedArray
+from catalyst.errors import NoFurtherDataError
+from catalyst.utils.calendars import get_calendar
+
+from .base import PipelineLoader
+
+UINT32_MAX = iinfo(uint32).max
+
+
+class CryptoPricingLoader(PipelineLoader):
+    """
+    PipelineLoader for Crypto Pricing data
+
+    Delegates loading of baselines and adjustments.
+    """
+
+    def __init__(self, bundle, data_frequency, dataset):
+
+        cal = get_calendar('OPEN')
+
+        if data_frequency == 'daily':
+            reader = bundle.daily_bar_reader
+            all_sessions = cal.all_sessions
+
+        elif data_frequency == 'minute':
+            reader = bundle.minute_bar_reader
+            all_sessions = cal.all_minutes
+
+        else:
+            raise ValueError(
+                'Invalid data frequency: {}'.format(data_frequency)
+            )
+
+        self.raw_price_loader = reader
+        self._columns = dataset.columns
+        self._all_sessions = all_sessions
+
+    @classmethod
+    def from_files(cls, pricing_path):
+        """
+        Create a loader from a bcolz equity pricing dir and a SQLite
+        adjustments path.
+
+        Parameters
+        ----------
+        pricing_path : str
+            Path to a bcolz directory written by a BcolzDailyBarWriter.
+        """
+        return cls(
+            BcolzDailyBarReader(pricing_path),
+        )
+
+    def load_adjusted_array(self, columns, dates, assets, mask):
+        # load_adjusted_array is called with dates on which the user's algo
+        # will be shown data, which means we need to return the data that would
+        # be known at the start of each date.  We assume that the latest data
+        # known on day N is the data from day (N - 1), so we shift all query
+        # dates back by a day.
+        start_date, end_date = _shift_dates(
+            self._all_sessions, dates[0], dates[-1], shift=1,
+        )
+        colnames = [c.name for c in columns]
+        raw_arrays = self.raw_price_loader.load_raw_arrays(
+            colnames,
+            start_date,
+            end_date,
+            assets,
+        )
+
+        out = {}
+        for c, c_raw in zip(columns, raw_arrays):
+            out[c] = AdjustedArray(
+                c_raw.astype(c.dtype),
+                mask,
+                {},
+                c.missing_value,
+            )
+        return out
+
+    @property
+    def columns(self):
+        return self._columns
+
+
+def _shift_dates(dates, start_date, end_date, shift):
+
+    try:
+        start = dates.get_loc(start_date)
+    except KeyError:
+        if start_date < dates[0]:
+            raise NoFurtherDataError(
+                msg=(
+                    "Pipeline Query requested data starting on {query_start}, "
+                    "but first known date is {calendar_start}"
+                ).format(
+                    query_start=str(start_date),
+                    calendar_start=str(dates[0]),
+                )
+            )
+        else:
+            raise ValueError("Query start %s not in calendar" % start_date)
+
+    # Make sure that shifting doesn't push us out of the calendar.
+    if start < shift:
+        raise NoFurtherDataError(
+            msg=(
+                "Pipeline Query requested data from {shift}"
+                " days before {query_start}, but first known date is only "
+                "{start} days earlier."
+            ).format(shift=shift, query_start=start_date, start=start),
+        )
+
+    try:
+        end = dates.get_loc(end_date)
+    except KeyError:
+        if end_date > dates[-1]:
+            raise NoFurtherDataError(
+                msg=(
+                    "Pipeline Query requesting data up to {query_end}, "
+                    "but last known date is {calendar_end}"
+                ).format(
+                    query_end=end_date,
+                    calendar_end=dates[-1],
+                )
+            )
+        else:
+            raise ValueError("Query end %s not in calendar" % end_date)
+    return dates[start - shift], dates[end - shift]
diff --git a/pool/shard001/Python/0013192_RubySmellBear.py b/pool/shard001/Python/0013192_RubySmellBear.py
new file mode 100644
index 0000000000000000000000000000000000000000..630ffb029536f0e9184f0ceaab60b25e53346e25
--- /dev/null
+++ b/pool/shard001/Python/0013192_RubySmellBear.py
@@ -0,0 +1,183 @@
+import json
+
+from coalib.bearlib import deprecate_settings
+from coalib.bearlib.abstractions.Linter import linter
+from coalib.bears.requirements.GemRequirement import GemRequirement
+from coalib.results.Result import Result
+from coalib.results.SourceRange import SourceRange
+from coala_utils.param_convertion import negate
+
+
+@linter(executable='reek', use_stdin=True)
+class RubySmellBear:
+    """
+    Detect code smells in Ruby source code.
+
+    For more information about the detected smells, see
+    .
+    """
+
+    LANGUAGES = {"Ruby"}
+    REQUIREMENTS = {GemRequirement('reek')}
+    AUTHORS = {'The coala developers'}
+    AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
+    LICENSE = 'AGPL-3.0'
+    CAN_DETECT = {'Smell'}
+
+    @staticmethod
+    def create_arguments(filename, file, config_file):
+        return '--format', 'json', '-c', config_file
+
+    def process_output(self, output, filename, file):
+        output = json.loads(output) if output else ()
+        for issue in output:
+            sourceranges = []
+            for line in issue['lines']:
+                sourceranges.append(SourceRange.from_values(
+                    file=filename, start_line=line))
+
+            if 'name' in issue:
+                message = "'{}' (in '{}') {}.".format(
+                    issue['name'], issue['context'], issue['message'])
+            else:
+                message = "'{}' {}".format(issue['context'], issue['message'])
+
+            yield Result(
+                origin="{} ({})".format(self.__class__.__name__,
+                                        issue['smell_type']),
+                message=message,
+                affected_code=sourceranges,
+                additional_info="More information is available at {}"
+                                ".".format(issue["wiki_link"]))
+
+    @deprecate_settings(allow_duplicate_method=(
+                            'duplicate_method_call', negate),
+                        allow_data_clump=('data_clump', negate),
+                        allow_control_parameters=('control_parameter', negate),
+                        allow_class_variables=('class_variable', negate),
+                        allow_boolean_parameter_in_functions=(
+                            'boolean_parameter', negate),
+                        allow_setter_in_classes=('attribute', negate),
+                        allow_unused_private_methods=(
+                            'unused_private_method', negate),
+                        allow_unused_variables=('unused_params', negate))
+    def generate_config(self,
+                        allow_setter_in_classes: bool=False,
+                        allow_boolean_parameter_in_functions: bool=False,
+                        allow_class_variables: bool=False,
+                        allow_control_parameters: bool=False,
+                        allow_data_clump: bool=False,
+                        allow_duplicate_method: bool=False,
+                        feature_envy: bool=True,
+                        missing_module_description: bool=True,
+                        long_param_list: bool=True,
+                        long_yield_list: bool=True,
+                        module_initialize: bool=True,
+                        nested_iterators: bool=True,
+                        nil_check: bool=True,
+                        prima_donna_method: bool=True,
+                        repeated_conditional: bool=True,
+                        too_many_instance_variables: bool=True,
+                        too_many_methods: bool=True,
+                        too_long_method: bool=True,
+                        bad_method_name: bool=True,
+                        bad_module_name: bool=True,
+                        bad_param_name: bool=True,
+                        bad_var_name: bool=True,
+                        allow_unused_variables: bool=False,
+                        allow_unused_private_methods: bool=True,
+                        utility_function: bool=True):
+        """
+        :param allow_setter_in_classes:
+            Allows setter in classes.
+        :param allow_boolean_parameter_in_functions:
+            Allows boolean parameter in functions (control coupling).
+        :param allow_class_variables:
+            Allows class variables.
+        :param allow_control_parameters:
+            Allows parameters that control function behaviour (control
+            coupling).
+        :param allow_data_clump:
+            Does not warn when the same two or three items frequently appear
+            together in function/class parameter list.
+        :param allow_duplicate_method:
+            Allows having two fragments of code that look nearly identical, or
+            two fragments of code that have nearly identical effects at some
+            conceptual level.
+        :param feature_envy:
+            Occurs when a code fragment references another object more often
+            than it references itself, or when several clients do the same
+            series of manipulations on a particular type of object.
+        :param missing_module_description:
+            Warns if a module description is missing.
+        :param long_param_list:
+            Warns about too many parameters of functions.
+        :param long_yield_list:
+            Warns when a method yields a lot of arguments to the block it gets
+            passed.
+        :param module_initialize:
+            Warns about ``#initialize`` methods in modules.
+        :param nested_iterators:
+            Warns when a block contains another block.
+        :param nil_check:
+            Warns about nil checks.
+        :param prima_donna_method:
+            Warns about methods whose names end with an exclamation mark.
+        :param repeated_conditional:
+            Warns about repeated conditionals.
+        :param too_many_instance_variables:
+            Warns for too many instance variables.
+        :param too_many_methods:
+            Warns if a class has too many methods.
+        :param too_long_method:
+            Warns about huge methods.
+        :param bad_method_name:
+            Warns about method names which are not communicating the purpose
+            of the method well.
+        :param bad_module_name:
+            Warns about module names which are not communicating the purpose
+            of the module well.
+        :param bad_param_name:
+            Warns about parameter names which are not communicating the purpose
+            of the parameter well.
+        :param bad_var_name:
+            Warns about variable names which are not communicating the purpose
+            of the variable well.
+        :param allow_unused_variables:
+            Allows unused parameters though they are dead code.
+        :param check_unused_private_methods:
+            Warns about unused private methods, as they are dead code.
+        :param utility_function:
+            Allows any instance method that has no dependency on the state of
+            the instance.
+        """
+        config = {
+            "Attribute": not allow_setter_in_classes,
+            "BooleanParameter": not allow_boolean_parameter_in_functions,
+            "ClassVariable": not allow_class_variables,
+            "ControlParameter": not allow_control_parameters,
+            "DataClump": not allow_data_clump,
+            "DuplicateMethodCall": not allow_duplicate_method,
+            "FeatureEnvy": feature_envy,
+            "IrresponsibleModule": missing_module_description,
+            "LongParameterList": long_param_list,
+            "LongYieldList": long_yield_list,
+            "ModuleInitialize": module_initialize,
+            "NestedIterators": nested_iterators,
+            "NilCheck": nil_check,
+            "PrimaDonnaMethod": prima_donna_method,
+            "RepeatedConditional": repeated_conditional,
+            "TooManyInstanceVariables": too_many_instance_variables,
+            "TooManyMethods": too_many_methods,
+            "TooManyStatements": too_long_method,
+            "UncommunicativeMethodName": bad_method_name,
+            "UncommunicativeModuleName": bad_module_name,
+            "UncommunicativeParameterName": bad_param_name,
+            "UncommunicativeVariableName": bad_var_name,
+            "UnusedParameters": not allow_unused_variables,
+            "UnusedPrivateMethod": not allow_unused_private_methods,
+            "UtilityFunction": utility_function}
+
+        return ('---\n' +
+                '\n'.join('{}:\n  enabled: {}'.format(key, str(value).lower())
+                          for key, value in config.items()))
diff --git a/pool/shard001/Python/0013193_test_captchasolver.py b/pool/shard001/Python/0013193_test_captchasolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..3683d0a01d2d08f7979b1db0006fc92e117128b1
--- /dev/null
+++ b/pool/shard001/Python/0013193_test_captchasolver.py
@@ -0,0 +1,54 @@
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import os
+import unittest
+
+from future import standard_library
+from mock.mock import patch, MagicMock
+
+standard_library.install_aliases()
+
+from cloudomate.util.captchasolver import CaptchaSolver, ReCaptchaSolver
+
+
+class TestCaptchaSolver(unittest.TestCase):
+
+    def setUp(self):
+        self.captcha_solver = CaptchaSolver("213389asd8u912823")
+        self.recaptcha_solver = ReCaptchaSolver("213389asd8u912824")
+
+    def test_get_current_key(self):
+        self.assertEqual(self.captcha_solver.get_current_key(), "213389asd8u912823")
+        self.assertEqual(self.recaptcha_solver.get_current_key(), "213389asd8u912824")
+
+    @patch("time.sleep")
+    def test_solve_captcha_text_case_sensitive(self, mock_time):
+        self.captcha_solver._create_task_captcha_text_case_sensitive = MagicMock()
+        self.captcha_solver._get_task_status = MagicMock()
+        self.captcha_solver._get_task_result = MagicMock()
+
+        self.captcha_solver.solve_captcha_text_case_sensitive(
+            os.path.join(os.path.dirname(__file__), "resources/captcha.png"))
+
+        self.assertTrue(self.captcha_solver._create_task_captcha_text_case_sensitive.called)
+        self.assertTrue(self.captcha_solver._get_task_status.called)
+        self.assertTrue(self.captcha_solver._get_task_result.called)
+
+    @patch("time.sleep")
+    def test_solve_google_recaptcha(self, mock_time):
+        self.recaptcha_solver._create_task_google_recaptcha = MagicMock()
+        self.recaptcha_solver._get_task_status = MagicMock()
+        self.recaptcha_solver._get_task_result = MagicMock()
+
+        self.recaptcha_solver.solve_google_recaptcha("test1", "test2")
+
+        self.assertTrue(self.recaptcha_solver._create_task_google_recaptcha.called)
+        self.assertTrue(self.recaptcha_solver._get_task_status.called)
+        self.assertTrue(self.recaptcha_solver._get_task_result.called)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/pool/shard001/Python/0013197_petri.py b/pool/shard001/Python/0013197_petri.py
new file mode 100644
index 0000000000000000000000000000000000000000..775fcff2b7d97d1a5b6003d5ce4832050f664df0
--- /dev/null
+++ b/pool/shard001/Python/0013197_petri.py
@@ -0,0 +1,35 @@
+import pygame
+import pygame.locals
+from pygame.locals import *
+
+from engine import GameWorld
+# TEST our gameobject
+from gameobject import GameObject
+
+def petrimousedown(gameworld, event):
+    if event.button == 1:
+        # MODIFIED CODE
+        # TEST AGAIN
+        GameObject(gameworld=gameworld, pos=event.pos)
+
+    elif event.button == 3:
+        # MODIFIED CODE
+        # TEST AGAIN
+        GameObject(gameworld=gameworld, pos=event.pos)
+
+def petrikeydown(gameworld, event):
+    if event.key == K_ESCAPE:
+        print "Erasing the board."
+
+if __name__ == "__main__":
+    pygame.init()
+    pygame.display.set_caption('Petri Dish')
+
+    petri = GameWorld()
+   
+    petri.addcallback("mousedown", petrimousedown)
+    petri.addcallback("keydown", petrikeydown)
+   
+    petri.run()
+   
+    pygame.quit()
diff --git a/pool/shard001/Python/0013199_graph.py b/pool/shard001/Python/0013199_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb861ef1968bace2b2fc50df6c0cec853fc57a5d
--- /dev/null
+++ b/pool/shard001/Python/0013199_graph.py
@@ -0,0 +1,55 @@
+from pydrone.utils.direction_modifier import modifier, d
+
+
+class Graph(object):
+    def __init__(self, x, y):
+        self.graph = {}
+        self.graph[(x, y)] = (0, 1, 0)
+        self.counter = 1
+        # Set this to the same amount of Drone.fuel to make
+        # the algorithm behave like if there is no optimization
+        # If it's less, it will delete nodes when the graph becomes
+        # big, saving memory, with a variable increase of the cost
+        # of the search algorithm. 20 seemed to be a good choice for
+        # this parameter, for matrixes between 5 and 20 of size
+        # (obviously not deleting nodes is always better for calculations)
+        self.graph_max_length = 2000
+
+    def __getitem__(self, item):
+        return self.graph[item]
+
+    def sum_coord(point, mod):
+        mod = modifier(mod, 1)
+        return (point[0] + mod[0], point[1] + mod[1])
+
+    def add_node_coord(self, coord):
+        self.counter += 1
+        if len(self.graph) > self.graph_max_length:
+            for node in self.graph:
+                if self.graph[node][2] == (self.counter - self.graph_max_length):
+                    self.graph.pop(node, None)
+                    break
+        new_node = Node(coord, 1, self.counter)
+        if new_node.k not in self.graph:
+            self.graph[new_node.k] = new_node.v
+        else:
+            old_node = self.graph[coord]
+            self.graph[coord] = (old_node[0], old_node[1] + 1, self.counter)
+        return new_node.k
+
+    def change_weight(self, coord, w):
+        self.graph[coord] = (w, self.graph[coord][1], self.graph[coord][2])
+
+    def print_graph(self):
+        for node in self.graph:
+            print node, ": ", self.graph[node]
+
+    def goto(self, coord, way):
+        new_coord = self.sum_coord(coord, d[way])
+        return self.graph[new_coord] if new_coord in self.graph else -1
+
+
+class Node(object):
+    def __init__(self, k, weight, counter):
+        self.k = k
+        self.v = (weight, 1, counter)
diff --git a/pool/shard001/Python/0013200_pressreleasev1.py b/pool/shard001/Python/0013200_pressreleasev1.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f788a34f53785e67ab2ebb0697959b3ea2d827c
--- /dev/null
+++ b/pool/shard001/Python/0013200_pressreleasev1.py
@@ -0,0 +1,63 @@
+__author__ = 'Renato'
+
+from time import sleep
+from ctypes import *
+user32 = windll.user32
+from input_structures import *
+import hardware_scan_code as sc
+import virtual_key_code as vk
+
+
+def mouse_event():
+        print('Mouse Event not implemented yet...')
+
+
+def hardware_event():
+        print('Hardware event not implemented yet...')
+
+
+def keyboard_event(virtual_code, hardware_code, go_down, input_structure):
+        up_down_event = 2
+        if go_down is True:
+            up_down_event = 8
+        input_structure.ki = KeyBdInput(virtual_code, hardware_code, up_down_event, 1, None)
+
+
+def event(virtual_code, hardware_code, go_down, type_input):
+    input_structure = InputI()
+    if type_input == 0:
+        mouse_event()
+    elif type_input == 1:
+        keyboard_event(virtual_code, hardware_code, go_down, input_structure)
+    elif type_input == 3:
+        hardware_event()
+    c = FInputs((type_input, input_structure),)
+    user32.SendInput(1, pointer(c), sizeof(c[0]))
+
+
+def press(virtual_code, hardware_code):
+    event(virtual_code, hardware_code, True, 1)
+
+
+def release(virtual_code, hardware_code):
+    event(virtual_code, hardware_code, False, 1)
+
+
+def press_release(virtual_code, hardware_code, toggle_lapse):
+    press(virtual_code, hardware_code)
+    sleep(toggle_lapse)
+    release(virtual_code, hardware_code)
+
+# click_q = InputI()
+# click_q.ki = KeyBdInput(0x51, 0x10, 8, 1, None)
+# release_q = InputI()
+# release_q.ki = KeyBdInput(0x51, 0x10, 2, 1, None)
+# c_q = FInputs((1, click_q),)
+# r_q = FInputs((1, release_q),)
+# sleep(1)
+# user32.SendInput(1, pointer(c_q), sizeof(c_q[0]))
+# sleep(0.016)
+# user32.SendInput(1, pointer(r_q), sizeof(r_q[0]))
+
+sleep(3)
+press_release(vk.VK_X, sc.SC_X, 0.016)
\ No newline at end of file
diff --git a/pool/shard001/Python/0013201_MoodModel.py b/pool/shard001/Python/0013201_MoodModel.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a8183a59fb70f9dcfe23dc2187d453d83f21eb0
--- /dev/null
+++ b/pool/shard001/Python/0013201_MoodModel.py
@@ -0,0 +1,147 @@
+import numpy as np
+import time
+import os
+import matplotlib.pyplot as plt #we might do some other tool later.
+from ActionModel import ActionModel
+from BisbasModel import BisbasModel
+from UnitModel import *
+baseline_pos_expectancy=1
+baseline_neg_expectancy=1
+action_state_elicitations=10
+
+
+#for this model we're going to try build a model which has an explicit desire to seek positive feedback.
+#So we're going to make "mood" an extra Need.
+#There's no explicit Elicitor for mood, but various elicitors will elicit it to varying degrees.
+#actually, we can't do this under the current model because there's no explicit connection between state and elicitors
+#only each of their independent connections to actions.
+#Mood competes as a Internal State like everything else...
+#There's no explicit Action associated with Mood, but most actions have some effect on it.
+#Learning: positive feedback increases mood; negative feedback decreases it. Not sure how to implement this..
+
+#let's start with a model similiar to the last but with just one extra State, Mood.
+
+bb=BisbasModel(
+    states =
+    [{"name":"Hunger", "value":1},
+        {"name":"SocialNeed", "value":1},
+        {"name":"RomanticNeed","value":1},
+        {"name":"KnowledgeNeed","value":1},
+        {"name":"Mood","value":1}],
+    actions =
+    UnitModel.GetLayerOfUnits([{"name":"Eat", "value":0},
+        {"name":"Meet friends", "value":0},
+        {"name":"Approach potential partner","value":0},
+        {"name":"Study","value":0}]),
+    elicitors =
+    [{"name":"Food", "value":0},
+        {"name":"Friends", "value":0},
+        {"name":"Potential partner","value":0},
+        {"name":"Library","value":0}],
+    baseline_pos_expectancy=1,
+    baseline_neg_expectancy=1,
+    baseline_action_threshold=3,
+    learning_rate=0.05,
+    action_tendency_persistence=0.9)
+
+bb.display_current_state_text()
+#keep it simple - map each action to the corresponding state
+
+#need to set up the relationships.
+bb.state_action[range(0,4),:]=np.diag([1.0]*4)
+bb.state_action[4,:]=[0.25,0.25,0.25,0.25] #should modify this study mood to be less.
+
+#and the action_elicitor links.
+bb.state_action[range(0,4),:]=np.diag([1.0]*4)
+bb.state_action[4,:]=[0.25,0.25,0.25,0.25]
+    #how much does each action satiate the "mood" item?
+    #this really ought to depend on the amount of reward signal and we don't have a way to do that in the existing model
+    #am I going down the wrong track?
+    #not necessarily...but it's not going to entirely make sense until we make the reward signal into an associationist model
+    #can we do that now or are there other more important things to sort out first?
+
+########################################################################################################################
+
+bb.step_and_display()
+#model doesn't do anything: there's no environment elicitation. let's bring some food in.
+bb.elicitors[0].value=1.0
+bb.step()
+bb.display_current_state()
+
+#still nothing...because there's negative association with the action, it's not done.
+#I'm not sure about including this reinforcement learning...
+#anyhow, let's show the model that eating has a smaller negative than positive value.
+bb.actions[0].neg_expectancy=0.5
+bb.actions[0].neg_val=0.5
+
+#bb.actions[1].pos_expectancy=2
+#approaching a potential partner carries a high risk of rejection
+#while meeting friends carries very little negative but also lesser positive expected gain
+#partner
+bb.actions[2].pos_val=2
+bb.actions[2].pos_expectancy=2
+bb.actions[2].neg_val=1.5
+bb.actions[2].neg_expectancy=1.5
+#friend
+bb.actions[3].pos_val=0.8
+bb.actions[3].pos_expectancy=1.6
+bb.actions[3].neg_val=0.1
+bb.actions[3].neg_expectancy=0.1
+
+bb.actions[3].pos_expectancy=0.8
+bb.actions[3].neg_expectancy=0.4
+
+while bb.actions[0].value==0:
+    bb.step()
+    plt.pause(0.25)
+    bb.display_current_state()
+
+bb.step()
+bb.display_current_state()
+
+#OK. Now, we introduce a potential partner, friends, and also a study environment
+bb.elicitors[1].value=1
+bb.elicitors[2].value =1
+bb.elicitors[3].value =1
+
+
+
+
+bb.display_current_state()
+
+
+bb.step()
+bb.display_current_state()
+#next task:
+# we need to work out how to/whether to include a generalized "reward"-seeking parameter.
+# also: if studying is actually motivated by an avoidance of failure, how do we model that?
+# is that a good way to model this?
+# how would we model the interaction of BIS/BAS in here in general...because we haven't really captured
+# behavioral inhibition here, except given capacity for domain-specific inhibition.
+
+#let's say participant has one bad *really* bad experience with approaching a partner
+#reset states and environmental settings
+for i in range(0,4):
+    bb.elicitors[1].value=1
+
+#next time model approaches we're in for a shock.
+bb.actions[2].neg_val=4
+bb.display_current_state()
+
+while bb.actions[2].value==0:
+
+    bb.step()
+    bb.display_current_state()
+    plt.pause(2)
+bb.step()
+bb.display_current_state()
+bb.step()
+bb.display_current_state()
+
+
+#it doesn't matter that next time there's no negative...damage is done!
+for i in range(0,10):
+    bb.actions[2].neg_val=0
+    bb.step()
+    bb.display_current_state()
+    plt.pause(2)
\ No newline at end of file
diff --git a/pool/shard001/Python/0013210_settings_dialog.py b/pool/shard001/Python/0013210_settings_dialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..af1bd54dc88461c2e8a6d6ab1dae999886781272
--- /dev/null
+++ b/pool/shard001/Python/0013210_settings_dialog.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+"""
+GPG Sync
+Helps users have up-to-date public keys for everyone in their organization
+https://github.com/firstlookmedia/gpgsync
+Copyright (C) 2016 First Look Media
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see .
+"""
+from PySide2 import QtCore, QtWidgets, QtGui
+
+
+class SettingsDialog(QtWidgets.QDialog):
+    def __init__(self, common):
+        super(SettingsDialog, self).__init__()
+        self.c = common
+
+        self.setWindowTitle('GPG Sync Settings')
+        self.setMinimumSize(425, 200)
+        self.setMaximumSize(425, 400)
+        self.settings = self.c.settings
+
+        self.settings_layout = SettingsLayout(self.settings)
+
+        layout = QtWidgets.QVBoxLayout()
+        layout.addLayout(self.settings_layout)
+        self.setLayout(layout)
+
+class SettingsLayout(QtWidgets.QVBoxLayout):
+    def __init__(self, settings):
+        super(SettingsLayout, self).__init__()
+        self.settings = settings
+        self.c = self.settings.c
+
+        self.run_automatically_checkbox = QtWidgets.QCheckBox("Run GPG Sync automatically on login")
+        if self.settings.run_automatically:
+            self.run_automatically_checkbox.setCheckState(QtCore.Qt.Checked)
+        else:
+            self.run_automatically_checkbox.setCheckState(QtCore.Qt.Unchecked)
+
+        autostart_vlayout = QtWidgets.QVBoxLayout()
+        autostart_vlayout.addWidget(self.run_automatically_checkbox)
+        autostart_group = QtWidgets.QGroupBox("Start automatically")
+        autostart_group.setLayout(autostart_vlayout)
+
+
+        self.run_autoupdate_checkbox = QtWidgets.QCheckBox("Check for updates automatically")
+        if self.settings.run_autoupdate:
+            self.run_autoupdate_checkbox.setCheckState(QtCore.Qt.Checked)
+        else:
+            self.run_autoupdate_checkbox.setCheckState(QtCore.Qt.Unchecked)
+        # self.run_autoupdate_checkbox.stateChanged.connect(self.run_autoupdate_changed)
+
+        # Update interval
+        update_interval_hlayout = QtWidgets.QHBoxLayout()
+        update_interval_label = QtWidgets.QLabel('Time between keylist syncs (in hours)')
+        self.update_interval_edit = QtWidgets.QLineEdit()
+        self.update_interval_edit.setText(self.settings.update_interval_hours.decode())
+        update_interval_hlayout.addWidget(update_interval_label)
+        update_interval_hlayout.addWidget(self.update_interval_edit)
+
+        update_interval_group = QtWidgets.QGroupBox("Sync frequency")
+        update_interval_group.setLayout(update_interval_hlayout)
+
+        # SOCKS5 proxy settings
+        self.use_proxy = QtWidgets.QCheckBox()
+        self.use_proxy.setText("Check for updates through SOCKS5 proxy (e.g. Tor)")
+        if self.settings.automatic_update_use_proxy:
+            self.use_proxy.setCheckState(QtCore.Qt.Checked)
+        else:
+            self.use_proxy.setCheckState(QtCore.Qt.Unchecked)
+
+        proxy_host_label = QtWidgets.QLabel('Host')
+        self.proxy_host_edit = QtWidgets.QLineEdit()
+        self.proxy_host_edit.setText(self.settings.automatic_update_proxy_host.decode())
+        proxy_port_label = QtWidgets.QLabel('Port')
+        self.proxy_port_edit = QtWidgets.QLineEdit()
+        self.proxy_port_edit.setText(self.settings.automatic_update_proxy_port.decode())
+
+        proxy_hlayout = QtWidgets.QHBoxLayout()
+        proxy_hlayout.addWidget(proxy_host_label)
+        proxy_hlayout.addWidget(self.proxy_host_edit)
+        proxy_hlayout.addWidget(proxy_port_label)
+        proxy_hlayout.addWidget(self.proxy_port_edit)
+
+        proxy_vlayout = QtWidgets.QVBoxLayout()
+        proxy_vlayout.addWidget(self.run_autoupdate_checkbox)
+        proxy_vlayout.addWidget(self.use_proxy)
+        proxy_vlayout.addLayout(proxy_hlayout)
+
+        autoupdate_group = QtWidgets.QGroupBox("Automatic Updates")
+        autoupdate_group.setLayout(proxy_vlayout)
+
+        save_button = QtWidgets.QPushButton("Save Settings")
+        save_button.clicked.connect(self.save_settings)
+        button_layout = QtWidgets.QHBoxLayout()
+        button_layout.addStretch()
+        button_layout.addWidget(save_button)
+        button_layout.addStretch()
+
+        self.addWidget(autostart_group)
+        self.addWidget(update_interval_group)
+        if self.c.os != 'Linux':
+            self.addWidget(autoupdate_group)
+        self.addLayout(button_layout)
+
+    def is_number(self, input):
+        try:
+            float(input)
+            return True
+        except ValueError:
+            return False
+
+    def save_settings(self):
+        self.settings.run_automatically = (self.run_automatically_checkbox.checkState() == QtCore.Qt.Checked)
+        if self.c.os != 'Linux':
+            self.settings.run_autoupdate = (self.run_autoupdate_checkbox.checkState() == QtCore.Qt.Checked)
+            self.settings.automatic_update_use_proxy = (self.use_proxy.checkState() == QtCore.Qt.Checked)
+            self.settings.automatic_update_proxy_host = self.proxy_host_edit.text().strip().encode()
+            self.settings.automatic_update_proxy_port = self.proxy_port_edit.text().strip().encode()
+
+        # test that the input is actually a number, eventually visually show an error if not
+        if self.is_number(self.update_interval_edit.text().strip()):
+            self.settings.update_interval_hours = self.update_interval_edit.text().strip().encode()
+
+        # if save is successful, close the dialog
+        if self.settings.save():
+            self.parent().parent().close()
diff --git a/pool/shard001/Python/0013214_test_create_from_snapshot.py b/pool/shard001/Python/0013214_test_create_from_snapshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bdce3794e6c0535346eecb6e82e219499c776e8
--- /dev/null
+++ b/pool/shard001/Python/0013214_test_create_from_snapshot.py
@@ -0,0 +1,92 @@
+# Copyright 2020 NetApp, 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.
+
+"""
+Tests for the CreateFromSnapshotFilter.
+"""
+import ddt
+
+from manila.scheduler.filters import create_from_snapshot
+from manila import test
+from manila.tests.scheduler import fakes
+
+
+@ddt.ddt
+class CreateFromSnapshotFilterTestCase(test.TestCase):
+    """Test case for CreateFromSnapshotFilter."""
+
+    def setUp(self):
+        super(CreateFromSnapshotFilterTestCase, self).setUp()
+        self.filter = create_from_snapshot.CreateFromSnapshotFilter()
+
+    @staticmethod
+    def _create_request(snapshot_id=None,
+                        snapshot_host=None,
+                        replication_domain=None):
+        return {
+            'request_spec': {
+                'snapshot_id': snapshot_id,
+                'snapshot_host': snapshot_host,
+            },
+            'replication_domain': replication_domain,
+        }
+
+    @staticmethod
+    def _create_host_state(host=None, rep_domain=None):
+        return fakes.FakeHostState(host,
+                                   {
+                                       'replication_domain': rep_domain,
+                                   })
+
+    def test_without_snapshot_id(self):
+        request = self._create_request()
+        host = self._create_host_state(host='fake_host')
+
+        self.assertTrue(self.filter.host_passes(host, request))
+
+    def test_without_snapshot_host(self):
+        request = self._create_request(snapshot_id='fake_snapshot_id',
+                                       replication_domain="fake_domain")
+        host = self._create_host_state(host='fake_host',
+                                       rep_domain='fake_domain_2')
+
+        self.assertTrue(self.filter.host_passes(host, request))
+
+    @ddt.data(('host1@AAA#pool1', 'host1@AAA#pool1'),
+              ('host1@AAA#pool1', 'host1@AAA#pool2'))
+    @ddt.unpack
+    def test_same_backend(self, request_host, host_state):
+        request = self._create_request(snapshot_id='fake_snapshot_id',
+                                       snapshot_host=request_host)
+        host = self._create_host_state(host=host_state)
+
+        self.assertTrue(self.filter.host_passes(host, request))
+
+    def test_same_availability_zone(self):
+        request = self._create_request(snapshot_id='fake_snapshot_id',
+                                       snapshot_host='fake_host',
+                                       replication_domain="fake_domain")
+        host = self._create_host_state(host='fake_host_2',
+                                       rep_domain='fake_domain')
+        self.assertTrue(self.filter.host_passes(host, request))
+
+    def test_different_backend_and_availability_zone(self):
+        request = self._create_request(snapshot_id='fake_snapshot_id',
+                                       snapshot_host='fake_host',
+                                       replication_domain="fake_domain")
+        host = self._create_host_state(host='fake_host_2',
+                                       rep_domain='fake_domain_2')
+
+        self.assertFalse(self.filter.host_passes(host, request))
diff --git a/pool/shard001/Python/0013218_inj.py b/pool/shard001/Python/0013218_inj.py
new file mode 100644
index 0000000000000000000000000000000000000000..66a87c9ba1768a85ad1806815d404d2f4ecab539
--- /dev/null
+++ b/pool/shard001/Python/0013218_inj.py
@@ -0,0 +1,21 @@
+#
+# This is a small python script to inject hand-made
+# shellcodes, symbols, or array of bytes in a simple
+# way into binaries at runtime or on-disk-patching
+# in a simple way.
+#
+
+from radare import *
+
+def inject_trampoline(addr, code_addr, code):
+	seek(addr)
+	op = analyze_opcode()
+	if op['size'] != 5:
+		print "Oops: The opcode at "+addr+" is not 5 byte long"
+		return 0
+
+	# Inject our trampoline
+	r.cmd("wa jmp %s @ 0x%08x"%(code_addr, addr))
+	r.cmd("wx %s"%code)
+
+	return 1
diff --git a/pool/shard001/Python/0013219_CreateWorkspace.py b/pool/shard001/Python/0013219_CreateWorkspace.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3dda365e2e29a3ba496d2ad72ea7efbce60c39e
--- /dev/null
+++ b/pool/shard001/Python/0013219_CreateWorkspace.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+
+"""
+***************************************************************************
+    CreateWorkspace.py
+    ---------------------
+    Date                 : October 2012
+    Copyright            : (C) 2012 by Victor Olaya
+    Email                : volayaf at gmail dot com
+***************************************************************************
+*                                                                         *
+*   This program is free software; you can redistribute it and/or modify  *
+*   it under the terms of the GNU General Public License as published by  *
+*   the Free Software Foundation; either version 2 of the License, or     *
+*   (at your option) any later version.                                   *
+*                                                                         *
+***************************************************************************
+"""
+
+__author__ = 'Victor Olaya'
+__date__ = 'October 2012'
+__copyright__ = '(C) 2012, Victor Olaya'
+# This will get replaced with a git SHA1 when you do a git archive
+__revision__ = '$Format:%H$'
+
+from qgis.core import *
+from sextante.parameters.ParameterString import ParameterString
+from sextante.admintools.GeoServerToolsAlgorithm import GeoServerToolsAlgorithm
+from sextante.outputs.OutputString import OutputString
+
+class CreateWorkspace(GeoServerToolsAlgorithm):
+
+    WORKSPACE = "WORKSPACE"
+    WORKSPACEURI = "WORKSPACEURI"
+
+    def processAlgorithm(self, progress):
+        self.createCatalog()
+        workspaceName = self.getParameterValue(self.WORKSPACE)
+        workspaceUri = self.getParameterValue(self.WORKSPACEURI)
+        self.catalog.create_workspace(workspaceName, workspaceUri)
+
+
+    def defineCharacteristics(self):
+        self.addBaseParameters()
+        self.name = "Create workspace"
+        self.group = "GeoServer management tools"
+        self.addParameter(ParameterString(self.WORKSPACE, "Workspace"))
+        self.addParameter(ParameterString(self.WORKSPACEURI, "Workspace URI"))
+        self.addOutput(OutputString(self.WORKSPACE, "Workspace"))
+
+
diff --git a/pool/shard001/Python/0013221_EditorWidgetTest.py b/pool/shard001/Python/0013221_EditorWidgetTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..382062ba1272ddd4f88d03ca19fec17371704394
--- /dev/null
+++ b/pool/shard001/Python/0013221_EditorWidgetTest.py
@@ -0,0 +1,94 @@
+##########################################################################
+#
+#  Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved.
+#  Copyright (c) 2012, John Haddon. All rights reserved.
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions are
+#  met:
+#
+#      * Redistributions of source code must retain the above
+#        copyright notice, this list of conditions and the following
+#        disclaimer.
+#
+#      * Redistributions in binary form must reproduce the above
+#        copyright notice, this list of conditions and the following
+#        disclaimer in the documentation and/or other materials provided with
+#        the distribution.
+#
+#      * Neither the name of John Haddon nor the names of
+#        any other contributors to this software may be used to endorse or
+#        promote products derived from this software without specific prior
+#        written permission.
+#
+#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+##########################################################################
+
+import unittest
+import weakref
+
+import Gaffer
+import GafferTest
+import GafferUI
+import GafferUITest
+
+class EditorWidgetTest( GafferUITest.TestCase ) :
+
+	def testLifetime( self ) :
+
+		application = Gaffer.Application( "Layout tester" )
+		scriptNode = Gaffer.ScriptNode()
+		application.root()["scripts"].addChild( scriptNode )
+
+		scriptNode["write"] = Gaffer.ObjectWriter()
+		scriptNode.selection().add( scriptNode["write"] )
+
+		for type in GafferUI.EditorWidget.types() :
+			editor = GafferUI.EditorWidget.create( type, scriptNode )
+			w = weakref.ref( editor )
+			del editor
+			self.assertEqual( w(), None )
+
+		self.assertEqual( w(), None )
+
+	def testContext( self ) :
+
+		s = Gaffer.ScriptNode()
+		c = Gaffer.Context()
+
+		editor = GafferUI.Viewer( s )
+
+		self.failUnless( editor.scriptNode().isSame( s ) )
+		self.failUnless( editor.getContext().isSame( s.context() ) )
+
+		editor.setContext( c )
+		self.failUnless( editor.scriptNode().isSame( s ) )
+		self.failUnless( editor.getContext().isSame( c ) )
+
+	def testSerialisation( self ) :
+
+		application = Gaffer.Application( "Layout tester" )
+		scriptNode = Gaffer.ScriptNode()
+		application.root()["scripts"].addChild( scriptNode )
+
+		layouts = GafferUI.Layouts.acquire( application )
+		for type in GafferUI.EditorWidget.types() :
+			editor = GafferUI.EditorWidget.create( type, scriptNode )
+			layouts.add( "testLayout", editor )
+			editor2 = layouts.create( "testLayout", scriptNode )
+			self.failUnless( editor2.scriptNode() is scriptNode )
+
+if __name__ == "__main__":
+	unittest.main()
+
diff --git a/pool/shard001/Python/0013223_views.py b/pool/shard001/Python/0013223_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3490f7e7440013c043082949f8d353608e30a9d
--- /dev/null
+++ b/pool/shard001/Python/0013223_views.py
@@ -0,0 +1,165 @@
+import datetime
+import random
+from django.core.urlresolvers import reverse_lazy
+from django.shortcuts import render_to_response, render
+# from django.views.generic import ListView,DetailView
+import time
+from openstack_dashboard.dashboards.newtouch.models import ServerMonitorMessage,Server,Service
+from openstack_dashboard.dashboards.newtouch.server import tables as project_tables
+from openstack_dashboard.dashboards.newtouch.server import forms as project_forms
+
+from horizon import tables,forms
+
+
+# Create your views here.
+class ServerEditView(forms.ModalFormView):
+    template_name = 'newtouch/server/edit.html'
+    form_class = project_forms.EditServerForm
+    success_url = reverse_lazy('horizon:newtouch:server:index')
+
+    def get_initial(self):
+        server = Server.objects.get(pk=self.kwargs["pk"])
+        return {'pk': self.kwargs["pk"],
+                'snmp_commit': server.snmp_commit,
+                'snmp_version':server.snmp_version,
+                'ssh_name': server.ssh_name,
+                'ssh_key': server.ssh_key}
+
+    def get_context_data(self, **kwargs):
+        context = super(ServerEditView, self).get_context_data(**kwargs)
+        context['pk'] = self.kwargs['pk']
+        return context
+
+class ServerEditServicesView(forms.ModalFormView):
+    template_name = 'newtouch/server/edit_services.html'
+    form_class = project_forms.ServerEditServicesForm
+    success_url = reverse_lazy('horizon:newtouch:server:index')
+
+    def get_initial(self):
+        server = Server.objects.get(pk=self.kwargs["pk"])
+        return {'pk': self.kwargs["pk"],
+                'services_available':[service.name for service in server.services.all()]}
+
+    def get_context_data(self, **kwargs):
+        context = super(ServerEditServicesView, self).get_context_data(**kwargs)
+        context['pk'] = self.kwargs['pk']
+        server = Server.objects.get(pk=self.kwargs["pk"])
+        context['service_used'] = [service.name for service in server.services.all()]
+        return context
+
+class ServerDetailService(object):
+    id = None
+    name = None
+    status = None
+
+    def __init__(self, **kwargs):
+        self.id = kwargs['id']
+        self.name = kwargs['name']
+        self.status = kwargs['status']
+        self.server = kwargs['server']
+
+    def __str__(self):
+        return self.name
+
+class ServerDetailChart(object):
+    def __init__(self, **kwargs):
+        self.type = kwargs['type']
+        self.data = kwargs['data']
+        self.container = kwargs['container']
+        self.extra = kwargs['extra']
+
+    def __str__(self):
+        return self.type
+
+class ServerListView(tables.DataTableView):
+    # A very simple class-based view...
+    template_name = 'newtouch/server/index.html'
+    table_class = project_tables.ServersTable
+
+    def get_data(self):
+        # Add data to the context here...
+        server_list = Server.objects.all()
+
+        return server_list
+
+class ServerDetailView(tables.MultiTableView):
+    table_classes = (project_tables.ServerServicesTable, project_tables.ServerMessagesTable)
+    template_name = 'newtouch/server/server_detail.html'
+    failure_url = reverse_lazy('horizon:newtouch:server:index')
+
+    def get_server_services_data(self, **kwargs):
+        server_id = self.kwargs.get('pk')
+        services = []
+
+        last_server_message = ServerMonitorMessage.objects.all().filter(server=Server.objects.get(pk=server_id)).order_by("-id")[0]
+        service_status = last_server_message.process_status.lstrip("{").rstrip("}").split(',')
+
+        for service in service_status:
+            service = str(service)
+            name, sep, status = service.partition(":")
+            name = name.strip().lstrip("u").strip("'")
+            id = Service.objects.get(name=name).id
+	    status = status.strip()
+            if(status == '1'):
+                status = 'UP'
+            else:
+                status = 'DOWN'
+            services.append(ServerDetailService(id = id,server = server_id,name= name, status=status))
+
+        return services
+
+    def get_server_messages_data(self, **kwargs):
+        pk = self.kwargs.get('pk')
+        server_messages = ServerMonitorMessage.objects.all().filter(server=Server.objects.get(pk=pk)).order_by("-id")
+
+        if len(server_messages) > 20:
+            server_messages = list(server_messages)[:20]
+
+        return server_messages
+
+    # def get_queryset(self, **kwargs):
+    #     pk = self.kwargs.get('pk')
+    #     server_detail_list = super(ServerDetailView, self).get_queryset()
+    #     server_detail_list = server_detail_list.filter(server=Server.objects.get(pk=pk))
+    #
+    #     return server_detail_list
+    #
+    def get_context_data(self, **kwargs):
+        context = super(ServerDetailView, self).get_context_data(**kwargs)
+        pk = self.kwargs.get('pk')
+
+        monitor_message_list = ServerMonitorMessage.objects.all().filter(server=Server.objects.get(pk=pk))
+	monitor_message_list = list(monitor_message_list)[-24:]
+
+        tooltip_date = "%d %b %Y %H:%M:%S %p"
+        extra_serie = {
+            "tooltip": {"y_start": "There are ", "y_end": " calls"},
+            "date_format": tooltip_date,
+            # 'color': '#a4c639'
+        }
+        xdata = [int(time.mktime(message.time.timetuple()) * 1000) for message in monitor_message_list]
+        ydata = [str(message.cpu_usage) for message in monitor_message_list]
+        ydata2 = [str(message.mem_usage) for message in monitor_message_list]
+        ydata3 = [str(message.disk_usage) for message in monitor_message_list]
+
+        data = {
+            'x': xdata,
+            'name1': 'cpu', 'y1': ydata, 'extra1': extra_serie,
+            'name2': 'memory', 'y2': ydata2, 'extra2': extra_serie,
+            'name3': 'disk', 'y3': ydata3, 'extra3': extra_serie,
+        }
+
+        extra = {
+            'x_is_date': True,
+            'x_axis_format': '%b %d %H:%M:%S',
+            'tag_script_js': True,
+            'jquery_on_ready': False,
+        }
+
+        chart1 = ServerDetailChart(type="lineChart",
+                                   container="linechart_container",
+                                   data=data,
+                                   extra=extra)
+        context["chart1"] = chart1
+
+        return context
diff --git a/pool/shard001/Python/0013227_liveviewer.py b/pool/shard001/Python/0013227_liveviewer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0cc7c58968066e1d5533801d0286c2230e6ca61
--- /dev/null
+++ b/pool/shard001/Python/0013227_liveviewer.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python
+from __future__ import division
+from optparse import OptionParser
+import roslib
+import rospy
+import rosparam
+import copy
+# import cv: open cv 1 not used
+import cv2
+import numpy as np
+import threading
+import dynamic_reconfigure.server
+from cv_bridge import CvBridge, CvBridgeError
+from sensor_msgs.msg import Image
+from std_msgs.msg import Float32, Header, String
+
+from multi_tracker.msg import Contourinfo, Contourlist
+from multi_tracker.msg import Trackedobject, Trackedobjectlist
+from multi_tracker.srv import resetBackgroundService, addImageToBackgroundService
+
+import image_processing
+
+from distutils.version import LooseVersion, StrictVersion
+print 'Using open cv: ' + cv2.__version__
+if StrictVersion(cv2.__version__.split('-')[0]) >= StrictVersion("3.0.0"):
+    OPENCV_VERSION = 3
+    print 'Open CV 3'
+else:
+    OPENCV_VERSION = 2
+    print 'Open CV 2'
+
+if 0:#OPENCV_VERSION == 3:
+    raise ImportError('cv bridge not compatible with opencv 3, killing live viewer')
+
+# for basler ace cameras, use camera_aravis
+# https://github.com/ssafarik/camera_aravis
+# rosrun camera_aravis camnode
+# default image: /camera/image_raw
+
+# for firefley cameras, camera1394 does not provide timestamps but otherwise works
+# use point grey drivers
+# http://wiki.ros.org/pointgrey_camera_driver
+# rosrun pointgrey_camera_driver camera_node
+# default image: /camera/image_mono
+
+# Trajectory class to aid in drawing colored tracked trajectories with opencv
+class Trajectory(object):
+    def __init__(self, objid):
+        self.objid = objid
+        self.positions = []
+        self.color = None
+        self.covariances = []
+        self.popout = 0
+
+def draw_trajectory(img, pts, color, thickness):
+    for i in range(len(pts)-3):
+        try:
+            cv2.line(img, (int(pts[i][0]), int(pts[i][1])), (int(pts[i+1][0]), int(pts[i+1][1])), color, thickness)
+        except:
+            pass
+            print 'could not draw trajectory line, length pts: ', len(pts), 'i: ', i
+            
+# The main tracking class, a ROS node
+class LiveViewer:
+    def __init__(self, nodenum):
+        '''
+        Default image_topic for:
+            Basler ace cameras with camera_aravis driver: camera/image_raw
+            Pt Grey Firefly cameras with pt grey driver : camera/image_mono
+        '''
+        # default parameters (parameter server overides them)
+        self.params = { 'image_topic'               : '/camera/image_mono',
+                        'min_persistence_to_draw'   : 10,
+                        'max_frames_to_draw'        : 50,
+                        'camera_encoding'           : 'mono8', # fireflies are bgr8, basler gige cams are mono8
+                        'roi_l'                     : 0,
+                        'roi_r'                     : -1,
+                        'roi_b'                     : 0,
+                        'roi_t'                     : -1,
+                        'circular_mask_x'           : 'none',
+                        'circular_mask_y'           : 'none',
+                        'circular_mask_r'           : 'none',
+                        }
+        for parameter, value in self.params.items():
+            try:
+		# allows image processed view to be overlaid with tracked objects
+                p = '/multi_tracker/' + nodenum + '/liveviewer/' + parameter
+                self.params[parameter] = rospy.get_param(p)
+            except:
+                try:
+                    p = '/multi_tracker/' + nodenum + '/tracker/' + parameter
+                    self.params[parameter] = rospy.get_param(p)
+                except:
+                    print 'Using default parameter: ', parameter, ' = ', value
+                
+        # initialize the node
+        rospy.init_node('liveviewer_' + nodenum)
+        self.nodename = rospy.get_name().rstrip('/')
+        self.nodenum = nodenum
+        
+        # initialize display
+        self.window_name = 'liveviewer_' + nodenum
+        self.subTrackedObjects = rospy.Subscriber('/multi_tracker/' + nodenum + '/tracked_objects', Trackedobjectlist, self.tracked_object_callback)
+        self.subContours = rospy.Subscriber('/multi_tracker/' + nodenum + '/contours', Contourlist, self.contour_callback)
+            
+        self.cvbridge = CvBridge()
+        self.tracked_trajectories = {}
+        self.contours = None
+
+        self.window_initiated = False
+        
+        # Subscriptions - subscribe to images, and tracked objects
+        self.image_mask = None 
+        sizeImage = 128+1024*1024*3 # Size of header + data.
+        self.subImage = rospy.Subscriber(self.params['image_topic'], Image, self.image_callback, queue_size=5, buff_size=2*sizeImage, tcp_nodelay=True)
+
+        # for adding images to background
+        add_image_to_background_service_name = '/multi_tracker/' + self.nodenum + '/' + 'tracker/' + "add_image_to_background"
+        rospy.wait_for_service(add_image_to_background_service_name)
+        try:
+            self.add_image_to_background = rospy.ServiceProxy(add_image_to_background_service_name, addImageToBackgroundService)
+        except:
+            print 'could not connect to add image to background service - is tracker running?'
+
+    def reset_background(self, service_call):
+        self.reset_background_flag = True
+        return 1
+        
+    def tracked_object_callback(self, tracked_objects):
+        for trajec in self.tracked_trajectories.values():
+            trajec.popout = 1
+    
+        for tracked_object in tracked_objects.tracked_objects:
+            if tracked_object.persistence > self.params['min_persistence_to_draw']:
+                if tracked_object.objid not in self.tracked_trajectories.keys(): # create new object
+                    self.tracked_trajectories.setdefault(tracked_object.objid, Trajectory(tracked_object.objid))
+                    self.tracked_trajectories[tracked_object.objid].color = np.random.randint(0,255,3).tolist()
+                # update tracked objects
+                self.tracked_trajectories[tracked_object.objid].covariances.append(tracked_object.covariance)
+                self.tracked_trajectories[tracked_object.objid].positions.append([tracked_object.position.x, tracked_object.position.y])
+                
+                # if it is a young object, let it grow to length 100
+                if len(self.tracked_trajectories[tracked_object.objid].positions) < self.params['max_frames_to_draw']:
+                    self.tracked_trajectories[tracked_object.objid].popout = 0
+        
+        # cull old objects
+        for objid, trajec in self.tracked_trajectories.items():
+            if trajec.popout:
+                trajec.positions.pop(0)
+                trajec.covariances.pop(0)
+                if len(trajec.positions) <= 1:
+                    del(self.tracked_trajectories[objid])
+
+    def contour_callback(self, contours):
+        self.contours = contours
+
+    def image_callback(self, rosimg):
+        # Convert the image.
+        try:
+            img = self.cvbridge.imgmsg_to_cv2(rosimg, 'passthrough') # might need to change to bgr for color cameras
+        except CvBridgeError, e:
+            rospy.logwarn ('Exception converting background image from ROS to opencv:  %s' % e)
+            img = np.zeros((320,240))
+        
+        self.imgScaled = img[self.params['roi_b']:self.params['roi_t'], self.params['roi_l']:self.params['roi_r']]
+        self.shapeImage = self.imgScaled.shape # (height,width)
+        
+        if self.params['circular_mask_x'] != 'none':
+            if self.image_mask is None:
+                self.image_mask = np.zeros_like(self.imgScaled)
+                cv2.circle(self.image_mask,(self.params['circular_mask_x'], self.params['circular_mask_y']),int(self.params['circular_mask_r']),[1,1,1],-1)
+            self.imgScaled = self.image_mask*self.imgScaled
+        
+        # Image for display
+        if self.params['camera_encoding'] == 'mono8':
+            try:
+                self.imgOutput = cv2.cvtColor(self.imgScaled, cv2.COLOR_GRAY2RGB)
+            except:
+                self.imgOutput = self.imgScaled
+                print("To get rid of this error warning, set rosparam /multi_tracker/1/liveviewer/camera_encoding to something other than mono8 (e.g. color)")
+        elif self.params['camera_encoding'] == 'binary':
+            self.imgOutput = self.imgScaled
+        else:
+            self.imgOutput = self.imgScaled
+        
+        
+        # Draw ellipses from contours
+        if self.contours is not None:
+            for c, contour in enumerate(self.contours.contours):
+                # b = contour.area / (np.pi*a)
+                # b = ecc*a
+                if contour.ecc != 0: # eccentricity of ellipse < 1 but > 0
+                    a = np.sqrt( contour.area / (np.pi*contour.ecc) )
+                    b = contour.ecc*a
+                else: # eccentricity of circle is 0 
+                    a = 1
+                    b = 1
+                center = (int(contour.x), int(contour.y))
+                angle = int(contour.angle)
+                axes = (int(np.min([a,b])), int(np.max([a,b])))
+                cv2.ellipse(self.imgOutput, center, axes, angle, 0, 360, (0,255,0), 2 )
+        
+        # Display the image | Draw the tracked trajectories
+        for objid, trajec in self.tracked_trajectories.items():
+            if len(trajec.positions) > 5:
+                draw_trajectory(self.imgOutput, trajec.positions, trajec.color, 2)
+                cv2.circle(self.imgOutput,(int(trajec.positions[-1][0]),int(trajec.positions[-1][1])),int(trajec.covariances[-1]),trajec.color,2)
+        cv2.imshow(self.window_name, self.imgOutput)
+
+        if not self.window_initiated: # for some reason this approach works in opencv 3 instead of previous approach
+            cv2.setMouseCallback(self.window_name, self.on_mouse_click)
+            self.window_initiated = True
+        
+        ascii_key = cv2.waitKey(1)
+        if ascii_key != -1:
+            self.on_key_press(ascii_key)
+        
+    def on_mouse_click(self, event, x, y, flags, param):
+        if event == cv2.EVENT_LBUTTONUP:
+            print 'clicked pixel: ', [x, y]
+    
+    def on_key_press(self, ascii_key):
+        key = chr(ascii_key)
+        if key == 'a':
+            resp = self.add_image_to_background()
+            print 'added image to background'
+            
+    def Main(self):
+        while (not rospy.is_shutdown()):
+            rospy.spin()
+        cv2.destroyAllWindows()
+
+#####################################################################################################
+    
+if __name__ == '__main__':
+    parser = OptionParser()
+    parser.add_option("--nodenum", type="str", dest="nodenum", default='1',
+                        help="node number, for example, if running multiple tracker instances on one computer")
+    (options, args) = parser.parse_args()
+    
+    liveviewer = LiveViewer(options.nodenum)
+    liveviewer.Main()
diff --git a/pool/shard001/Python/0013231_testing.py b/pool/shard001/Python/0013231_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..d14ce64788e2ffab3e14016878f10a2801df3fad
--- /dev/null
+++ b/pool/shard001/Python/0013231_testing.py
@@ -0,0 +1,28 @@
+#
+# Helpers for testing
+#
+import os
+import shutil
+import tempfile
+
+
+class FakeGnuPGHomeTestCase(object):
+    """A test case that provides a fake GnuPG home.
+    """
+
+    gnupg_home = None
+
+    def create_empty_gpg_home(self):
+        self._old_gnupg_home = os.getenv('GNUPGHOME', None)
+        self.gnupg_home = tempfile.mkdtemp()
+        os.environ['GNUPGHOME'] = self.gnupg_home
+        return os.environ['GNUPGHOME']
+
+    def cleanup_gpg_home(self):
+        if self._old_gnupg_home is None:
+            del os.environ['GNUPGHOME']
+        else:
+            os.environ['GNUPGHOME'] = self._old_gnupg_home
+        if (self.gnupg_home is None) or (not os.path.isdir(self.gnupg_home)):
+            return
+        shutil.rmtree(self.gnupg_home)
diff --git a/pool/shard001/Python/0013244_conftest.py b/pool/shard001/Python/0013244_conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e11bc6c4326c3463030d207e137aeffd41d481f
--- /dev/null
+++ b/pool/shard001/Python/0013244_conftest.py
@@ -0,0 +1,30 @@
+import hashlib
+import os
+import logging
+import pytest
+
+log = logging.getLogger(__name__)
+
+
+@pytest.fixture(autouse=True)
+def log_before_after():
+    log.info('starting test')
+    yield
+    log.info('ending test')
+
+
+def pytest_collection_modifyitems(config, items):
+    n_splits = int(os.environ.get('PYTEST_SPLITS', '1'))
+    split_index = int(os.environ.get('PYTEST_SPLIT_INDEX', '-1'))
+    if n_splits <= 1:
+        return
+    if not (0 <= split_index < n_splits):
+        raise RuntimeError(f"invalid split_index: index={split_index}, n_splits={n_splits}\n  env={os.environ}")
+    skip_this = pytest.mark.skip(reason="skipped in this round")
+
+    def digest(s):
+        return int.from_bytes(hashlib.md5(str(s).encode('utf-8')).digest(), 'little')
+
+    for item in items:
+        if not digest(item.name) % n_splits == split_index:
+            item.add_marker(skip_this)
diff --git a/pool/shard001/Python/0013250_loginlogoutmodel.py b/pool/shard001/Python/0013250_loginlogoutmodel.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1ab1f6aabd15df0089fc7c0c8e8d6c5d251b892
--- /dev/null
+++ b/pool/shard001/Python/0013250_loginlogoutmodel.py
@@ -0,0 +1,22 @@
+from golem.monitorconfig import MONITOR_CONFIG
+from golem.network.p2p.peersession import P2P_PROTOCOL_ID
+from golem.task.tasksession import TASK_PROTOCOL_ID
+
+from modelbase import BasicModel
+
+class LoginLogoutBaseModel(BasicModel):
+    def __init__(self, metadata):
+        super(LoginLogoutBaseModel, self).__init__(self.TYPE, metadata.cliid, metadata.sessid)
+        self.metadata = metadata.dict_repr()
+        self.protocol_versions = {
+            'monitor': MONITOR_CONFIG['PROTO_VERSION'],
+            'p2p': P2P_PROTOCOL_ID,
+            'task': TASK_PROTOCOL_ID,
+        }
+
+class LoginModel(LoginLogoutBaseModel):
+    TYPE = "Login"
+
+
+class LogoutModel(LoginLogoutBaseModel):
+    TYPE = "Logout"
diff --git a/pool/shard001/Python/0013253_util.py b/pool/shard001/Python/0013253_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..afb379d8e90057784b0261e790b4e985265835d5
--- /dev/null
+++ b/pool/shard001/Python/0013253_util.py
@@ -0,0 +1,28 @@
+"""Test utilities."""
+
+import pickle
+
+import ibis
+import ibis.util as util
+
+
+def assert_equal(left, right):
+    """Assert that two ibis objects are equal."""
+
+    if util.all_of([left, right], ibis.Schema):
+        assert left.equals(right), 'Comparing schemas: \n{!r} !=\n{!r}'.format(
+            left, right
+        )
+    else:
+        assert left.equals(right), 'Objects unequal: {}\nvs\n{}'.format(
+            repr(left), repr(right)
+        )
+
+
+def assert_pickle_roundtrip(obj):
+    """Assert that an ibis object remains the
+    same after pickling and unpickling."""
+
+    raw = pickle.dumps(obj)
+    loaded = pickle.loads(raw)
+    assert obj.equals(loaded)
diff --git a/pool/shard001/Python/0013255_fish.py b/pool/shard001/Python/0013255_fish.py
new file mode 100644
index 0000000000000000000000000000000000000000..6711595e99534065614a6d01dd1c418829f8e1f6
--- /dev/null
+++ b/pool/shard001/Python/0013255_fish.py
@@ -0,0 +1,172 @@
+# Copyright 2017 The dm_control Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ============================================================================
+
+"""Fish Domain."""
+
+import collections
+
+from dm_control import mujoco
+from dm_control.rl import control
+from dm_control.suite import base
+from dm_control.suite import common
+from dm_control.utils import containers
+from dm_control.utils import rewards
+import numpy as np
+
+
+_DEFAULT_TIME_LIMIT = 40
+_CONTROL_TIMESTEP = .04
+_JOINTS = ['tail1',
+           'tail_twist',
+           'tail2',
+           'finright_roll',
+           'finright_pitch',
+           'finleft_roll',
+           'finleft_pitch']
+SUITE = containers.TaggedTasks()
+
+
+def get_model_and_assets():
+  """Returns a tuple containing the model XML string and a dict of assets."""
+  return common.read_model('fish.xml'), common.ASSETS
+
+
+@SUITE.add('benchmarking')
+def upright(time_limit=_DEFAULT_TIME_LIMIT, random=None,
+            environment_kwargs=None):
+  """Returns the Fish Upright task."""
+  physics = Physics.from_xml_string(*get_model_and_assets())
+  task = Upright(random=random)
+  environment_kwargs = environment_kwargs or {}
+  return control.Environment(
+      physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit,
+      **environment_kwargs)
+
+
+@SUITE.add('benchmarking')
+def swim(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
+  """Returns the Fish Swim task."""
+  physics = Physics.from_xml_string(*get_model_and_assets())
+  task = Swim(random=random)
+  environment_kwargs = environment_kwargs or {}
+  return control.Environment(
+      physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit,
+      **environment_kwargs)
+
+
+class Physics(mujoco.Physics):
+  """Physics simulation with additional features for the Fish domain."""
+
+  def upright(self):
+    """Returns projection from z-axes of torso to the z-axes of worldbody."""
+    return self.named.data.xmat['torso', 'zz']
+
+  def torso_velocity(self):
+    """Returns velocities and angular velocities of the torso."""
+    return self.data.sensordata
+
+  def joint_velocities(self):
+    """Returns the joint velocities."""
+    return self.named.data.qvel[_JOINTS]
+
+  def joint_angles(self):
+    """Returns the joint positions."""
+    return self.named.data.qpos[_JOINTS]
+
+  def mouth_to_target(self):
+    """Returns a vector, from mouth to target in local coordinate of mouth."""
+    data = self.named.data
+    mouth_to_target_global = data.geom_xpos['target'] - data.geom_xpos['mouth']
+    return mouth_to_target_global.dot(data.geom_xmat['mouth'].reshape(3, 3))
+
+
+class Upright(base.Task):
+  """A Fish `Task` for getting the torso upright with smooth reward."""
+
+  def __init__(self, random=None):
+    """Initializes an instance of `Upright`.
+
+    Args:
+      random: Either an existing `numpy.random.RandomState` instance, an
+        integer seed for creating a new `RandomState`, or None to select a seed
+        automatically.
+    """
+    super().__init__(random=random)
+
+  def initialize_episode(self, physics):
+    """Randomizes the tail and fin angles and the orientation of the Fish."""
+    quat = self.random.randn(4)
+    physics.named.data.qpos['root'][3:7] = quat / np.linalg.norm(quat)
+    for joint in _JOINTS:
+      physics.named.data.qpos[joint] = self.random.uniform(-.2, .2)
+    # Hide the target. It's irrelevant for this task.
+    physics.named.model.geom_rgba['target', 3] = 0
+    super().initialize_episode(physics)
+
+  def get_observation(self, physics):
+    """Returns an observation of joint angles, velocities and uprightness."""
+    obs = collections.OrderedDict()
+    obs['joint_angles'] = physics.joint_angles()
+    obs['upright'] = physics.upright()
+    obs['velocity'] = physics.velocity()
+    return obs
+
+  def get_reward(self, physics):
+    """Returns a smooth reward."""
+    return rewards.tolerance(physics.upright(), bounds=(1, 1), margin=1)
+
+
+class Swim(base.Task):
+  """A Fish `Task` for swimming with smooth reward."""
+
+  def __init__(self, random=None):
+    """Initializes an instance of `Swim`.
+
+    Args:
+      random: Optional, either a `numpy.random.RandomState` instance, an
+        integer seed for creating a new `RandomState`, or None to select a seed
+        automatically (default).
+    """
+    super().__init__(random=random)
+
+  def initialize_episode(self, physics):
+    """Sets the state of the environment at the start of each episode."""
+
+    quat = self.random.randn(4)
+    physics.named.data.qpos['root'][3:7] = quat / np.linalg.norm(quat)
+    for joint in _JOINTS:
+      physics.named.data.qpos[joint] = self.random.uniform(-.2, .2)
+    # Randomize target position.
+    physics.named.model.geom_pos['target', 'x'] = self.random.uniform(-.4, .4)
+    physics.named.model.geom_pos['target', 'y'] = self.random.uniform(-.4, .4)
+    physics.named.model.geom_pos['target', 'z'] = self.random.uniform(.1, .3)
+    super().initialize_episode(physics)
+
+  def get_observation(self, physics):
+    """Returns an observation of joints, target direction and velocities."""
+    obs = collections.OrderedDict()
+    obs['joint_angles'] = physics.joint_angles()
+    obs['upright'] = physics.upright()
+    obs['target'] = physics.mouth_to_target()
+    obs['velocity'] = physics.velocity()
+    return obs
+
+  def get_reward(self, physics):
+    """Returns a smooth reward."""
+    radii = physics.named.model.geom_size[['mouth', 'target'], 0].sum()
+    in_target = rewards.tolerance(np.linalg.norm(physics.mouth_to_target()),
+                                  bounds=(0, radii), margin=2*radii)
+    is_upright = 0.5 * (physics.upright() + 1)
+    return (7*in_target + is_upright) / 8
diff --git a/pool/shard001/Python/0013260_test_vestiging_filter_api.py b/pool/shard001/Python/0013260_test_vestiging_filter_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..f04ac71fd92b7e269142ae918145dc034e432a98
--- /dev/null
+++ b/pool/shard001/Python/0013260_test_vestiging_filter_api.py
@@ -0,0 +1,162 @@
+
+import logging
+
+# django
+from rest_framework.test import APITestCase
+
+# Project
+from datasets.hr.tests import factories as factories_hr
+from datasets.hr import models as models_hr
+from .fixtures import patch_filter_requests
+from . import authorization
+
+LOG = logging.getLogger(__name__)
+
+
+@patch_filter_requests
+class VestingFilterTest(APITestCase, authorization.AuthorizationSetup):
+
+    # create some factory stuff
+
+    @classmethod
+    def setUpClass(cls):
+        super().setUpClass()
+        cls.vestigingen = factories_hr.create_x_vestigingen()
+
+    @classmethod
+    def tearDownClass(cls):
+        super().tearDownClass()
+
+    def setUp(self):
+        """
+        For x bag panden
+        """
+        self.setUpAuthorization()
+        # factories_hr.restore_cbs_sbi()
+
+    def test_simple_response(self):
+        """
+        Verify that the endpoint exists.
+        """
+        test_id = self.vestigingen[0].vestigingsnummer
+
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response = self.client.get(
+            '/handelsregister/vestiging/{}/'.format(test_id))
+
+        self.assertEquals(200, response.status_code)
+
+    def test_filter_nummeraanduiding(self):
+        vestigingen = models_hr.Vestiging.objects.filter(
+           bezoekadres__bag_numid=0,
+        )
+        vestigingen_p = models_hr.Vestiging.objects.filter(
+           postadres__bag_numid='p0',
+        )
+
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response_b = self.client.get(
+            '/handelsregister/vestiging/?nummeraanduiding=0')
+
+        data_b = response_b.json()
+        self.assertEquals(200, response_b.status_code)
+        self.assertEquals(vestigingen.count(), data_b['count'])
+
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response_p = self.client.get(
+            '/handelsregister/vestiging/?nummeraanduiding=p0')
+
+        data_p = response_p.json()
+
+        self.assertEquals(200, response_p.status_code)
+        self.assertEquals(vestigingen_p.count(), data_p['count'])
+
+    def test_filter_vbo_id(self):
+
+        vestigingen = models_hr.Vestiging.objects.filter(
+           bezoekadres__bag_vbid=5,
+        )
+
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+
+        response = self.client.get(
+            '/handelsregister/vestiging/?verblijfsobject=5')
+
+        data = response.json()
+        self.assertEquals(200, response.status_code)
+
+        self.assertEquals(vestigingen.count(), data['count'])
+
+    def test_filter_pand_id(self):
+        """
+        We mock the bag api endpoint request with json fixtures
+        """
+
+        # json contains verblijsfsobjecten with id 4 for given
+        # pand id
+        vestigingen = models_hr.Vestiging.objects.filter(
+           bezoekadres__bag_numid=4,
+        )
+
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response = self.client.get(
+            '/handelsregister/vestiging/?pand=0363010000758545')
+
+        self.assertEquals(200, response.status_code)
+        data = response.json()
+
+        self.assertEquals(vestigingen.count(), data['count'])
+
+    def test_filter_kot_id(self):
+        """
+        We created some vbo's in setup using fixtures
+        The vbo's we can now find/filter in the fixtures
+        A reqest for vbo's id's is done to kot api in the filter.
+        The returend id's should be found
+        """
+        # vestigingen filter which should be in fixture response
+        # of kot. minimal 3 max 30
+        vestigingen = models_hr.Vestiging.objects.filter(
+           bezoekadres__bag_numid__in=[1, 2, 'p1']
+        )
+
+        # minimal 1 max 10
+        vestigingen_to_few = models_hr.Vestiging.objects.filter(
+           bezoekadres__bag_numid__in=['p1']
+        )
+
+        # Trigger a filter request with kot object id
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response = self.client.get(
+            '/handelsregister/vestiging/?kadastraal_object=NL.KAD.OnroerendeZaak.11450749270000')
+
+        self.assertEquals(200, response.status_code)
+
+        data = response.json()
+
+        # We should be able to find all vestigingen
+        # using 1, 2 and p1 location
+        self.assertEquals(vestigingen.count(), data['count'])
+        self.assertNotEqual(vestigingen_to_few.count(), data['count'])
+
+    def test_unknown_vbo_is_200(self):
+        """
+        """
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response = self.client.get(
+            '/handelsregister/vestiging/?verblijfsobject=9999')
+
+        self.assertEquals(200, response.status_code)
+
+    def test_dataselectie_filter(self):
+        self.client.credentials(
+            HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr_r))
+        response = self.client.get(
+            '/handelsregister/dataselectie/?sbi_code=1073')
diff --git a/pool/shard001/Python/0013265_tests.py b/pool/shard001/Python/0013265_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..e97a7def3b23a3a4dd2e30eca91720f751ba8ca7
--- /dev/null
+++ b/pool/shard001/Python/0013265_tests.py
@@ -0,0 +1,91 @@
+# Quick tests for the markup templatetags (django.contrib.markup)
+import re
+
+from django.template import Template, Context, add_to_builtins
+from django.utils import unittest
+from django.utils.html import escape
+
+add_to_builtins('django.contrib.markup.templatetags.markup')
+
+try:
+    import textile
+except ImportError:
+    textile = None
+
+try:
+    import markdown
+except ImportError:
+    markdown = None
+
+try:
+    import docutils
+except ImportError:
+    docutils = None
+
+class Templates(unittest.TestCase):
+
+    textile_content = """Paragraph 1
+
+Paragraph 2 with "quotes" and @code@"""
+
+    markdown_content = """Paragraph 1
+
+## An h2"""
+
+    rest_content = """Paragraph 1
+
+Paragraph 2 with a link_
+
+.. _link: http://www.example.com/"""
+
+
+    @unittest.skipUnless(textile, 'texttile not installed')
+    def test_textile(self):
+        t = Template("{{ textile_content|textile }}")
+        rendered = t.render(Context({'textile_content':self.textile_content})).strip()
+        self.assertEqual(rendered.replace('\t', ''), """

Paragraph 1

+ +

Paragraph 2 with “quotes” and code

""") + + @unittest.skipIf(textile, 'texttile is installed') + def test_no_textile(self): + t = Template("{{ textile_content|textile }}") + rendered = t.render(Context({'textile_content':self.textile_content})).strip() + self.assertEqual(rendered, escape(self.textile_content)) + + @unittest.skipUnless(markdown, 'markdown not installed') + def test_markdown(self): + t = Template("{{ markdown_content|markdown }}") + rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() + pattern = re.compile("""

Paragraph 1\s*

\s*

\s*An h2

""") + self.assertTrue(pattern.match(rendered)) + + @unittest.skipIf(markdown, 'markdown is installed') + def test_no_markdown(self): + t = Template("{{ markdown_content|markdown }}") + rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() + self.assertEqual(rendered, self.markdown_content) + + @unittest.skipUnless(docutils, 'docutils not installed') + def test_docutils(self): + t = Template("{{ rest_content|restructuredtext }}") + rendered = t.render(Context({'rest_content':self.rest_content})).strip() + # Different versions of docutils return slightly different HTML + try: + # Docutils v0.4 and earlier + self.assertEqual(rendered, """

Paragraph 1

+

Paragraph 2 with a link

""") + except AssertionError, e: + # Docutils from SVN (which will become 0.5) + self.assertEqual(rendered, """

Paragraph 1

+

Paragraph 2 with a link

""") + + @unittest.skipIf(docutils, 'docutils is installed') + def test_no_docutils(self): + t = Template("{{ rest_content|restructuredtext }}") + rendered = t.render(Context({'rest_content':self.rest_content})).strip() + self.assertEqual(rendered, self.rest_content) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0013271_diff_tile_metadata_yaml.py b/pool/shard001/Python/0013271_diff_tile_metadata_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..10be4294076d290552b70f1276b0a53fe038f8e6 --- /dev/null +++ b/pool/shard001/Python/0013271_diff_tile_metadata_yaml.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python + +import dictdiffer +import sys +import yaml + + +if len(sys.argv) != 3: + print(('Usage: %s FILE_A FILE_B\nSort tile metadata yaml files and compare FILE_A to FILE_B.' % sys.argv[0].split('/')[-1])) + sys.exit(1) + +with open(sys.argv[1], 'r') as f: + a = f.read() +with open(sys.argv[2], 'r') as f: + b = f.read() + +aa = yaml.load(a) +bb = yaml.load(b) + +for conf in [aa, bb]: + for release in conf['releases']: + if release.get('name') == 'test-tile': + release.pop('version') + release.pop('file') + conf.pop('product_version') + conf.pop('provides_product_versions') + conf['property_blueprints'] = sorted(conf['property_blueprints'], key=lambda k: k['name']) + conf['job_types'] = sorted(conf['job_types'], key=lambda k: k['name']) + for x in conf['job_types']: x['manifest'] = sorted(x['manifest'].items()) if type(x['manifest']) is dict else sorted(yaml.load(x['manifest']).items()) + +from pprint import pprint +for x in list(dictdiffer.diff(aa,bb)): pprint(x); print('') + diff --git a/pool/shard001/Python/0013286_custom_tags.py b/pool/shard001/Python/0013286_custom_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..8e06ec9652f95999191a1d7e821989499fb01148 --- /dev/null +++ b/pool/shard001/Python/0013286_custom_tags.py @@ -0,0 +1,95 @@ +from __future__ import print_function, unicode_literals, with_statement, division + +from django import template +from django.forms import widgets +from django.template.loader import get_template + +register = template.Library() + + +class FormFieldNode(template.Node): + """ + Helper class for the render_form_field below + """ + def __init__(self, form_field, help_text=None, css_classes=None): + self.form_field = template.Variable(form_field) + self.help_text = help_text[1:-1] if help_text else help_text + self.css_classes = css_classes[1:-1] if css_classes else css_classes + + def render(self, context): + + try: + form_field = self.form_field.resolve(context) + except template.VariableDoesNotExist: + return '' + + widget = form_field.field.widget + + if isinstance(widget, widgets.HiddenInput): + return form_field + elif isinstance(widget, widgets.RadioSelect): + t = get_template('common/fragments/radio_field.html') + elif isinstance(widget, widgets.CheckboxInput): + t = get_template('common/fragments/checkbox_field.html') + elif isinstance(widget, widgets.CheckboxSelectMultiple): + t = get_template('common/fragments/multi_checkbox_field.html') + else: + t = get_template('common/fragments/form_field.html') + + help_text = self.help_text + if help_text is None: + help_text = form_field.help_text + + return t.render({ + 'form_field': form_field, + 'help_text': help_text, + 'css_classes': self.css_classes + }) + + +@register.tag +def render_form_field(parser, token): + """ + Usage is {% render_form_field form.field_name optional_help_text optional_css_classes %} + + - optional_help_text and optional_css_classes are strings + - if optional_help_text is not given, then it is taken from form field object + """ + try: + help_text = None + css_classes = None + + token_split = token.split_contents() + if len(token_split) == 4: + tag_name, form_field, help_text, css_classes = token.split_contents() + elif len(token_split) == 3: + tag_name, form_field, help_text = token.split_contents() + else: + tag_name, form_field = token.split_contents() + except ValueError: + raise template.TemplateSyntaxError( + "Unable to parse arguments for {0}".format(repr(token.contents.split()[0]))) + + return FormFieldNode(form_field, help_text=help_text, css_classes=css_classes) + + +@register.simple_tag +def active(request, pattern): + """ + Returns the string 'active' if pattern matches. + Used to assign a css class in navigation bars to active tab/section. + """ + if request.path == pattern: + return 'active' + return '' + + +@register.simple_tag +def active_starts(request, pattern): + """ + Returns the string 'active' if request url starts with pattern. + Used to assign a css class in navigation bars to active tab/section. + """ + if request.path.startswith(pattern): + return 'active' + return '' diff --git a/pool/shard001/Python/0013288_factories.py b/pool/shard001/Python/0013288_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd00d2bb7cc3095f172428b17daa2013e3b88ee --- /dev/null +++ b/pool/shard001/Python/0013288_factories.py @@ -0,0 +1,110 @@ +"""Factories for generating fake catalog data.""" +# pylint: disable=missing-docstring, invalid-name +from random import randint + +import factory +from faker import Faker + + +fake = Faker() + + +def generate_course_key(): + return '+'.join(fake.words(2)) + + +def generate_course_run_key(): + return 'course-v1:' + '+'.join(fake.words(3)) + + +def generate_zulu_datetime(): + """ + The catalog returns UTC datetimes formatted using Z, the zone designator + for the zero UTC offset, not the +00:00 offset. For more, see + https://en.wikipedia.org/wiki/ISO_8601#UTC. + """ + return fake.date_time().isoformat() + 'Z' + + +class DictFactory(factory.Factory): + class Meta(object): + model = dict + + +class ImageFactory(DictFactory): + height = factory.Faker('random_int') + width = factory.Faker('random_int') + + +class Image(ImageFactory): + """ + For constructing dicts mirroring the catalog's serialized representation of ImageFields. + + See https://github.com/edx/course-discovery/blob/master/course_discovery/apps/api/fields.py. + """ + description = factory.Faker('sentence') + src = factory.Faker('image_url') + + +class StdImage(ImageFactory): + """ + For constructing dicts mirroring the catalog's serialized representation of StdImageFields. + + See https://github.com/edx/course-discovery/blob/master/course_discovery/apps/api/fields.py. + """ + url = factory.Faker('image_url') + + +def generate_sized_stdimage(): + return { + size: StdImage() for size in ['large', 'medium', 'small', 'x-small'] + } + + +class Organization(DictFactory): + key = factory.Faker('word') + name = factory.Faker('company') + uuid = factory.Faker('uuid4') + + +class CourseRun(DictFactory): + end = factory.LazyFunction(generate_zulu_datetime) + enrollment_end = factory.LazyFunction(generate_zulu_datetime) + enrollment_start = factory.LazyFunction(generate_zulu_datetime) + image = Image() + key = factory.LazyFunction(generate_course_run_key) + marketing_url = factory.Faker('url') + pacing_type = 'self_paced' + short_description = factory.Faker('sentence') + start = factory.LazyFunction(generate_zulu_datetime) + title = factory.Faker('catch_phrase') + type = 'verified' + uuid = factory.Faker('uuid4') + + +class Course(DictFactory): + course_runs = [CourseRun() for __ in range(randint(3, 5))] + image = Image() + key = factory.LazyFunction(generate_course_key) + owners = [Organization()] + title = factory.Faker('catch_phrase') + uuid = factory.Faker('uuid4') + + +class Program(DictFactory): + authoring_organizations = [Organization()] + banner_image = factory.LazyFunction(generate_sized_stdimage) + card_image_url = factory.Faker('image_url') + courses = [Course() for __ in range(randint(3, 5))] + marketing_slug = factory.Faker('slug') + marketing_url = factory.Faker('url') + status = 'active' + subtitle = factory.Faker('sentence') + title = factory.Faker('catch_phrase') + type = factory.Faker('word') + uuid = factory.Faker('uuid4') + + +class ProgramType(DictFactory): + name = factory.Faker('word') + logo_image = factory.LazyFunction(generate_sized_stdimage) diff --git a/pool/shard001/Python/0013292_test_lockfile.py b/pool/shard001/Python/0013292_test_lockfile.py new file mode 100644 index 0000000000000000000000000000000000000000..852c23611295fc70c36a087721b43822e3c550a6 --- /dev/null +++ b/pool/shard001/Python/0013292_test_lockfile.py @@ -0,0 +1,75 @@ +import time +import os + +from django.test import TestCase + +from ..lockfile import FileLock, FileLocked + + +def setup_fake_lock(lock_file_name): + pid = os.getpid() + lockfile = '%s.lock' % pid + try: + os.remove(lock_file_name) + except OSError: + pass + os.symlink(lockfile, lock_file_name) + + +class LockTest(TestCase): + + def test_process_killed_force_unlock(self): + pid = os.getpid() + lockfile = '%s.lock' % pid + setup_fake_lock('test.lock') + + with open(lockfile, 'w+') as f: + f.write('9999999') + assert os.path.exists(lockfile) + with FileLock('test'): + assert True + + def test_force_unlock_in_same_process(self): + pid = os.getpid() + lockfile = '%s.lock' % pid + os.symlink(lockfile, 'test.lock') + + with open(lockfile, 'w+') as f: + f.write(str(os.getpid())) + + with FileLock('test', force=True): + assert True + + def test_exception_after_timeout(self): + pid = os.getpid() + lockfile = '%s.lock' % pid + setup_fake_lock('test.lock') + + with open(lockfile, 'w+') as f: + f.write(str(os.getpid())) + + try: + with FileLock('test', timeout=1): + assert False + except FileLocked: + assert True + + def test_force_after_timeout(self): + pid = os.getpid() + lockfile = '%s.lock' % pid + setup_fake_lock('test.lock') + + with open(lockfile, 'w+') as f: + f.write(str(os.getpid())) + + timeout = 1 + start = time.time() + with FileLock('test', timeout=timeout, force=True): + assert True + end = time.time() + assert end - start > timeout + + def test_get_lock_pid(self): + """Ensure get_lock_pid() works properly""" + with FileLock('test', timeout=1, force=True) as lock: + self.assertEqual(lock.get_lock_pid(), int(os.getpid())) diff --git a/pool/shard001/Python/0013307_Hexaco.py b/pool/shard001/Python/0013307_Hexaco.py new file mode 100644 index 0000000000000000000000000000000000000000..68a41eddfe2b839fe5aac0cb3b78f810c63fecb3 --- /dev/null +++ b/pool/shard001/Python/0013307_Hexaco.py @@ -0,0 +1,66 @@ +""" + + This file is part of HexACO. + + HexACO is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + HexACO is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with HexACO. If not, see . + +######################################################################## + + Main Hexaco + +######################################################################## + +Description +----------- +Creates all software components and manages the main game loop """ + +from Engine import GraphicsEngine +from Engine import GameEngine +from Engine.GameSettings import TURNS + +try: + from Tkinter import * +except ImportError: + from tkinter import * + +from time import sleep + +ROOT = Tk() + +# Create the engines +GAME_ENGINE = GameEngine() +GRAPHICS_ENGINE = GraphicsEngine(master=ROOT) + +# Set all constants +GRAPHICS_ENGINE.set_hex_radius() + +# Alert other engines when a new game_object is added +GAME_ENGINE.callback_for_new_object(GRAPHICS_ENGINE.add_component) + +# Initialize all engines +GAME_ENGINE.initialize() + +i = TURNS or -1 + +print ("Starting main game loop") + +while i is not 0: + + i -= 1 + GRAPHICS_ENGINE.set_turn_text(i) + + GAME_ENGINE.update() + + GRAPHICS_ENGINE.updateScreen() + sleep(0.) diff --git a/pool/shard001/Python/0013311_afp.py b/pool/shard001/Python/0013311_afp.py new file mode 100644 index 0000000000000000000000000000000000000000..6648f0ac9e4562b7821e58c8e9bd83ac97709b43 --- /dev/null +++ b/pool/shard001/Python/0013311_afp.py @@ -0,0 +1,53 @@ +#!/usr/local/bin/python + +import requests +import json +import sys +sys.path.append('../conn/') +import conn + +#vol_name = raw_input('Input volume name:') +url = conn.url + 'sharing/afp/' +auth = conn.auth +headers = conn.headers +payload = { + "afp_name": "My Test Share", + "afp_path": "/mnt/tank0" +} + +def afp_get(): + r = requests.get(url, auth = auth) + result = json.loads(r.text) + i = 0 + for i in range(0,len(result)): + for items in result[i]: + print items+':', result[i][items] + +def afp_post(): + r = requests.post(url, auth = auth, data = json.dumps(payload), headers = headers) + result = json.loads(r.text) + for items in result: + print items+':', result[items] + +def afp_put(): + id = raw_input('Input id:')+'/' + r = requests.put(url+id, auth = auth, data = json.dumps(payload), headers = headers) + result = json.loads(r.text) + for items in result: + print items+':', result[items] + +def afp_delete(): + id = raw_input('Input id:')+'/' + r = requests.delete(url+id, auth = auth) + print r.status_code + +while (1): + method = raw_input('Input method:') + if method == 'get': + afp_get() + elif method == 'post': + afp_post() + elif method == 'delete': + afp_delete() + elif method == 'put': + afp_put() diff --git a/pool/shard001/Python/0013312_test_spaces.py b/pool/shard001/Python/0013312_test_spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..59632007825783419a4e8c2f2de30700d6dafbfe --- /dev/null +++ b/pool/shard001/Python/0013312_test_spaces.py @@ -0,0 +1,124 @@ +import unittest +from http import HTTPStatus +from unittest.mock import call + +from abstract_test_case import AbstractTestCase +from cloudfoundry_client.v3.entities import Entity, ToOneRelationship + + +class TestSpaces(unittest.TestCase, AbstractTestCase): + @classmethod + def setUpClass(cls): + cls.mock_client_class() + + def setUp(self): + self.build_client() + + def test_create(self): + self.client.post.return_value = self.mock_response( + "/v3/spaces", HTTPStatus.OK, None, "v3", "spaces", "POST_response.json" + ) + result = self.client.v3.spaces.create("space-name", "organization-guid") + self.client.post.assert_called_with( + self.client.post.return_value.url, + files=None, + json={"name": "space-name", "relationships": {"organization": {"data": {"guid": "organization-guid"}}}}, + ) + self.assertIsNotNone(result) + self.assertIsInstance(result, Entity) + + def test_list(self): + self.client.get.return_value = self.mock_response( + "/v3/spaces", HTTPStatus.OK, None, "v3", "spaces", "GET_response.json" + ) + all_spaces = [space for space in self.client.v3.spaces.list()] + self.client.get.assert_called_with(self.client.get.return_value.url) + self.assertEqual(2, len(all_spaces)) + self.assertEqual(all_spaces[0]["name"], "space1") + self.assertIsInstance(all_spaces[0], Entity) + + def test_get(self): + self.client.get.return_value = self.mock_response( + "/v3/spaces/space_id", HTTPStatus.OK, None, "v3", "spaces", "GET_{id}_response.json" + ) + space = self.client.v3.spaces.get("space_id") + self.client.get.assert_called_with(self.client.get.return_value.url) + self.assertEqual("my-space", space["name"]) + self.assertIsInstance(space, Entity) + + def test_get_then_organization(self): + get_space = self.mock_response( + "/v3/spaces/space_id", HTTPStatus.OK, None, "v3", "spaces", "GET_{id}_response.json" + ) + get_organization = self.mock_response( + "/v3/organizations/e00705b9-7b42-4561-ae97-2520399d2133", + HTTPStatus.OK, + None, + "v3", + "organizations", + "GET_{id}_response.json", + ) + self.client.get.side_effect = [get_space, get_organization] + organization = self.client.v3.spaces.get("space_id").organization() + self.client.get.assert_has_calls([call(get_space.url), call(get_organization.url)], any_order=False) + self.assertEqual("my-organization", organization["name"]) + + def test_get_assigned_isolation_segment(self): + self.client.get.return_value = self.mock_response( + "/v3/spaces/space_id/relationships/isolation_segment", + HTTPStatus.OK, + None, + "v3", + "spaces", + "GET_{id}_relationships_isolation_segment_response.json", + ) + + result = self.client.v3.spaces.get_assigned_isolation_segment("space_id") + + self.assertIsInstance(result, ToOneRelationship) + self.assertEqual("e4c91047-3b29-4fda-b7f9-04033e5a9c9f", result.guid) + + def test_assign_isolation_segment(self): + self.client.patch.return_value = self.mock_response( + "/v3/spaces/space_id/relationships/isolation_segment", + HTTPStatus.OK, + None, + "v3", + "spaces", + "POST_{id}_relationships_isolation_segment_response.json", + ) + result = self.client.v3.spaces.assign_isolation_segment("space_id", "iso-seg-guid") + self.client.patch.assert_called_with(self.client.patch.return_value.url, json={"data": {"guid": "iso-seg-guid"}}) + self.assertIsInstance(result, ToOneRelationship) + self.assertEqual("iso-seg-guid", result.guid) + + def test_remove(self): + self.client.delete.return_value = self.mock_response("/v3/spaces/space_id", HTTPStatus.NO_CONTENT, None) + self.client.v3.spaces.remove("space_id") + self.client.delete.assert_called_with(self.client.delete.return_value.url) + + def test_get_include_organization(self): + self.client.get.return_value = self.mock_response( + "/v3/spaces/space_id?include=organization", + HTTPStatus.OK, + None, + "v3", + "spaces", + "GET_{id}_response_include_org.json" + ) + org = self.client.v3.spaces.get("space_id", include="organization").organization() + self.client.get.assert_called_with(self.client.get.return_value.url) + self.assertEqual("my-organization", org["name"]) + self.assertIsInstance(org, Entity) + + def test_list_include_organization(self): + self.client.get.return_value = self.mock_response( + "/v3/spaces?include=organization", HTTPStatus.OK, None, "v3", "spaces", "GET_response_include_org.json" + ) + all_orgs = [space.organization() for space in self.client.v3.spaces.list(include="organization")] + self.client.get.assert_called_with(self.client.get.return_value.url) + self.assertEqual(2, len(all_orgs)) + self.assertEqual(all_orgs[0]["name"], "org1") + self.assertIsInstance(all_orgs[0], Entity) + self.assertEqual(all_orgs[1]["name"], "org2") + self.assertIsInstance(all_orgs[1], Entity) diff --git a/pool/shard001/Python/0013313_cache.py b/pool/shard001/Python/0013313_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..adeee38a5c9a2d430b3df9089a99b7b868ededd8 --- /dev/null +++ b/pool/shard001/Python/0013313_cache.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# vim:ts=4:sw=4:expandtab +""" + py-diffbot - cache.py + + Caching handlers with support for file, GAE memcache and python memcache + + This source file is subject to the new BSD license that is bundled with this + package in the file LICENSE.txt. The license is also available online at the + URL: + + :copyright: Copyright (C) 2011 Nik Cubrilovic and others, see AUTHORS + :license: new BSD, see LICENSE for more details. +""" + +__version__ = '0.0.2' +__author__ = 'Nik Cubrilovic ' + + +import os, logging, hashlib, urllib + +try: + from google.appengine.api import memcache + GAE = True +except ImportError: + GAE = False + try: + import memcache + LOCAL_MEMCACHE = True + except ImportError: + LOCAL_MEMCACHE = False + +#--------------------------------------------------------------------------- +# Handler Classes +#--------------------------------------------------------------------------- + +class CacheHandler(object): + + options = None + + def __init__(self, options): + self.options = options + + def wrap(self, func): + def cache(url, data): + logging.info("Called fetch function with") + key = self.hash(url + '?' + urllib.urlencode(data)) + cache_store = self.get(key) + if cache_store: + return cache_store + val = func(url, data) + if val: + self.set(key, val) + return val + return cache + + def hash(self, key): + return hashlib.sha1(key).hexdigest() + +class NullHandler(CacheHandler): + def __init__(self, options): + pass + + def wrap(self, func): + return func + +class MemcacheHandler(CacheHandler): + + def fname(self): + pass + + def fname(self): + pass + + +class GAEMemcacheHandler(CacheHandler): + ttl = 60 * 60 * 24 * 4 + + def get(self, key): + return memcache.get(key) + + def set(self, key, value): + return memcache.set(key, value, self.ttl) + + +class FileCacheHandler(CacheHandler): + + cache_folder = None + + def __init__(self, options): + if options is not None and options.has_key('cache_folder'): + cf = options['cache_folder'] + if not cf.startswith('/'): + cf = os.path.join(os.path.dirname(__file__), cf) + if os.path.isdir(cf): + self.cache_folder = options['cache_folder'] + else: + raise Exception("Not a valid cache folder: %s (got: %s)" % (cf, os.path.isdir(cf))) + else: + import tempfile + self.cache_folder = tempfile.gettempdir() + + def get_filepath(self, key): + return os.path.join(self.cache_folder, "%s.txt" % key) + + def get(self, key): + file_path = self.get_filepath(key) + if os.path.isfile(file_path): + logging.info("CACHE HIT") + return open(file_path).read() + return False + + def set(self, key, value): + file_path = self.get_filepath(key) + try: + f = open(file_path, 'w') + f.write(value) + except Exception, e: + logging.error("Exception: could not write file %s" % (file_path)) + logging.exception(e) + return False + return True + + +#--------------------------------------------------------------------------- +# Handler Class +#--------------------------------------------------------------------------- + + +def handler(cache_options = None): + if cache_options: + if cache_options.has_key('handler'): + if cache_options['handler'] == 'memcache' and GAE: + return GAEMemcacheHandler(cache_options) + elif cache_options['handler'] == 'memcache' and LOCAL_MEMCACHE: + return MemcacheHandler(cache_options) + elif cache_options['handler'] == 'file': + return FileCacheHandler(cache_options) + if GAE: + return GAEMemcacheHandler(cache_options) + if LOCAL_MEMCACHE and cache_options.has_key('memcache_server'): + return MemcacheHandler(cache_options) + return NullHandler(cache_options) diff --git a/pool/shard001/Python/0013316_test_nexson_validation.py b/pool/shard001/Python/0013316_test_nexson_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..d04444c9b5fd8b762d3a2eb7be3734ab9a8432a2 --- /dev/null +++ b/pool/shard001/Python/0013316_test_nexson_validation.py @@ -0,0 +1,117 @@ +#! /usr/bin/env python +from peyotl.nexson_syntax import detect_nexson_version, get_empty_nexson +from peyotl.utility.str_util import UNICODE +from peyotl.nexson_validation import validate_nexson +from peyotl.test.support import pathmap +from peyotl.test.support.helper import (testing_write_json, + testing_read_json, + testing_through_json, + testing_dict_eq, + testing_conv_key_unicode_literal) +from peyotl.utility import get_logger +import unittest +import os + +_LOG = get_logger(__name__) + +# round trip filename tuples +VALID_NEXSON_DIRS = ['9', 'otu', ] + + +class TestConvert(unittest.TestCase): + def testDetectVersion(self): + o = pathmap.nexson_obj('invalid/bad_version.json.input') + v = detect_nexson_version(o) + self.assertEqual(v, '1.3.1') + + def testValidFilesPass(self): + format_list = ['1.2'] + msg = '' + for d in VALID_NEXSON_DIRS: + for nf in format_list: + frag = os.path.join(d, 'v{f}.json'.format(f=nf)) + nexson = pathmap.nexson_obj(frag) + aa = validate_nexson(nexson) + annot = aa[0] + for e in annot.errors: + _LOG.debug('unexpected error from {f}: {m}'.format(f=frag, m=UNICODE(e))) + if len(annot.errors) > 0: + ofn = pathmap.nexson_source_path(frag + '.output') + ew_dict = annot.get_err_warn_summary_dict() + testing_write_json(ew_dict, ofn) + msg = "File failed to validate cleanly. See {o}".format(o=ofn) + self.assertEqual(len(annot.errors), 0, msg) + + def testInvalidFilesFail(self): + msg = '' + for fn in pathmap.all_files(os.path.join('nexson', 'invalid')): + if fn.endswith('.input'): + frag = fn[:-len('.input')] + inp = testing_read_json(fn) + try: + aa = validate_nexson(inp) + except: + continue + annot = aa[0] + if len(annot.errors) == 0: + ofn = pathmap.nexson_source_path(frag + '.output') + ew_dict = annot.get_err_warn_summary_dict() + testing_write_json(ew_dict, ofn) + msg = "Failed to reject file. See {o}".format(o=str(msg)) + self.assertTrue(False, msg) + + def testExpectedWarnings(self): + msg = '' + for fn in pathmap.all_files(os.path.join('nexson', 'warn_err')): + if fn.endswith('.input'): + frag = fn[:-len('.input')] + efn = frag + '.expected' + if os.path.exists(efn): + inp = testing_read_json(fn) + aa = validate_nexson(inp) + annot = aa[0] + ew_dict = annot.get_err_warn_summary_dict() + ew_dict = testing_conv_key_unicode_literal(testing_through_json(ew_dict)) + exp = testing_conv_key_unicode_literal(testing_read_json(efn)) + if not testing_dict_eq(ew_dict, exp): + ofn = frag + '.output' + testing_write_json(ew_dict, ofn) + msg = "Validation failed to produce expected outcome. Compare {o} and {e}".format(o=ofn, e=efn) + self.assertDictEqual(exp, ew_dict, msg) + else: + _LOG.warn('Expected output file "{f}" not found'.format(f=efn)) + + def testOldExpectedWarnings(self): + msg = '' + for fn in pathmap.all_files(os.path.join('nexson', 'old-tests')): + if fn.endswith('.input'): + frag = fn[:-len('.input')] + efn = frag + '.expected' + if os.path.exists(efn): + inp = testing_read_json(fn) + aa = validate_nexson(inp) + annot = aa[0] + ew_dict = annot.get_err_warn_summary_dict() + ew_dict = testing_through_json(ew_dict) + exp = testing_read_json(efn) + if not testing_dict_eq(ew_dict, exp): + ofn = frag + '.output' + testing_write_json(ew_dict, ofn) + msg = "Validation failed to produce expected outcome. Compare {o} and {e}".format(o=ofn, e=efn) + self.assertDictEqual(exp, ew_dict, msg) + else: + _LOG.warn('Expected output file "{f}" not found'.format(f=efn)) + + def testCreated(self): + b = get_empty_nexson() + aa = validate_nexson(b) + annot = aa[0] + self.assertFalse(annot.has_error()) + b = get_empty_nexson(include_cc0=True) + aa = validate_nexson(b) + annot = aa[0] + self.assertFalse(annot.has_error()) + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard001/Python/0013317_scaleway.py b/pool/shard001/Python/0013317_scaleway.py new file mode 100644 index 0000000000000000000000000000000000000000..17670dd2ea318c5ddf4a47997ee6653f62551314 --- /dev/null +++ b/pool/shard001/Python/0013317_scaleway.py @@ -0,0 +1,245 @@ +# Copyright (c) 2017 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) + +__metaclass__ = type + +DOCUMENTATION = ''' + name: scaleway + plugin_type: inventory + author: + - Remy Leone (@sieben) + short_description: Scaleway inventory source + description: + - Get inventory hosts from Scaleway + options: + plugin: + description: token that ensures this is a source file for the 'scaleway' plugin. + required: True + choices: ['scaleway'] + regions: + description: Filter results on a specific Scaleway region + type: list + default: + - ams1 + - par1 + tags: + description: Filter results on a specific tag + type: list + oauth_token: + required: True + description: Scaleway OAuth token. + env: + # in order of precedence + - name: SCW_TOKEN + - name: SCW_API_KEY + - name: SCW_OAUTH_TOKEN + hostnames: + description: List of preference about what to use as an hostname. + type: list + default: + - public_ipv4 + choices: + - public_ipv4 + - private_ipv4 + - public_ipv6 + - hostname + - id +''' + +EXAMPLES = ''' +# scaleway_inventory.yml file in YAML format +# Example command line: ansible-inventory --list -i scaleway_inventory.yml + +plugin: scaleway +regions: + - ams1 + - par1 +tags: + - foobar +hostnames: + - public_ipv4 +''' + +import json + +from ansible.errors import AnsibleError +from ansible.plugins.inventory import BaseInventoryPlugin +from ansible.module_utils.scaleway import SCALEWAY_LOCATION +from ansible.module_utils.urls import open_url +from ansible.module_utils._text import to_native + + +def _fetch_information(token, url): + try: + response = open_url(url, + headers={'X-Auth-Token': token, + 'Content-type': 'application/json'}) + except Exception as e: + raise AnsibleError("Error while fetching %s: %s" % (url, to_native(e))) + + try: + raw_json = json.loads(response.read()) + except ValueError: + raise AnsibleError("Incorrect JSON payload") + + try: + return raw_json["servers"] + except KeyError: + raise AnsibleError("Incorrect format from the Scaleway API response") + + +def _build_server_url(api_endpoint): + return "/".join([api_endpoint, "servers"]) + + +def extract_public_ipv4(server_info): + try: + return server_info["public_ip"]["address"] + except (KeyError, TypeError): + return None + + +def extract_private_ipv4(server_info): + try: + return server_info["private_ip"] + except (KeyError, TypeError): + return None + + +def extract_hostname(server_info): + try: + return server_info["hostname"] + except (KeyError, TypeError): + return None + + +def extract_server_id(server_info): + try: + return server_info["id"] + except (KeyError, TypeError): + return None + + +def extract_public_ipv6(server_info): + try: + return server_info["ipv6"]["address"] + except (KeyError, TypeError): + return None + + +def extract_tags(server_info): + try: + return server_info["tags"] + except (KeyError, TypeError): + return None + + +def extract_zone(server_info): + try: + return server_info["location"]["zone_id"] + except (KeyError, TypeError): + return None + +extractors = { + "public_ipv4": extract_public_ipv4, + "private_ipv4": extract_private_ipv4, + "public_ipv6": extract_public_ipv6, + "hostname": extract_hostname, + "id": extract_server_id +} + + +class InventoryModule(BaseInventoryPlugin): + NAME = 'scaleway' + + def verify_file(self, path): + return "scaleway" in path + + def _fill_host_variables(self, host, server_info): + targeted_attributes = ( + "arch", + "commercial_type", + "id", + "organization", + "state", + "hostname", + "state" + ) + for attribute in targeted_attributes: + self.inventory.set_variable(host, attribute, server_info[attribute]) + + self.inventory.set_variable(host, "tags", server_info["tags"]) + + if extract_public_ipv6(server_info=server_info): + self.inventory.set_variable(host, "public_ipv6", extract_public_ipv6(server_info=server_info)) + + if extract_public_ipv4(server_info=server_info): + self.inventory.set_variable(host, "public_ipv4", extract_public_ipv4(server_info=server_info)) + self.inventory.set_variable(host, "ansible_host", extract_public_ipv4(server_info=server_info)) + + def _get_zones(self, config_zones): + return set(SCALEWAY_LOCATION.keys()).intersection(config_zones) + + def match_groups(self, server_info, tags): + server_zone = extract_zone(server_info=server_info) + server_tags = extract_tags(server_info=server_info) + + # If a server does not have a zone, it means it is archived + if server_zone is None: + return set() + + # If no filtering is defined, all tags are valid groups + if tags is None: + return set(server_tags).union((server_zone,)) + + matching_tags = set(server_tags).intersection(tags) + + if not matching_tags: + return set() + else: + return matching_tags.union((server_zone,)) + + def _filter_host(self, host_infos, hostname_preferences): + + for pref in hostname_preferences: + if extractors[pref](host_infos): + return extractors[pref](host_infos) + + return None + + def do_zone_inventory(self, zone, token, tags, hostname_preferences): + self.inventory.add_group(zone) + zone_info = SCALEWAY_LOCATION[zone] + + url = _build_server_url(zone_info["api_endpoint"]) + raw_zone_hosts_infos = _fetch_information(url=url, token=token) + + for host_infos in raw_zone_hosts_infos: + + hostname = self._filter_host(host_infos=host_infos, + hostname_preferences=hostname_preferences) + + # No suitable hostname were found in the attributes and the host won't be in the inventory + if not hostname: + continue + + groups = self.match_groups(host_infos, tags) + + for group in groups: + self.inventory.add_group(group=group) + self.inventory.add_host(group=group, host=hostname) + self._fill_host_variables(host=hostname, server_info=host_infos) + + def parse(self, inventory, loader, path, cache=True): + super(InventoryModule, self).parse(inventory, loader, path) + self._read_config_data(path=path) + + config_zones = self.get_option("regions") + tags = self.get_option("tags") + token = self.get_option("oauth_token") + hostname_preference = self.get_option("hostnames") + + for zone in self._get_zones(config_zones): + self.do_zone_inventory(zone=zone, token=token, tags=tags, hostname_preferences=hostname_preference) diff --git a/pool/shard001/Python/0013326_DEMO12.py b/pool/shard001/Python/0013326_DEMO12.py new file mode 100644 index 0000000000000000000000000000000000000000..a8587c9da6c154268eca156b20e624eef7eb220d --- /dev/null +++ b/pool/shard001/Python/0013326_DEMO12.py @@ -0,0 +1,22 @@ +import sys, os, traceback, optparse +import time +import re +import requests +from bs4 import BeautifulSoup +import csv +import html5lib + +r = requests.get("http://www.ontariogasprices.com/Pioneer_Gas_Stations/St_Catharines/70472/index.aspx") +soup = BeautifulSoup(r.content, "html5lib") + +content = soup.find_all("dd") + +Address_List = [] +for item in content: + item = item.text + Address_List.append(item) + #print each.contents.find_all("d1", {"class": "spa_cont"}) + #print each.contents.find_all("dd").text + +Address_List = Address_List[:4] +print Address_List \ No newline at end of file diff --git a/pool/shard001/Python/0013329_sort.py b/pool/shard001/Python/0013329_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..8f69a45bc00d3a107d074c32bf9dc0b31208a492 --- /dev/null +++ b/pool/shard001/Python/0013329_sort.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +#coding: utf-8 +import sys +from common import sort_items + +if len(sys.argv) < 2: + print "Sort the dictionary" + print "Usage: ", sys.argv[0], "[input] ([output])" + exit(1) + +input = sys.argv[1] + +if len(sys.argv) < 3: + output = input +else: + output = sys.argv[2] + +sort_items(input, output) diff --git a/pool/shard001/Python/0013330_test_commites_model.py b/pool/shard001/Python/0013330_test_commites_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a8fa951dc6d8e29d6836fa4b797641744ba9dc --- /dev/null +++ b/pool/shard001/Python/0013330_test_commites_model.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +__author__ = 'panter.dsd@gmail.com' + +import tempfile +import os +import unittest + +from PyQt5.QtCore import Qt + +from git import Git +from commites_model import CommitesModel + + +class TestCommitesModel(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.init_empty_git_repo() + + def tearDown(self): + self.temp_dir.cleanup() + del self.temp_dir + + def init_empty_git_repo(self): + os.chdir(self.temp_dir.name) + self._git = Git() + self._git.execute_command(["init"], False) + self._git.repo_path = self.temp_dir.name + "/.git" + + def test_empty_repo(self): + model = CommitesModel(self._git, None) + self.assertEqual(model.rowCount(), 0) + self.assertEqual(model.columnCount(), 4) + + for column in range(model.columnCount()): + self.assertFalse( + model.data(model.index(0, column), Qt.DisplayRole) + ) + + def _commit_file(self, commit_name): + file = tempfile.mkstemp(dir=self.temp_dir.name) + self._git.stage_files([file[1]]) + self.assertTrue(self._git.commit(commit_name)) + + def _generate_repo(self): + result = [] + for i in range(10): + commit_name = "Commit" + str(i) + self._commit_file(commit_name) + result.append(commit_name) + + return result + + def test_comments_repo(self): + commites = self._generate_repo() + model = CommitesModel(self._git, None) + self.assertEqual(model.rowCount(), len(commites)) + i = len(commites) - 1 + + for commit in commites: + self.assertEqual( + model.data(model.index(i, 1), Qt.EditRole), commit + ) + + i -= 1 + + def test_roles_data(self): + commites = self._generate_repo() + model = CommitesModel(self._git, None) + + commit = commites[-1] + + self.assertEqual( + model.data(model.index(0, 1), Qt.DisplayRole), "[master]" + commit + ) + + self.assertEqual(model.data(model.index(0, 1), Qt.ToolTipRole), commit) + self.assertEqual(model.data(model.index(0, 1), Qt.EditRole),commit) + self.assertTrue( + model.data(model.index(0, 0), Qt.EditRole).startswith( + model.data(model.index(0, 0), Qt.DisplayRole) + ) + ) + self.assertNotEqual( + model.data(model.index(0, 0), Qt.EditRole), + model.data(model.index(0, 0), Qt.DisplayRole) + ) + + def test_data_with_tag(self): + commites = self._generate_repo() + tag_name = "some_tag" + tag_message = "some_tag_message" + + self._git.create_tag( + self._git.commites()[0].id(), tag_name, tag_message + ) + + model = CommitesModel(self._git, None) + commit = commites[-1] + + self.assertEqual( + model.data(model.index(0, 1), Qt.DisplayRole), + "<" + tag_name + ">[master]" + commit + ) + + self.assertTrue( + tag_name in model.data(model.index(0, 1), Qt.ToolTipRole) + ) + + self.assertTrue( + tag_message in model.data(model.index(0, 1), Qt.ToolTipRole) + ) + + self.assertEqual(model.data(model.index(0, 1), Qt.EditRole), commit) + + +def suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(TestCommitesModel)) + return suite diff --git a/pool/shard001/Python/0013339_dae_single_shooting_in_30_lines.py b/pool/shard001/Python/0013339_dae_single_shooting_in_30_lines.py new file mode 100644 index 0000000000000000000000000000000000000000..4b707855eef5e527ad98ba2895efa4b38107bd2f --- /dev/null +++ b/pool/shard001/Python/0013339_dae_single_shooting_in_30_lines.py @@ -0,0 +1,83 @@ +# +# This file is part of CasADi. +# +# CasADi -- A symbolic framework for dynamic optimization. +# Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, +# K.U. Leuven. All rights reserved. +# Copyright (C) 2011-2014 Greg Horn +# +# CasADi is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 3 of the License, or (at your option) any later version. +# +# CasADi is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with CasADi; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# +from casadi import * + +""" +This example mainly intended for CasADi presentations. +It implements direct single shooting for DAEs in only about 30 lines of code, +using a minimal number of concepts. + +We do not recommend using this example as a template for solving optimal control problems in practise. + +Joel Andersson, 2012 +""" + +# Declare variables +x = SX.sym("x",2) # Differential states +z = SX.sym("z") # Algebraic variable +u = SX.sym("u") # Control +t = SX.sym("t") # Time + +# Differential equation +f_x = vertcat((z*x[0]-x[1]+u, x[0])) + +# Algebraic equation +f_z = x[1]**2 + z - 1 + +# Lagrange cost term (quadrature) +f_q = x[1]**2 + x[1]**2 + u**2 + +# DAE callback function +f = SXFunction([x,z,u,t],[f_x,f_z,f_q]) + +# Create an integrator +I = Integrator("idas", f) +I.setOption("tf",0.5) # interval length +I.init() + +# All controls +U = MX.sym("U",20) + +# Construct graph of integrator calls +X = MX([0,1]) +J = 0 +for k in range(20): + tmp = I.call( integratorIn(x0=X,p=U[k]) ) # Call the integrator + X,Q = integratorOut(tmp,"xf","qf") + J += Q # Sum up quadratures + +# NLP callback functions +nlp = MXFunction(nlpIn(x=U),nlpOut(f=J,g=X)) + +# Allocate an NLP solver +solver = NlpSolver("ipopt", nlp) +solver.init() + +# Pass bounds, initial guess and solve NLP +solver.setInput(-0.75, "lbx") # Lower variable bound +solver.setInput( 1.0, "ubx") # Upper variable bound +solver.setInput( 0.0, "lbg") # Lower constraint bound +solver.setInput( 0.0, "ubg") # Upper constraint bound +solver.setInput( 0.0, "x0") # Initial guess +solver.evaluate() diff --git a/pool/shard001/Python/0013342_models.py b/pool/shard001/Python/0013342_models.py new file mode 100644 index 0000000000000000000000000000000000000000..2db574cf0e6c8903130d1edad0d3aa79b7d50938 --- /dev/null +++ b/pool/shard001/Python/0013342_models.py @@ -0,0 +1,75 @@ +# lint-amnesty, pylint: disable=missing-module-docstring + +from config_models.models import ConfigurationModel +from django.contrib.sites.models import Site +from django.db import models +from django.utils.translation import gettext_lazy as _ +from model_utils import Choices +from model_utils.models import TimeStampedModel +from simple_history.models import HistoricalRecords + + +class Schedule(TimeStampedModel): + """ + .. no_pii: + """ + + enrollment = models.OneToOneField('student.CourseEnrollment', null=False, on_delete=models.CASCADE) + # The active field on the schedule is deprecated, please do not rely on it. + # You can use the is_active field on the CourseEnrollment model instead (i.e. schedule.enrollment.is_active). + # Removing this field from the database is a TODO for https://openedx.atlassian.net/browse/AA-574. + active = models.BooleanField( + default=True, + help_text=_('Indicates if this schedule is actively used') + ) + start_date = models.DateTimeField( + db_index=True, + help_text=_('Date this schedule went into effect'), + null=True, + default=None + ) + upgrade_deadline = models.DateTimeField( + blank=True, + db_index=True, + null=True, + help_text=_('Deadline by which the learner must upgrade to a verified seat') + ) + history = HistoricalRecords() + + def get_experience_type(self): + try: + return self.experience.experience_type # lint-amnesty, pylint: disable=no-member + except ScheduleExperience.DoesNotExist: + return ScheduleExperience.EXPERIENCES.default + + class Meta: + verbose_name = _('Schedule') + verbose_name_plural = _('Schedules') + + +class ScheduleConfig(ConfigurationModel): + """ + .. no_pii: + """ + KEY_FIELDS = ('site',) + + site = models.ForeignKey(Site, on_delete=models.CASCADE) + enqueue_recurring_nudge = models.BooleanField(default=False) + deliver_recurring_nudge = models.BooleanField(default=False) + enqueue_upgrade_reminder = models.BooleanField(default=False) + deliver_upgrade_reminder = models.BooleanField(default=False) + enqueue_course_update = models.BooleanField(default=False) + deliver_course_update = models.BooleanField(default=False) + + +class ScheduleExperience(models.Model): + """ + .. no_pii: + """ + EXPERIENCES = Choices( + (0, 'default', 'Recurring Nudge and Upgrade Reminder'), + (1, 'course_updates', 'Course Updates') + ) + + schedule = models.OneToOneField(Schedule, related_name='experience', on_delete=models.CASCADE) + experience_type = models.PositiveSmallIntegerField(choices=EXPERIENCES, default=EXPERIENCES.default) diff --git a/pool/shard001/Python/0013343_team14.py b/pool/shard001/Python/0013343_team14.py new file mode 100644 index 0000000000000000000000000000000000000000..eb70693c81535ab5a4b3417803ea7b33cac36325 --- /dev/null +++ b/pool/shard001/Python/0013343_team14.py @@ -0,0 +1,68 @@ +#### +# Each team's file must define four tokens: +# team_name: a string +# strategy_name: a string +# strategy_description: a string +# move: A function that returns 'c' or 'b' +#### + +team_name = 'Carter' # Only 10 chars displayed. +strategy_name = 'The name the team gives to this strategy' +strategy_description = 'How does this strategy decide?' + +def move(my_history, their_history, my_score, their_score): + ''' Arguments accepted: my_history, their_history are strings. + my_score, their_score are ints. + + Make my move. + Returns 'c' or 'b'. + ''' + + # my_history: a string with one letter (c or b) per round that has been played with this opponent. + # their_history: a string of the same length as history, possibly empty. + # The first round between these two players is my_history[0] and their_history[0]. + # The most recent round is my_history[-1] and their_history[-1]. + + # Analyze my_history and their_history and/or my_score and their_score. + # Decide whether to return 'c' or 'b'. + + return 'c' + + +def test_move(my_history, their_history, my_score, their_score, result): + '''calls move(my_history, their_history, my_score, their_score) + from this module. Prints error if return value != result. + Returns True or False, dpending on whether result was as expected. + ''' + real_result = move(my_history, their_history, my_score, their_score) + if real_result == result: + return True + else: + print("move(" + + ", ".join(["'"+my_history+"'", "'"+their_history+"'", + str(my_score), str(their_score)])+ + ") returned " + "'" + real_result + "'" + + " and should have returned '" + result + "'") + return False + +if __name__ == '__main__': + + # Test 1: Betray on first move. + if test_move(my_history='', + their_history='', + my_score=0, + their_score=0, + result='b'): + print ('Test passed') + # Test 2: Continue betraying if they collude despite being betrayed. + test_move(my_history='bbb', + their_history='ccc', + # Note the scores are for testing move(). + # The history and scores don't need to match unless + # that is relevant to the test of move(). Here, + # the simulation (if working correctly) would have awarded + # 300 to me and -750 to them. This test will pass if and only if + # move('bbb', 'ccc', 0, 0) returns 'b'. + my_score=0, + their_score=0, + result='b') diff --git a/pool/shard001/Python/0013344_minitest.py b/pool/shard001/Python/0013344_minitest.py new file mode 100644 index 0000000000000000000000000000000000000000..ee5c2705b9866b7234466682785dcd8950cd60ab --- /dev/null +++ b/pool/shard001/Python/0013344_minitest.py @@ -0,0 +1,33 @@ +import openstack.admin +import openstack.compute +import openstack.auth +import openstack.extras + + +auth = openstack.auth.Auth(management_url='http://localhost:8080/v2.0/') +token = auth.tokens.create('1234', 'joeuser', 'secrete') + +extras = openstack.extras.Extras(auth_token=token.id, + auth_url='http://localhost:8774/v1.1/', + management_url='http://localhost:8774/v1.1/') + +admin = openstack.admin.Admin(auth_token=token.id, + auth_url='http://localhost:8774/v1.1/', + management_url='http://localhost:8774/v1.1/') + +compute = openstack.compute.Compute(auth_token=token.id, + auth_url='http://localhost:8774/v1.1/', + management_url='http://localhost:8774/v1.1/') +servers = admin.servers.list() + +console = extras.consoles.create(servers[0].id, 'vnc') +print console.output + +#print compute.servers.list() + +if False: + admin.projects.create('test', 'joeuser') + admin.projects.delete('test') + + print admin.projects.list() + print compute.images.list() diff --git a/pool/shard001/Python/0013348_go.py b/pool/shard001/Python/0013348_go.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7f02eae9b8f2bf7c61b016837f5e5fbb34058e --- /dev/null +++ b/pool/shard001/Python/0013348_go.py @@ -0,0 +1,148 @@ +"""Gene Ontology Enrichment Analysis.""" +import csv +import tempfile +from collections import defaultdict + +from resolwe.process import ( + Cmd, + DataField, + FileField, + FloatField, + IntegerField, + JsonField, + ListField, + Persistence, + SchedulingClass, + StringField, +) + +from resolwe_bio.process.runtime import ProcessBio + + +class GOEnrichmentAnalysis(ProcessBio): + """Identify significantly enriched Gene Ontology terms for given genes.""" + + slug = "goenrichment" + name = "GO Enrichment analysis" + process_type = "data:goea" + version = "3.6.0" + category = "Other" + data_name = 'GO Enrichment analysis for {{genes|join(", ")|default("?")}}' + scheduling_class = SchedulingClass.INTERACTIVE + persistence = Persistence.TEMP + requirements = { + "expression-engine": "jinja", + "executor": { + "docker": {"image": "public.ecr.aws/genialis/resolwebio/rnaseq:6.0.0"} + }, + "resources": {"cores": 1, "memory": 16384, "storage": 50}, + } + + class Input: + """Input fields to process GOEnrichmentAnalysis.""" + + ontology = DataField("ontology:obo", label="Gene Ontology") + gaf = DataField("gaf", label="GO annotation file (GAF v2.0)") + genes = ListField( + StringField(), label="List of genes", placeholder="new gene id" + ) + source = StringField(label="Gene ID database of selected genes") + species = StringField( + label="Species", + allow_custom_choice=True, + description="Specify species name. This field is required if gene subset is set.", + choices=[ + ("Homo sapiens", "Homo sapiens"), + ("Mus musculus", "Mus musculus"), + ("Rattus norvegicus", "Rattus norvegicus"), + ("Dictyostelium discoideum", "Dictyostelium discoideum"), + ], + ) + pval_threshold = FloatField( + label="P-value threshold", + default=0.1, + ) + min_genes = IntegerField( + label="Minimum number of genes", + default=1, + description="Minimum number of genes on a GO term.", + ) + + class Output: + """Output fields to process GOEnrichmentAnalysis.""" + + terms = JsonField(label="Enriched terms") + ids = FileField(label="Mapped ids", required=False) + source = StringField(label="Source") + species = StringField(label="Species") + + def run(self, inputs, outputs): + """Run analysis.""" + + if inputs.species != inputs.gaf.output.species: + self.warning( + "Selected genes Species must be the same as the Species field of the GAF file." + ) + self.error( + f"Selected genes are from {inputs.species}, " + f"while GAF file has defined {inputs.gaf.output.species} under Species field." + ) + + org_features = self.feature.filter( + source=inputs.source, species=inputs.species, feature_id__in=inputs.genes + ) + + if len(org_features) == 0: + self.error("No genes were fetched from the knowledge base.") + + if inputs.source == inputs.gaf.output.source: + target_ids = inputs.genes + else: + mapping_res = self.mapping.filter( + source_db=inputs.source, + source_species=inputs.species, + target_db=inputs.gaf.output.source, + target_species=inputs.gaf.output.species, + source_id__in=inputs.genes, + ) + + if len(mapping_res) == 0: + self.error("Failed to map features.") + + ids = defaultdict(list) + target_ids = [] + for m in mapping_res: + if m.source_id in inputs.genes: + target_ids.append(m.target_id) + if m.source_id in ids: + self.warning(f"Mapping {m.source_id} returned multiple times.") + ids[m.source_id].append(m.target_id) + + if len(inputs.genes) > len(ids): + self.warning("Not all features could be mapped.") + + if len(target_ids) > 0: + with open("mapped_ids.txt", "w") as f: + writer = csv.writer(f, delimiter="\t", lineterminator="\n") + for key, value in ids.items(): + for v in value: + writer.writerow([key, v]) + outputs.ids = "mapped_ids.txt" + + with tempfile.NamedTemporaryFile() as input_genes: + input_genes.write(" ".join(target_ids).encode("UTF-8")) + input_genes.flush() + + args = [ + str(inputs.pval_threshold), + str(inputs.min_genes), + inputs.ontology.output.obo_obj.path, + inputs.gaf.output.gaf_obj.path, + input_genes.name, + ] + + (Cmd["processor"][args] > "terms.json")() + + outputs.source = inputs.gaf.output.source + outputs.species = inputs.gaf.output.species + outputs.terms = "terms.json" diff --git a/pool/shard001/Python/0013350_pyunit_pubdev_5761_pdp_NA.py b/pool/shard001/Python/0013350_pyunit_pubdev_5761_pdp_NA.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb63df9aaa45b1878cc0e551a707133ad8624bf --- /dev/null +++ b/pool/shard001/Python/0013350_pyunit_pubdev_5761_pdp_NA.py @@ -0,0 +1,125 @@ +import sys +sys.path.insert(1,"../../") +import h2o +import math +from tests import pyunit_utils +from h2o.estimators.gbm import H2OGradientBoostingEstimator +import random +from six import string_types + + +''' +This test is written to check the following: +1. We can specify the weight column index and the correct weights will be applied to the pdp; +2. We can choose to add a missing values to our predictor of interest if NAs are found in our data. + +We will test the following: +1. build a pdp without weight or missing value enabled +2. build a pdp with missing value enabled and with constant weight enabled. +3. build a pdp with missing value enabled and with changing weight enabled. + +The mean/std/stderr should agree between the two models except for the missing(NA) level as the first pdp will +not have one. + +Implemented the weight mean and std and compare this result with the model found in 3. In Python test, we will +test a classifier. In R test, we will test a regressor. +''' +def partial_plot_test(): + # Import data set that contains NAs + data = h2o.import_file(pyunit_utils.locate('smalldata/prostate/prostate_cat_NA.csv')) + x = data.names + y = 'CAPSULE' + x.remove(y) + + weights = h2o.H2OFrame([3.0]*data.nrow) + tweight2 = [1.0]*data.nrow + random.seed(12345) + for ind in range(len(tweight2)): + tweight2[ind] = random.randint(0,5) + weights2 = h2o.H2OFrame(tweight2) + data = data.cbind(weights) + data = data.cbind(weights2) + data.set_name(data.ncol-2, "constWeight") + data.set_name(data.ncol-1, "variWeight") + + # Build a GBM model predicting for response CAPSULE + gbm_model = H2OGradientBoostingEstimator(ntrees=50, learn_rate=0.05, seed=12345) + gbm_model.train(x=x, y=y, training_frame=data) + + # pdp without weight or NA + pdpOrig = gbm_model.partial_plot(data=data,cols=['AGE', 'RACE'],server=True, plot=True) + # pdp with constant weight and NA + pdpcWNA = gbm_model.partial_plot(data=data, cols=['AGE', 'RACE'], server=True, plot=True, + weight_column="constWeight", include_na=True) + + # compare results + pyunit_utils.assert_H2OTwoDimTable_equal_upto(pdpOrig[0], pdpcWNA[0], pdpOrig[0].col_header, tolerance=1e-10) + pyunit_utils.assert_H2OTwoDimTable_equal_upto(pdpOrig[1], pdpcWNA[1], pdpOrig[1].col_header, tolerance=1e-10) + # pdp with changing weight NA + pdpvWNA = gbm_model.partial_plot(data=data, cols=['AGE', 'RACE'], server=True, plot=True, + weight_column="variWeight", include_na=True) + ageList = pyunit_utils.extract_col_value_H2OTwoDimTable(pdpvWNA[0], "age") + raceList = pyunit_utils.extract_col_value_H2OTwoDimTable(pdpvWNA[1], "race") + raceList.remove(raceList[2]) + raceList.append(data[21,"RACE"]) # replace with NA word + ageList[len(ageList)-1] = float('nan') # replace nan with proper form for python + + compare_weightedStats(gbm_model, 'smalldata/prostate/prostate_cat_NA.csv', raceList, "RACE", tweight2, pdpvWNA[1], tol=1e-10) + compare_weightedStats(gbm_model, 'smalldata/prostate/prostate_cat_NA.csv', ageList, "AGE", tweight2, pdpvWNA[0], tol=1e-10) + + +def compare_weightedStats(model, datafile, xlist, xname, weightV, pdpTDTable, tol=1e-6): + weightStat = manual_partial_dependence(model, datafile, xlist, xname, weightV) # calculate theoretical weighted sts + wMean = pyunit_utils.extract_col_value_H2OTwoDimTable(pdpTDTable, "mean_response") # stats for age predictor + wStd = pyunit_utils.extract_col_value_H2OTwoDimTable(pdpTDTable, "stddev_response") + wStdErr = pyunit_utils.extract_col_value_H2OTwoDimTable(pdpTDTable, "std_error_mean_response") + pyunit_utils.equal_two_arrays(weightStat[0], wMean, tol, tol, throwError=True) + pyunit_utils.equal_two_arrays(weightStat[1], wStd, tol, tol, throwError=True) + pyunit_utils.equal_two_arrays(weightStat[2], wStdErr, tol, tol, throwError=True) + + +def manual_partial_dependence(model, datafile, xlist, xname, weightV): + dataframe = h2o.import_file(pyunit_utils.locate(datafile)) + meanV = [] + stdV = [] + stderrV = [] + nRows = dataframe.nrow + nCols = dataframe.ncol-1 + + for xval in xlist: + cons = [xval]*nRows + if xname in dataframe.names: + dataframe=dataframe.drop(xname) + if not((isinstance(xval, string_types) and xval=='NA') or (isinstance(xval, float) and math.isnan(xval))): + dataframe = dataframe.cbind(h2o.H2OFrame(cons)) + dataframe.set_name(nCols, xname) + + pred = model.predict(dataframe).as_data_frame(use_pandas=False, header=False) + pIndex = len(pred[0])-1 + sumEle = 0.0 + sumEleSq = 0.0 + sumWeight = 0.0 + numNonZeroWeightCount = 0.0 + m = 1.0/math.sqrt(dataframe.nrow*1.0) + for rindex in range(len(pred)): + val = float(pred[rindex][pIndex]); + weight = weightV[rindex] + if (abs(weight) > 0) and isinstance(val, float) and not(math.isnan(val)): + temp = val*weight + sumEle = sumEle+temp + sumEleSq = sumEleSq+temp*val + sumWeight = sumWeight+weight + numNonZeroWeightCount = numNonZeroWeightCount+1 + wMean = sumEle/sumWeight + scale = numNonZeroWeightCount*1.0/(numNonZeroWeightCount-1) + wSTD = math.sqrt((sumEleSq/sumWeight-wMean*wMean)*scale) + meanV.append(wMean) + stdV.append(wSTD) + stderrV.append(wSTD*m) + + return meanV, stdV, stderrV + +if __name__ == "__main__": + pyunit_utils.standalone_test(partial_plot_test) +else: + partial_plot_test() \ No newline at end of file diff --git a/pool/shard001/Python/0013354_test_create_credentials_api_configuration.py b/pool/shard001/Python/0013354_test_create_credentials_api_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..ff002bdb106d801a876eefe243776765c9d1518f --- /dev/null +++ b/pool/shard001/Python/0013354_test_create_credentials_api_configuration.py @@ -0,0 +1,30 @@ +""" +Tests for the create_credentials_api_configuration command +""" + +from unittest import TestCase + +import mock +import pytest +from django.core.management import call_command + +from openedx.core.djangoapps.credentials.models import CredentialsApiConfig +from openedx.core.djangolib.testing.utils import skip_unless_lms + +from ..create_credentials_api_configuration import Command + +COMMAND_MODULE = "openedx.core.djangoapps.credentials.management.commands.create_credentials_api_configuration" + + +@skip_unless_lms +@pytest.mark.django_db +class CertAllowlistGenerationTests(TestCase): + """ + Tests for the create_credentials_api_configuration management command + """ + + @mock.patch(COMMAND_MODULE) + # pylint: disable=unused-argument + def test_successful_generation(self, mock_command): + call_command(Command()) + assert len(CredentialsApiConfig.objects.all()) > 0 diff --git a/pool/shard001/Python/0013355_searchtime2latex.py b/pool/shard001/Python/0013355_searchtime2latex.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8286a282ce349c03b4452bf745a602ea745816 --- /dev/null +++ b/pool/shard001/Python/0013355_searchtime2latex.py @@ -0,0 +1,43 @@ +#encoding=utf-8 + +import csv +import sys +import math + + +def avg(values): + return reduce(lambda x,y: x+y, values) / float(len(values)) + +def sigma(values): + mu = avg(values) + + x = 0 + for i in values: + x += (i - mu)**2 + + return math.sqrt(x/float(len(values))) + +reader = csv.reader(open(sys.argv[1], 'r'), delimiter=' ') + + +times = {} +for row in reader: + length = int(row[0]) + time = float(row[1]) + + if not length in times.keys(): + times[length] = [] + + times[length].append(time) + +print """\\begin{tabular}{lll} + $|w|$ & $n$ & $t \pm \sigma$ \\\\\hline""" + +keys = times.keys() +keys.sort() +for l in keys: + print "\t$%d$ & $%d$ & $%.2f \\pm %.2f$ \\\\" % (l, len(times[l]), avg(times[l]), sigma(times[l])) + + + +print """\end{tabular}""" diff --git a/pool/shard001/Python/0013358_Geometry2DV.py b/pool/shard001/Python/0013358_Geometry2DV.py new file mode 100644 index 0000000000000000000000000000000000000000..b26aa02e66c6350968417153875319bb72ce5faa --- /dev/null +++ b/pool/shard001/Python/0013358_Geometry2DV.py @@ -0,0 +1,52 @@ +""" +Geometry for Flow 2DV +Load width, depth and length data in a dictionary + +Date: 23-07-15 +Authors: Y.M. Dijkstra +""" +from nifty import dynamicImport +from nifty import splitModuleName + + +class Geometry2DV: + # Variables + + # Methods + def __init__(self, input): + """ + """ + self.input = input + return + + def run(self): + """ + """ + # load data from the DataContainer with input + # name and package of functions for depth and width + depthPackage, depthName = splitModuleName(self.input.v('H0', 'type')) + widthPackage, widthName = splitModuleName(self.input.v('B0', 'type')) + + # input variables + depthData = self.input.slice('H0', excludeKey=True) + depthData.addData('L', self.input.v('L')) + + widthData = self.input.slice('B0', excludeKey=True) + widthData.addData('L', self.input.v('L')) + + # instantiate width/depth objects + depthMain_ = dynamicImport(depthPackage, depthName) + widthMain_ = dynamicImport(widthPackage, widthName) + depth = depthMain_('x', depthData) + width = widthMain_('x', widthData) + + # save data + d = {} + d['B'] = width.function + d['H'] = depth.function + d['L'] = self.input.v('L') + + return d + + + diff --git a/pool/shard001/Python/0013367_test_strip_session_ids.py b/pool/shard001/Python/0013367_test_strip_session_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..5cafe891ab580c1300a81a370deb22f348b0c945 --- /dev/null +++ b/pool/shard001/Python/0013367_test_strip_session_ids.py @@ -0,0 +1,70 @@ +# +# Copyright (c) 2011 Daniel Truemper truemped@googlemail.com +# +# test_strip_session_ids.py 14-Apr-2011 +# +# 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 unittest + +from spyder.core.constants import CURI_EXTRACTED_URLS +from spyder.core.settings import Settings +from spyder.processor.stripsessions import StripSessionIds +from spyder.thrift.gen.ttypes import CrawlUri + + +class StripSessionIdsTest(unittest.TestCase): + + def test_that_stripping_session_stuff_works(self): + + s = StripSessionIds(Settings()) + + url = "http://pREis.de/traeger/index.php?sid=8429fb3ae210a2a0e28800b7f48d90f2" + + self.assertEqual("http://pREis.de/traeger/index.php?", + s._remove_session_ids(url)) + + url = "http://preis.de/traeger/index.php?jsessionid=8429fb3ae210a2a0e28800b7f48d90f2" + + self.assertEqual("http://preis.de/traeger/index.php?", + s._remove_session_ids(url)) + + url = "http://preis.de/traeger/index.php?phpsessid=8429fb3ae210a2a0e28800b7f48d90f2" + + self.assertEqual("http://preis.de/traeger/index.php?", + s._remove_session_ids(url)) + + url = "http://preis.de/traeger/index.php?aspsessionid=8429fb3ae210a2a0e28800b7f48d90f2" + + self.assertEqual("http://preis.de/traeger/index.php?", + s._remove_session_ids(url)) + + def test_that_with_uri_works(self): + + s = StripSessionIds(Settings()) + + urls = ["http://preis.de/traeger/index.php?sid=8429fb3ae210a2a0e28800b7f48d90f2", + "http://preis.de/traeger/index.php?jsessionid=8429fb3ae210a2a0e28800b7f48d90f2", + "http://preis.de/traeger/index.php?phpsessid=8429fb3ae210a2a0e28800b7f48d90f2", + "http://preis.de/traeger/index.php?aspsessionid=8429fb3ae210a2a0e28800b7f48d90f2", + ] + + curi = CrawlUri() + curi.optional_vars = { CURI_EXTRACTED_URLS: "\n".join(urls) } + + curi = s(curi) + clean_urls = curi.optional_vars[CURI_EXTRACTED_URLS].split('\n') + + for u in clean_urls: + self.assertEqual("http://preis.de/traeger/index.php?", u) diff --git a/pool/shard001/Python/0013369_build_spirv_binaries.py b/pool/shard001/Python/0013369_build_spirv_binaries.py new file mode 100644 index 0000000000000000000000000000000000000000..f0482285729d969235b0c75c322636a878e29625 --- /dev/null +++ b/pool/shard001/Python/0013369_build_spirv_binaries.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------- +# Vulkan CTS +# ---------- +# +# Copyright (c) 2015 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#------------------------------------------------------------------------- + +import os +import sys +import string +import argparse +import tempfile +import shutil +import fnmatch + +sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "..", "scripts")) + +from build.common import * +from build.config import * +from build.build import * + +class Module: + def __init__ (self, name, dirName, binName): + self.name = name + self.dirName = dirName + self.binName = binName + +VULKAN_MODULE = Module("dEQP-VK", "../external/vulkancts/modules/vulkan", "deqp-vk") +DEFAULT_BUILD_DIR = os.path.join(tempfile.gettempdir(), "spirv-binaries", "{targetName}-{buildType}") +DEFAULT_TARGET = "null" +DEFAULT_DST_DIR = os.path.join(DEQP_DIR, "external", "vulkancts", "data", "vulkan", "prebuilt") + +def getBuildConfig (buildPathPtrn, targetName, buildType): + buildPath = buildPathPtrn.format( + targetName = targetName, + buildType = buildType) + + return BuildConfig(buildPath, buildType, ["-DDEQP_TARGET=%s" % targetName]) + +def cleanDstDir (dstPath): + binFiles = [f for f in os.listdir(dstPath) if os.path.isfile(os.path.join(dstPath, f)) and fnmatch.fnmatch(f, "*.spv")] + + for binFile in binFiles: + print("Removing %s" % os.path.join(dstPath, binFile)) + os.remove(os.path.join(dstPath, binFile)) + +def execBuildPrograms (buildCfg, generator, module, dstPath, vulkanVersion): + fullDstPath = os.path.realpath(dstPath) + workDir = os.path.join(buildCfg.getBuildDir(), "modules", module.dirName) + + pushWorkingDir(workDir) + + try: + binPath = generator.getBinaryPath(buildCfg.getBuildType(), os.path.join(".", "vk-build-programs")) + execute([binPath, "--validate-spv", "--dst-path", fullDstPath, "--target-vulkan-version", vulkanVersion]) + finally: + popWorkingDir() + +def parseArgs (): + parser = argparse.ArgumentParser(description = "Build SPIR-V programs", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("-b", + "--build-dir", + dest="buildDir", + default=DEFAULT_BUILD_DIR, + help="Temporary build directory") + parser.add_argument("-t", + "--build-type", + dest="buildType", + default="Debug", + help="Build type") + parser.add_argument("-c", + "--deqp-target", + dest="targetName", + default=DEFAULT_TARGET, + help="dEQP build target") + parser.add_argument("-d", + "--dst-path", + dest="dstPath", + default=DEFAULT_DST_DIR, + help="Destination path") + parser.add_argument("-u", + "--target-vulkan-version", + dest="vulkanVersion", + default="1.2", + choices=["1.0", "1.1", "1.2"], + help="Target Vulkan version") + return parser.parse_args() + +if __name__ == "__main__": + args = parseArgs() + + generator = ANY_GENERATOR + buildCfg = getBuildConfig(args.buildDir, args.targetName, args.buildType) + module = VULKAN_MODULE + + build(buildCfg, generator, ["vk-build-programs"]) + + if not os.path.exists(args.dstPath): + os.makedirs(args.dstPath) + + execBuildPrograms(buildCfg, generator, module, args.dstPath, args.vulkanVersion) diff --git a/pool/shard001/Python/0013376_test_application.py b/pool/shard001/Python/0013376_test_application.py new file mode 100644 index 0000000000000000000000000000000000000000..811e67785536d060c83b0acf42dce9b739f6baee --- /dev/null +++ b/pool/shard001/Python/0013376_test_application.py @@ -0,0 +1,171 @@ +from asyncio import coroutine, new_event_loop, set_event_loop, get_event_loop +from unittest.mock import Mock +import sys + +from pkg_resources import EntryPoint +import pytest + +from asphalt.core.application import Application +from asphalt.core.component import Component +from asphalt.core.context import ApplicationContext, ContextEventType +from asphalt.core.util import asynchronous + + +class ShutdownAPI: + def __init__(self, app_ctx: ApplicationContext, method: str): + self.app_ctx = app_ctx + self.method = method + + @asynchronous + def shutdown(self): + def callback(): + if self.method == 'stop': + get_event_loop().stop() + elif self.method == 'exit': + sys.exit() + else: + raise BaseException('this should crash the application') + + def schedule(ctx): + event_loop.call_later(0.1, callback) + + event_loop = get_event_loop() + self.app_ctx.add_callback(ContextEventType.started, schedule) + + +class ShutdownComponent(Component): + def __init__(self, method: str): + self.method = method + + def start(self, app_ctx: ApplicationContext): + app_ctx.resources.add(ShutdownAPI(app_ctx, self.method), context_var='shutter') + + +class CustomApp(Application): + def __init__(self, components=None, **kwargs): + super().__init__(components, **kwargs) + self.start_callback_called = False + self.finish_callback_called = False + + @coroutine + def start(self, app_ctx: ApplicationContext): + def started_callback(ctx): + self.start_callback_called = True + + def finished_callback(ctx): + self.finish_callback_called = True + + app_ctx.add_callback(ContextEventType.started, started_callback) + app_ctx.add_callback(ContextEventType.finished, finished_callback) + app_ctx.shutter.shutdown() + + +class TestApplication: + @pytest.fixture + def event_loop(self): + event_loop = new_event_loop() + set_event_loop(event_loop) + return event_loop + + @pytest.fixture + def app(self): + app = CustomApp() + app.component_types['shutdown'] = ShutdownComponent + return app + + @pytest.mark.parametrize('use_entrypoint', [True, False], ids=['entrypoint', 'explicit_class']) + def test_add_component(self, use_entrypoint): + """ + Tests that add_component works with an without an entry point and that external + configuration overriddes local (hardcoded) configuration values. + """ + + app = CustomApp({'shutdown': {'method': 'stop'}}) + if not use_entrypoint: + app.add_component('shutdown', ShutdownComponent, method='exception') + else: + entrypoint = EntryPoint('shutdown', __spec__.name) + entrypoint.load = Mock(return_value=ShutdownComponent) + app.component_types['shutdown'] = entrypoint + app.add_component('shutdown', method='exception') + + assert len(app.components) == 1 + assert isinstance(app.components[0], ShutdownComponent) + assert app.components[0].method == 'stop' + + @pytest.mark.parametrize('alias, cls, exc_cls, message', [ + ('', None, TypeError, 'component_alias must be a nonempty string'), + (6, None, TypeError, 'component_alias must be a nonempty string'), + ('foo', None, LookupError, 'no such component type: foo'), + ('foo', int, TypeError, 'the component class must be a subclass of asphalt.core.Component') + ]) + def test_add_component_errors(self, app, alias, cls, exc_cls, message): + exc = pytest.raises(exc_cls, app.add_component, alias, cls) + assert str(exc.value) == message + + @pytest.mark.parametrize('shutdown_method', ['stop', 'exit']) + @pytest.mark.parametrize('logging_config', [ + True, + {'version': 1, 'loggers': {'asphalt': {'level': 'INFO'}}} + ], ids=['basic', 'dictconfig']) + def test_run(self, event_loop, app, caplog, shutdown_method, logging_config): + """ + Tests that both started and finished callbacks are run when the application is started and + shut down properly. + """ + + app.add_component('shutdown', method=shutdown_method) + app.logging_config = logging_config + app.run(event_loop) + + assert app.start_callback_called + assert app.finish_callback_called + records = [record for record in caplog.records() if record.name == 'asphalt.core'] + assert len(records) == 4 + assert records[0].message == 'Starting components' + assert records[1].message == 'All components started' + assert records[2].message == 'Application started' + assert records[3].message == 'Application stopped' + + def test_start_exception(self, event_loop, app, caplog): + """ + Tests that an exception caught during the application initialization is put into the + application context and made available to finish callbacks. + """ + + def finish(app_ctx): + nonlocal exception + exception = app_ctx.exception + + def start(app_ctx: ApplicationContext): + app_ctx.add_callback(ContextEventType.finished, finish) + raise Exception('bad component') + + exception = None + app.start = start + app.add_component('shutdown', method='stop') + app.run(event_loop) + + assert str(exception) == 'bad component' + records = [record for record in caplog.records() if record.name == 'asphalt.core'] + assert len(records) == 4 + assert records[0].message == 'Starting components' + assert records[1].message == 'All components started' + assert records[2].message == 'Error during application startup' + assert records[3].message == 'Application stopped' + + def test_run_baseexception(self, event_loop, app, caplog): + """ + Tests that BaseExceptions aren't caught anywhere in the stack and crash the application. + """ + + app.add_component('shutdown', method='exception') + exc = pytest.raises(BaseException, app.run, event_loop) + assert str(exc.value) == 'this should crash the application' + + assert app.start_callback_called + records = [record for record in caplog.records() if record.name == 'asphalt.core'] + assert len(records) == 3 + assert records[0].message == 'Starting components' + assert records[1].message == 'All components started' + assert records[2].message == 'Application started' diff --git a/pool/shard001/Python/0013379_init__.py b/pool/shard001/Python/0013379_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1646a4baf14b7c7574f5c18466f7d60f978b063 --- /dev/null +++ b/pool/shard001/Python/0013379_init__.py @@ -0,0 +1,80 @@ +from __future__ import unicode_literals + +import threading +import logging +from functools import wraps +from tests import TestCase as BaseTestCase +from werkzeug.serving import make_server +from flask import g, session, redirect +from catsnap.web import app +from nose.tools import nottest +from splinter import Browser +from splinter.exceptions import ElementDoesNotExist +from selenium.webdriver.remote.remote_connection import LOGGER + +web_actors = {} + + +class TestCase(BaseTestCase): + def setUp(self): + super(TestCase, self).setUp() + self.browser = web_actors['browser'] + + def tearDown(self): + try: + self.visit_url('/logout') + finally: + super(TestCase, self).tearDown() + + def visit_url(self, path): + self.browser.visit('http://localhost:65432' + path) + + +class App(object): + def __init__(self): + self.app = app + + def start(self): + self.server = make_server('0.0.0.0', 65432, self.app) + self.server.serve_forever() + + def stop(self): + if hasattr(self, 'server'): + self.server.shutdown() + + +def setUpPackage(): + test_app = App() + thread = threading.Thread(target=test_app.start) + thread.daemon = True + thread.start() + web_actors['server'] = test_app + + web_actors['browser'] = Browser() + LOGGER.setLevel(logging.WARNING) + + +def tearDownPackage(): + web_actors['browser'].quit() + web_actors['server'].stop() + + +@nottest +@app.route('/become_logged_in') +def become_logged_in(): + g.user = 1 + session['logged_in'] = True + return redirect('/') + +@nottest +@app.before_request +def indicate_test_server(): + g.test_server = True + +@nottest +def logged_in(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + web_actors['browser'].visit('http://localhost:65432/become_logged_in') + fn(*args, **kwargs) + return wrapper diff --git a/pool/shard001/Python/0013382_limits.py b/pool/shard001/Python/0013382_limits.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f2186dbb60ca30b7125daf2bc0f3c4d1874bf3 --- /dev/null +++ b/pool/shard001/Python/0013382_limits.py @@ -0,0 +1,57 @@ +# +# 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. + +"""The limits V3 api.""" + +from cinder.api import microversions as mv +from cinder.api.openstack import wsgi +from cinder.api.v2 import limits as limits_v2 +from cinder.api.views import limits as limits_views +from cinder import quota + +QUOTAS = quota.QUOTAS + + +class LimitsController(limits_v2.LimitsController): + """Controller for accessing limits in the OpenStack API.""" + + def index(self, req): + """Return all global and rate limit information.""" + context = req.environ['cinder.context'] + params = req.params.copy() + req_version = req.api_version_request + + # TODO(wangxiyuan): Support "tenant_id" here to keep the backwards + # compatibility. Remove it once we drop all support for "tenant". + if (req_version.matches(None, + mv.get_prior_version(mv.LIMITS_ADMIN_FILTER)) + or not context.is_admin): + params.pop('project_id', None) + params.pop('tenant_id', None) + project_id = params.get( + 'project_id', params.get('tenant_id', context.project_id)) + + quotas = QUOTAS.get_project_quotas(context, project_id, + usages=False) + abs_limits = {k: v['limit'] for k, v in quotas.items()} + rate_limits = req.environ.get("cinder.limits", []) + + builder = self._get_view_builder(req) + return builder.build(rate_limits, abs_limits) + + def _get_view_builder(self, req): + return limits_views.ViewBuilder() + + +def create_resource(): + return wsgi.Resource(LimitsController()) diff --git a/pool/shard001/Python/0013384_0008_auto_20170425_1958.py b/pool/shard001/Python/0013384_0008_auto_20170425_1958.py new file mode 100644 index 0000000000000000000000000000000000000000..33bd71e330e0f80d5bc564e66499f7bf42242fca --- /dev/null +++ b/pool/shard001/Python/0013384_0008_auto_20170425_1958.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2017-04-25 19:58 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0007_auto_20170425_1256'), + ] + + operations = [ + migrations.AddField( + model_name='service', + name='replicas', + field=models.IntegerField(blank=True, null=True, verbose_name='Replicas'), + ), + migrations.AlterField( + model_name='service', + name='stack', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='services', to='api.Stack'), + ), + ] diff --git a/pool/shard001/Python/0013386_run.py b/pool/shard001/Python/0013386_run.py new file mode 100644 index 0000000000000000000000000000000000000000..dd336b2627e882d7ac9a1fe7d12c59ca3f68d673 --- /dev/null +++ b/pool/shard001/Python/0013386_run.py @@ -0,0 +1,38 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +''' +HDX Collector for OCHA CERF data. + +''' +import os +import scraperwiki +import app.utilities.load as Load + +from app.utilities.item import item +from app.collect.collect import collectData +from app.utilities.store_data import storeData + +def main(): + ''' + Application wrapper. + + ''' + dir_name = os.path.dirname(os.path.realpath(__file__)) + file = os.path.join(dir_name, 'config', 'config.json') + config = Load.loadJSONFile(file) + + for endpoint in config['endpoints']: + data = collectData(endpoint['url']) + storeData(data, endpoint['name']) + + +if __name__ == '__main__': + try: + main() + print('{success} Successully collected OCHA CERF data.'.format(success=item('success'))) + scraperwiki.status('ok') + + except Exception as e: + print('{failure} Failed to collected OCHA CERF data.'.format(failure=item('error'))) + scraperwiki.status('error', 'Failed to collect data.') + diff --git a/pool/shard001/Python/0013388_0008_auto_20171007_1703.py b/pool/shard001/Python/0013388_0008_auto_20171007_1703.py new file mode 100644 index 0000000000000000000000000000000000000000..27f3a25ae374474359a5d16c17e4f7e18438ea9e --- /dev/null +++ b/pool/shard001/Python/0013388_0008_auto_20171007_1703.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.1 on 2017-10-07 15:03 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('fc', '0007_auto_20171007_1649'), + ] + + operations = [ + migrations.AlterField( + model_name='freecompany', + name='fcFb', + field=models.URLField(blank=True, help_text='Inserisci url gruppo facebook', max_length=255, null=True, verbose_name='Facebook'), + ), + migrations.AlterField( + model_name='freecompany', + name='fcTw', + field=models.URLField(blank=True, help_text='Inserisci url account Twitter', max_length=255, null=True, verbose_name='Twitter'), + ), + migrations.AlterField( + model_name='freecompany', + name='fcWebSite', + field=models.URLField(blank=True, max_length=255, null=True, verbose_name='Sito Web Fc'), + ), + ] diff --git a/pool/shard001/Python/0013391_main.py b/pool/shard001/Python/0013391_main.py new file mode 100644 index 0000000000000000000000000000000000000000..1f79312942d29ece4eb3e6e1d2f2abdd9cf3eccc --- /dev/null +++ b/pool/shard001/Python/0013391_main.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- + +from bottle import request, route, run +from fuzzywuzzy import process +import os +import re +import random +import readline +import sys +import telegram +import yaml + + +# Загружаем ответы из внешнего файла, если такой указан и существует +RESPONSES = {} +replies_fn = os.environ.get('REPLIES_YAML', 'replies.yaml') +if os.path.exists(replies_fn): + with open(replies_fn, 'r') as fp: + RESPONSES = yaml.safe_load(fp.read()) + +# Инициализируем бота +bot_token = os.environ.get('BOT_TOKEN', None) +if not bot_token: + raise ValueError("No token found!") +bot = telegram.Bot(token=bot_token) + + +def replace_emoji_code(m): + code = m.group(1) + return getattr(telegram.Emoji, code.upper(), code) + + +def find_reply(message_text, replies_dict): + message = message_text.strip('!., ').lower() + distance = process.extract(message, replies_dict.keys(), limit=1)[0] + + if distance[1] < 75: + reply = u'Дорогая, выпей вина! :wine_glass:' + else: + reply = replies_dict.get( + distance[0], + u'Дорогая, выпей вина! :wine_glass:', + ) + + if isinstance(reply, list): + reply = random.choice(reply) + return re.sub(':([a-z_]+):', replace_emoji_code, reply.encode('utf-8')) + + +def test_replies(replies_dict): + while True: + line = raw_input('> ') + if line == '': + break + print find_reply(line.decode('utf-8'), replies_dict) + + +@route('/bot', method='POST') +def webhook_handler(): + update = telegram.Update.de_json(request.json) + chat_id = update.message.chat_id + + if message: + print '(%d) [%s] %s {{ %s }}' % ( + chat_id, + update.message.from_user.name.encode('utf-8'), + update.message.text.encode('utf-8'), + message.encode('utf-8'), + ) + + reply = find_reply(update.message.text, RESPONSES) + bot.sendChatAction( + chat_id=chat_id, + action=telegram.ChatAction.TYPING, + ) + bot.sendMessage( + chat_id=chat_id, + text=reply, + ) + return 'ok' + + +@route('/') +def index(): + return '42' + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == 'test': + test_replies(RESPONSES) + else: + run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000))) diff --git a/pool/shard001/Python/0013397_windows.py b/pool/shard001/Python/0013397_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3a680d354eac46af4ccbb529229e11d072e9ef --- /dev/null +++ b/pool/shard001/Python/0013397_windows.py @@ -0,0 +1,72 @@ +import sys +from dataclasses import dataclass + + +@dataclass +class WindowsConsoleFeatures: + """Windows features available.""" + + vt: bool = False + """The console supports VT codes.""" + truecolor: bool = False + """The console supports truecolor.""" + + +try: + import ctypes + from ctypes import LibraryLoader, wintypes + + if sys.platform == "win32": + windll = LibraryLoader(ctypes.WinDLL) + else: + windll = None + raise ImportError("Not windows") +except (AttributeError, ImportError, ValueError): + + # Fallback if we can't load the Windows DLL + def get_windows_console_features() -> WindowsConsoleFeatures: + features = WindowsConsoleFeatures() + return features + +else: + + STDOUT = -11 + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 + _GetConsoleMode = windll.kernel32.GetConsoleMode + _GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD] + _GetConsoleMode.restype = wintypes.BOOL + + _GetStdHandle = windll.kernel32.GetStdHandle + _GetStdHandle.argtypes = [ + wintypes.DWORD, + ] + _GetStdHandle.restype = wintypes.HANDLE + + def get_windows_console_features() -> WindowsConsoleFeatures: + """Get windows console features. + + Returns: + WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. + """ + handle = _GetStdHandle(STDOUT) + console_mode = wintypes.DWORD() + result = _GetConsoleMode(handle, console_mode) + vt = bool(result and console_mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) + truecolor = False + if vt: + win_version = sys.getwindowsversion() + truecolor = win_version.major > 10 or ( + win_version.major == 10 and win_version.build >= 15063 + ) + features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) + return features + + +if __name__ == "__main__": + import platform + + features = get_windows_console_features() + from pip._vendor.rich import print + + print(f'platform="{platform.system()}"') + print(repr(features)) diff --git a/pool/shard001/Python/0013399_plugins.py b/pool/shard001/Python/0013399_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..9059d68b4dea6f23870392cc5ba5231506bdaac6 --- /dev/null +++ b/pool/shard001/Python/0013399_plugins.py @@ -0,0 +1,54 @@ +from loguru import logger + +from flexget import options +from flexget.event import event +from flexget.plugin import get_plugins +from flexget.terminal import TerminalTable, colorize, console, disable_colors, table_parser + +logger = logger.bind(name='plugins') + + +def plugins_summary(manager, options): + if options.table_type == 'porcelain': + disable_colors() + header = ['Keyword', 'Interfaces', 'Phases', 'Flags'] + table = TerminalTable(*header, table_type=options.table_type) + for plugin in sorted(get_plugins(phase=options.phase, interface=options.interface)): + if options.builtins and not plugin.builtin: + continue + + flags = [] + if plugin.instance.__doc__: + flags.append('doc') + if plugin.builtin: + flags.append('builtin') + if plugin.debug: + if not options.debug: + continue + flags.append('developers') + + handlers = plugin.phase_handlers + roles = [] + for phase in handlers: + priority = handlers[phase].priority + roles.append('{0}({1})'.format(phase, priority)) + + name = colorize('green', plugin.name) if 'builtin' in flags else plugin.name + table.add_row(name, ', '.join(plugin.interfaces), ', '.join(roles), ', '.join(flags)) + + table.caption = colorize('green', ' Built-in plugins') + table.caption_justify = 'left' + console(table) + + +@event('options.register') +def register_parser_arguments(): + parser = options.register_command( + 'plugins', + plugins_summary, + help='Print registered plugin summaries', + parents=[table_parser], + ) + parser.add_argument('--interface', help='Show plugins belonging to this interface') + parser.add_argument('--phase', help='Show plugins that act on this phase') + parser.add_argument('--builtins', action='store_true', help='Show just builtin plugins') diff --git a/pool/shard001/Python/0013400_ceph_storage.py b/pool/shard001/Python/0013400_ceph_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..e26b9f562ecf7a1686df78ee95155a963684d10e --- /dev/null +++ b/pool/shard001/Python/0013400_ceph_storage.py @@ -0,0 +1,88 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# thumbor ceph storage +# https://github.com/ksperis/thumbor_ceph + +from thumbor.storages import BaseStorage +from thumbor.utils import logger +import rados +import hashlib +from json import loads, dumps + + +class Storage(BaseStorage): + def __init__(self, context, conffile=None): + if conffile is None: + conffile = '/etc/ceph/ceph.conf' + + super(Storage, self).__init__(context) + + if not self.context.config.CEPH_STORAGE_POOL: + raise RuntimeError("CEPH_STORAGE_POOL undefined") + self.cluster = rados.Rados(conffile=conffile) + self.cluster.connect() + logger.debug('INIT RADOS Storage (ID:' + self.cluster.get_fsid() + ')') + self.storage = self.cluster.open_ioctx(self.context.config.CEPH_STORAGE_POOL) + + def put(self, path, bytes): + file_abspath = self.normalize_path(path) + logger.debug('PUT ' + path + ' (' + file_abspath + ')') + self.storage.write_full(file_abspath,bytes) + return file_abspath + + def put_crypto(self, path): + file_abspath = self.normalize_path(path) + logger.debug('PUT CRYPTO ' + path + ' (' + file_abspath + ') : ' + self.context.config.SECURITY_KEY) + if not self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE: + return + + if not self.context.config.SECURITY_KEY: + raise RuntimeError("STORES_CRYPTO_KEY_FOR_EACH_IMAGE can't be True if no SECURITY_KEY specified") + + self.storage.set_xattr(file_abspath, "CRYPTO", self.context.config.SECURITY_KEY) + + def put_detector_data(self, path, data): + key = self.normalize_path(path) + "-detector" + self.storage.write_full(key, dumps(data)) + return key + + def get(self, path): + file_abspath = self.normalize_path(path) + logger.debug('GET ' + path + ' (' + file_abspath + ')') + try: + return self.storage.read(file_abspath, self.storage.stat(file_abspath)[0]) + except rados.ObjectNotFound: + return None + + # get signature key + def get_crypto(self, path): + file_abspath = self.normalize_path(path) + logger.debug('GET CRYPTO ' + path + ' (' + file_abspath + ')') + if not self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE: + return None + return self.storage.get_xattr(file_abspath, "CRYPTO") + + def get_detector_data(self, path): + key = self.normalize_path(path) + "-detector" + try: + data = self.storage.read(key) + except rados.ObjectNotFound: + return None + if not data: + return None + return loads(data) + + def exists(self, path): + file_abspath = self.normalize_path(path) + try: + self.storage.stat(file_abspath) + logger.debug('EXIST (result) ' + path + ' (' + file_abspath + ') : YES') + return True + except rados.ObjectNotFound: + logger.debug('EXIST (result) ' + path + ' (' + file_abspath + ') : NO') + return False + + def normalize_path(self, path): + path = hashlib.sha1(path.encode('utf-8')).hexdigest() + return path diff --git a/pool/shard001/Python/0013404_agent.py b/pool/shard001/Python/0013404_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..023a74b1d932b3797f57d094e7d43712596570d9 --- /dev/null +++ b/pool/shard001/Python/0013404_agent.py @@ -0,0 +1,154 @@ +# +# Autogenerated by Thrift Compiler (0.10.0) +# +# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING +# +# options string: py:new_style +# + +from thrift.Thrift import ( + TApplicationException, + TMessageType, + TProcessor, + TType, +) +from thrift.transport import TTransport + +from opencensus.ext.jaeger.trace_exporter.gen.jaeger import jaeger + + +class Iface(object): + def emitBatch(self, batch): + """ + Parameters: + - batch + """ + pass + + +class Client(Iface): + def __init__(self, iprot, oprot=None): + self._iprot = self._oprot = iprot + if oprot is not None: + self._oprot = oprot + self._seqid = 0 + + def emitBatch(self, batch): + """ + Parameters: + - batch + """ + self.send_emitBatch(batch) + + def send_emitBatch(self, batch): + self._oprot.writeMessageBegin('emitBatch', TMessageType.ONEWAY, + self._seqid) + args = emitBatch_args() + args.batch = batch + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() + + +class Processor(Iface, TProcessor): + def __init__(self, handler): + self._handler = handler + self._processMap = {} + self._processMap["emitBatch"] = Processor.process_emitBatch + + def process(self, iprot, oprot): + (name, type, seqid) = iprot.readMessageBegin() + if name not in self._processMap: + iprot.skip(TType.STRUCT) + iprot.readMessageEnd() + x = TApplicationException(TApplicationException.UNKNOWN_METHOD, + 'Unknown function %s' % (name)) + oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) + x.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() + return + else: + self._processMap[name](self, seqid, iprot, oprot) + return True + + def process_emitBatch(self, seqid, iprot, oprot): + args = emitBatch_args() + args.read(iprot) + iprot.readMessageEnd() + try: + self._handler.emitBatch(args.batch) + except (TTransport.TTransportException, KeyboardInterrupt, SystemExit): + raise + + +# HELPER FUNCTIONS AND STRUCTURES + + +class emitBatch_args(object): + """ + Attributes: + - batch + """ + + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + 'batch', + (jaeger.Batch, jaeger.Batch.thrift_spec), + None, + ), # 1 + ) + + def __init__( + self, + batch=None, + ): + self.batch = batch + + def read(self, iprot): + if iprot._fast_decode is not None and \ + isinstance(iprot.trans, TTransport.CReadableTransport) and \ + self.thrift_spec is not None: + iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.batch = jaeger.Batch() + self.batch.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot._fast_encode is not None and self.thrift_spec is not None: + oprot.trans.write( + oprot._fast_encode(self, (self.__class__, self.thrift_spec))) + return + oprot.writeStructBegin('emitBatch_args') + if self.batch is not None: + oprot.writeFieldBegin('batch', TType.STRUCT, 1) + self.batch.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + + def validate(self): + return + + def __eq__(self, other): + return isinstance(other, self.__class__) and \ + self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) diff --git a/pool/shard001/Python/0013405_aiplatform_generated_aiplatform_v1_vizier_service_lookup_study_async.py b/pool/shard001/Python/0013405_aiplatform_generated_aiplatform_v1_vizier_service_lookup_study_async.py new file mode 100644 index 0000000000000000000000000000000000000000..4f87a235fd1a768f54642a965e8448ad9c595d82 --- /dev/null +++ b/pool/shard001/Python/0013405_aiplatform_generated_aiplatform_v1_vizier_service_lookup_study_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for LookupStudy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-aiplatform + + +# [START aiplatform_generated_aiplatform_v1_VizierService_LookupStudy_async] +from google.cloud import aiplatform_v1 + + +async def sample_lookup_study(): + # Create a client + client = aiplatform_v1.VizierServiceAsyncClient() + + # Initialize request argument(s) + request = aiplatform_v1.LookupStudyRequest( + parent="parent_value", + display_name="display_name_value", + ) + + # Make the request + response = await client.lookup_study(request=request) + + # Handle the response + print(response) + +# [END aiplatform_generated_aiplatform_v1_VizierService_LookupStudy_async] diff --git a/pool/shard001/Python/0013406_setup.py b/pool/shard001/Python/0013406_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..64ecaa6cc1335b96e08a9021d48ca7c7adf554b2 --- /dev/null +++ b/pool/shard001/Python/0013406_setup.py @@ -0,0 +1,97 @@ +from setuptools import setup, find_packages # Always prefer setuptools over distutils +from codecs import open # To use a consistent encoding +from os import path +from version import get_git_version + +here = path.abspath(path.dirname(__file__)) + +# Get the long description from the relevant file +with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: + long_description = f.read() + +setup( + name='modular_client', + + # Versions should comply with PEP440. For a discussion on single-sourcing + # the version across setup.py and the project code, see + # http://packaging.python.org/en/latest/tutorial.html#version + version=get_git_version(), + + description='Modular device Python client interface for communicating with and calling remote methods on modular device servers.', + long_description=long_description, + + # The project's main homepage. + url='https://github.com/janelia-pypi/modular_client_python', + + # Author details + author='Peter Polidoro', + author_email='peterpolidoro@gmail.com', + + # Choose your license + license='BSD', + + # See https://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 4 - Beta', + + # Indicate who your project is intended for + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Build Tools', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: BSD License', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + # 'Programming Language :: Python :: 2', + # 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + # 'Programming Language :: Python :: 3.2', + # 'Programming Language :: Python :: 3.3', + # 'Programming Language :: Python :: 3.4', + ], + + # What does your project relate to? + keywords='modular serial arduino device client modulardevice modular-device modular_device modularclient modular-client modular_client json json-rpc', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + packages=find_packages(exclude=['contrib', 'docs', 'tests*']), + + # List run-time dependencies here. These will be installed by pip when your + # project is installed. For an analysis of "install_requires" vs pip's + # requirements files see: + # https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files + install_requires=['pyserial', + 'serial_interface', + 'inflection', + 'sre_yield', + ], + + # If there are data files included in your packages that need to be + # installed, specify them here. If using Python 2.6 or less, then these + # have to be included in MANIFEST.in as well. + # package_data={ + # 'sample': ['package_data.dat'], + # }, + + # Although 'package_data' is the preferred approach, in some case you may + # need to place data files outside of your packages. + # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files + # In this case, 'data_file' will be installed into '/my_data' + # data_files=[('my_data', ['data/data_file'])], + + # To provide executable scripts, use entry points in preference to the + # "scripts" keyword. Entry points provide cross-platform support and allow + # pip to create the appropriate form of executable for the target platform. + # entry_points={ + # 'console_scripts': [ + # 'sample=sample:main', + # ], + # }, +) diff --git a/pool/shard001/Python/0013407_runas.py b/pool/shard001/Python/0013407_runas.py new file mode 100644 index 0000000000000000000000000000000000000000..48c694a37f94d159f026d93271be4f38a6b2d225 --- /dev/null +++ b/pool/shard001/Python/0013407_runas.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os +import re +import time +import getpass +from subprocess import Popen, PIPE, STDOUT + +username = eval(input("Username: ")) +passwd = getpass.getpass('gPass: ') + +print(passwd) + +''' +myenv = os.environ.copy() + +myenv['SUDO_ASKPASS'] = '/tmp/askpass.py' +''' +lines = [] + +command = ["/usr/bin/su", '-', username, str("-c"), '/bin/launchctl asuser rsn_local /Applications/stonix4mac.app/Contents/Resources/stonix.app/Contents/MacOS/stonix'] + +#proc = Popen(command, stdout=PIPE, stderr=PIPE).communicate('\n' + passwd + '\n') + + +##### +# Run the command +p = Popen(command, + stdout=PIPE, + stderr=PIPE, + stdin=PIPE, + shell=True, + bufsize=0) + #env=myenv) + +#p.stdin.write('\n') +#p.stdin.flush() +out = p.stdout.readline() +#print out +#while p.poll() is not None: + +while out: + line = out + line = line.rstrip("\n") + lines.append(line) + #print line + if re.match("Password", line): + p.stdin.write(passwd.strip()) + p.stdin.flush() + time.sleep(.5) + out = p.stdout.readline() + else: + out = p.stdout.readline() + +p.wait() diff --git a/pool/shard001/Python/0013409_catalog.py b/pool/shard001/Python/0013409_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..4770abafbcb425490b1dc4898bc062a7212583a8 --- /dev/null +++ b/pool/shard001/Python/0013409_catalog.py @@ -0,0 +1,17 @@ +from django.conf.urls import patterns, url + +from shop.views import ShopListView +from shop.views.product import ProductDetailView +from shop.models.productmodel import Product + + +urlpatterns = patterns('', + url(r'^$', + ShopListView.as_view(model=Product), + name='product_list' + ), + url(r'^(?P[0-9A-Za-z-_.//]+)/$', + ProductDetailView.as_view(), + name='product_detail' + ), + ) diff --git a/pool/shard001/Python/0013410_rabbitmq_global_parameter.py b/pool/shard001/Python/0013410_rabbitmq_global_parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..484b1c757d8ff8a8547de2f46ba6e147bc3ca6ee --- /dev/null +++ b/pool/shard001/Python/0013410_rabbitmq_global_parameter.py @@ -0,0 +1,157 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2013, Chatham Financial +# Copyright: (c) 2017, Juergen Kirschbaum +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: rabbitmq_global_parameter +short_description: Manage RabbitMQ global parameters +description: + - Manage dynamic, cluster-wide global parameters for RabbitMQ +version_added: "2.8" +author: "Juergen Kirschbaum (@jgkirschbaum)" +options: + name: + description: + - Name of the global parameter being set + required: true + default: null + value: + description: + - Value of the global parameter, as a JSON term + required: false + default: null + node: + description: + - erlang node name of the rabbit we wish to configure + required: false + default: rabbit + state: + description: + - Specify if user is to be added or removed + required: false + default: present + choices: [ 'present', 'absent'] +''' + +EXAMPLES = ''' +# Set the global parameter 'cluster_name' to a value of 'mq-cluster' (in quotes) +- rabbitmq_global_parameter: + name: cluster_name + value: "{{ 'mq-cluster' | to_json }}" + state: present +''' + +RETURN = ''' +name: + description: name of the global parameter being set + returned: success + type: string + sample: "cluster_name" +value: + description: value of the global parameter, as a JSON term + returned: changed + type: string + sample: "the-cluster-name" +''' + +import json +from ansible.module_utils.basic import AnsibleModule + + +class RabbitMqGlobalParameter(object): + def __init__(self, module, name, value, node): + self.module = module + self.name = name + self.value = value + self.node = node + + self._value = None + + self._rabbitmqctl = module.get_bin_path('rabbitmqctl', True) + + def _exec(self, args, run_in_check_mode=False): + if not self.module.check_mode or (self.module.check_mode and run_in_check_mode): + cmd = [self._rabbitmqctl, '-q', '-n', self.node] + rc, out, err = self.module.run_command(cmd + args, check_rc=True) + return out.splitlines() + return list() + + def get(self): + global_parameters = self._exec(['list_global_parameters'], True) + + for param_item in global_parameters: + name, value = param_item.split('\t') + + if name == self.name: + self._value = json.loads(value) + return True + return False + + def set(self): + self._exec(['set_global_parameter', + self.name, + json.dumps(self.value)]) + + def delete(self): + self._exec(['clear_global_parameter', self.name]) + + def has_modifications(self): + return self.value != self._value + + +def main(): + arg_spec = dict( + name=dict(type='str', required=True), + value=dict(type='str', default=None), + state=dict(default='present', choices=['present', 'absent']), + node=dict(type='str', default='rabbit') + ) + module = AnsibleModule( + argument_spec=arg_spec, + supports_check_mode=True + ) + + name = module.params['name'] + value = module.params['value'] + if isinstance(value, str): + value = json.loads(value) + state = module.params['state'] + node = module.params['node'] + + result = dict(changed=False) + rabbitmq_global_parameter = RabbitMqGlobalParameter(module, name, value, node) + + if rabbitmq_global_parameter.get(): + if state == 'absent': + rabbitmq_global_parameter.delete() + result['changed'] = True + else: + if rabbitmq_global_parameter.has_modifications(): + rabbitmq_global_parameter.set() + result['changed'] = True + elif state == 'present': + rabbitmq_global_parameter.set() + result['changed'] = True + + result['name'] = name + result['value'] = value + result['state'] = state + + module.exit_json(**result) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0013414_ragel_gen.py b/pool/shard001/Python/0013414_ragel_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..529ac9b6ce776f507090c68565390f61cc0695b8 --- /dev/null +++ b/pool/shard001/Python/0013414_ragel_gen.py @@ -0,0 +1,105 @@ +# coding=utf-8 +# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +import os +import re +import subprocess + +from pants.backend.codegen.targets.java_ragel_library import JavaRagelLibrary +from pants.backend.codegen.tasks.simple_codegen_task import SimpleCodegenTask +from pants.backend.jvm.targets.java_library import JavaLibrary +from pants.base.build_environment import get_buildroot +from pants.base.exceptions import TaskError +from pants.binaries.binary_util import BinaryUtil +from pants.util.dirutil import safe_mkdir_for +from pants.util.memo import memoized_property + + +class RagelGen(SimpleCodegenTask): + @classmethod + def global_subsystems(cls): + return super(RagelGen, cls).global_subsystems() + (BinaryUtil.Factory,) + + @classmethod + def register_options(cls, register): + super(RagelGen, cls).register_options(register) + register('--supportdir', default='bin/ragel', advanced=True, + help='The path to find the ragel binary. Used as part of the path to lookup the' + 'tool with --pants-support-baseurls and --pants_bootstrapdir.') + + # We take the cautious approach here and assume a version bump will always correspond to + # changes in ragel codegen products. + register('--version', default='6.9', advanced=True, fingerprint=True, + help='The version of ragel to use. Used as part of the path to lookup the' + 'tool with --pants-support-baseurls and --pants-bootstrapdir') + + def __init__(self, *args, **kwargs): + super(RagelGen, self).__init__(*args, **kwargs) + self._java_out = os.path.join(self.workdir, 'gen-java') + + @memoized_property + def ragel_binary(self): + binary_util = BinaryUtil.Factory.create() + return binary_util.select_binary(self.get_options().supportdir, + self.get_options().version, + 'ragel') + + def synthetic_target_type(self, target): + return JavaLibrary + + def is_gentarget(self, target): + return isinstance(target, JavaRagelLibrary) + + def execute_codegen(self, invalid_targets): + for target in invalid_targets: + output_dir = self.codegen_workdir(target) + for source in target.sources_relative_to_buildroot(): + abs_source = os.path.join(get_buildroot(), source) + + output_file = os.path.join(output_dir, calculate_genfile(abs_source)) + safe_mkdir_for(output_file) + + args = [self.ragel_binary, '-J', '-o', output_file, abs_source] + + self.context.log.debug('Executing: {args}'.format(args=' '.join(args))) + process = subprocess.Popen(args) + result = process.wait() + if result != 0: + raise TaskError('{binary} ... exited non-zero ({result})' + .format(binary=self.ragel_binary, result=result)) + + +def calculate_class_and_package(path): + package, classname = None, None + with open(path, 'r') as ragel: + for line in ragel.readlines(): + line = line.strip() + package_match = re.match(r'^package ([.a-zA-Z0-9]+);', line) + if package_match: + if package: + raise TaskError('Multiple package declarations in {path}'.format(path=path)) + package = package_match.group(1) + class_match = re.match(r'^public class ([A-Za-z0-9_]+).*', line) + if class_match: + if classname: + raise TaskError('Multiple class declarations in {path}'.format(path=path)) + classname = class_match.group(1) + + if not package: + raise TaskError('Missing package declaration in {path}'.format(path=path)) + if not classname: + raise TaskError('Missing class declaration in {path}'.format(path=path)) + return package, classname + + +def get_filename(package, classname): + return "{package}/{cls}.java".format(package=package.replace(".", os.path.sep), cls=classname) + + +def calculate_genfile(path): + package, classname = calculate_class_and_package(path) + return get_filename(package, classname) diff --git a/pool/shard001/Python/0013420_core.py b/pool/shard001/Python/0013420_core.py new file mode 100644 index 0000000000000000000000000000000000000000..82fc747cfdad930e649e5de8ef124bb3a97b9c92 --- /dev/null +++ b/pool/shard001/Python/0013420_core.py @@ -0,0 +1,275 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst +""" +This module implements the base class and star finder kernel for +detecting stars in an astronomical image. Each star-finding class should +define a method called ``find_stars`` that finds stars in an image. +""" + +import abc +import math +import warnings + +from astropy.stats import gaussian_fwhm_to_sigma +import numpy as np + +from .peakfinder import find_peaks +from ..utils.exceptions import NoDetectionsWarning + + +__all__ = ['StarFinderBase'] + + +class StarFinderBase(metaclass=abc.ABCMeta): + """ + Abstract base class for star finders. + """ + + def __call__(self, data, mask=None): + return self.find_stars(data, mask=mask) + + @staticmethod + def _find_stars(convolved_data, kernel, threshold, *, min_separation=0.0, + mask=None, exclude_border=False): + """ + Find stars in an image. + + Parameters + ---------- + convolved_data : 2D array_like + The convolved 2D array. + + kernel : `_StarFinderKernel` + The convolution kernel. + + threshold : float + The absolute image value above which to select sources. This + threshold should be the threshold input to the star finder class + multiplied by the kernel relerr. + + min_separation : float, optional + The minimum separation for detected objects in pixels. + + mask : 2D bool array, optional + A boolean mask with the same shape as ``data``, where a `True` + value indicates the corresponding element of ``data`` is masked. + Masked pixels are ignored when searching for stars. + + exclude_border : bool, optional + Set to `True` to exclude sources found within half the size of + the convolution kernel from the image borders. The default is + `False`, which is the mode used by IRAF's `DAOFIND`_ and + `starfind`_ tasks. + + Returns + ------- + result : Nx2 `~numpy.ndarray` + A Nx2 array containing the (x, y) pixel coordinates. + + .. _DAOFIND: https://iraf.net/irafhelp.php?val=daofind + + .. _starfind: https://iraf.net/irafhelp.php?val=starfind + """ + # define a local footprint for the peak finder + if min_separation == 0: # daofind + if isinstance(kernel, np.ndarray): + footprint = np.ones(kernel.shape) + else: + footprint = kernel.mask.astype(bool) + else: + # define a local circular footprint for the peak finder + idx = np.arange(-min_separation, min_separation + 1) + xx, yy = np.meshgrid(idx, idx) + footprint = np.array((xx**2 + yy**2) <= min_separation**2, + dtype=int) + + # pad the convolved data and mask by half the kernel size (or + # x/y radius) to allow for detections near the edges + if isinstance(kernel, np.ndarray): + ypad = (kernel.shape[0] - 1) // 2 + xpad = (kernel.shape[1] - 1) // 2 + else: + ypad = kernel.yradius + xpad = kernel.xradius + + if not exclude_border: + pad = ((ypad, ypad), (xpad, xpad)) + pad_mode = 'constant' + convolved_data = np.pad(convolved_data, pad, mode=pad_mode, + constant_values=0.0) + if mask is not None: + mask = np.pad(mask, pad, mode=pad_mode, constant_values=False) + + # find local peaks in the convolved data + # suppress any NoDetectionsWarning from find_peaks + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=NoDetectionsWarning) + tbl = find_peaks(convolved_data, threshold, footprint=footprint, + mask=mask) + + if exclude_border: + xmax = convolved_data.shape[1] - xpad + ymax = convolved_data.shape[0] - ypad + mask = ((tbl['x_peak'] > xpad) & (tbl['y_peak'] > ypad) + & (tbl['x_peak'] < xmax) & (tbl['y_peak'] < ymax)) + tbl = tbl[mask] + + if tbl is None: + return None + + xpos, ypos = tbl['x_peak'], tbl['y_peak'] + if not exclude_border: + xpos -= xpad + ypos -= ypad + + return np.transpose((xpos, ypos)) + + @abc.abstractmethod + def find_stars(self, data, mask=None): + """ + Find stars in an astronomical image. + + Parameters + ---------- + data : 2D array_like + The 2D image array. + + mask : 2D bool array, optional + A boolean mask with the same shape as ``data``, where a + `True` value indicates the corresponding element of ``data`` + is masked. Masked pixels are ignored when searching for + stars. + + Returns + ------- + table : `~astropy.table.Table` or `None` + A table of found stars. If no stars are found then `None` is + returned. + """ + raise NotImplementedError('Needs to be implemented in a subclass.') + + +class _StarFinderKernel: + """ + Container class for a 2D Gaussian density enhancement kernel. + + The kernel has negative wings and sums to zero. It is used by both + `DAOStarFinder` and `IRAFStarFinder`. + + Parameters + ---------- + fwhm : float + The full-width half-maximum (FWHM) of the major axis of the + Gaussian kernel in units of pixels. + + ratio : float, optional + The ratio of the minor and major axis standard deviations of the + Gaussian kernel. ``ratio`` must be strictly positive and less + than or equal to 1.0. The default is 1.0 (i.e., a circular + Gaussian kernel). + + theta : float, optional + The position angle (in degrees) of the major axis of the + Gaussian kernel, measured counter-clockwise from the positive x + axis. + + sigma_radius : float, optional + The truncation radius of the Gaussian kernel in units of sigma + (standard deviation) [``1 sigma = FWHM / + 2.0*sqrt(2.0*log(2.0))``]. The default is 1.5. + + normalize_zerosum : bool, optional + Whether to normalize the Gaussian kernel to have zero sum, The + default is `True`, which generates a density-enhancement kernel. + + Notes + ----- + The class attributes include the dimensions of the elliptical kernel + and the coefficients of a 2D elliptical Gaussian function expressed + as: + + ``f(x,y) = A * exp(-g(x,y))`` + + where + + ``g(x,y) = a*(x-x0)**2 + 2*b*(x-x0)*(y-y0) + c*(y-y0)**2`` + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Gaussian_function + """ + + def __init__(self, fwhm, ratio=1.0, theta=0.0, sigma_radius=1.5, + normalize_zerosum=True): + + if fwhm < 0: + raise ValueError('fwhm must be positive.') + + if ratio <= 0 or ratio > 1: + raise ValueError('ratio must be positive and less or equal ' + 'than 1.') + + if sigma_radius <= 0: + raise ValueError('sigma_radius must be positive.') + + self.fwhm = fwhm + self.ratio = ratio + self.theta = theta + self.sigma_radius = sigma_radius + self.xsigma = self.fwhm * gaussian_fwhm_to_sigma + self.ysigma = self.xsigma * self.ratio + + theta_radians = np.deg2rad(self.theta) + cost = np.cos(theta_radians) + sint = np.sin(theta_radians) + xsigma2 = self.xsigma**2 + ysigma2 = self.ysigma**2 + + self.a = (cost**2 / (2.0 * xsigma2)) + (sint**2 / (2.0 * ysigma2)) + # CCW + self.b = 0.5 * cost * sint * ((1.0 / xsigma2) - (1.0 / ysigma2)) + self.c = (sint**2 / (2.0 * xsigma2)) + (cost**2 / (2.0 * ysigma2)) + + # find the extent of an ellipse with radius = sigma_radius*sigma; + # solve for the horizontal and vertical tangents of an ellipse + # defined by g(x,y) = f + self.f = self.sigma_radius**2 / 2.0 + denom = (self.a * self.c) - self.b**2 + + # nx and ny are always odd + self.nx = 2 * int(max(2, math.sqrt(self.c * self.f / denom))) + 1 + self.ny = 2 * int(max(2, math.sqrt(self.a * self.f / denom))) + 1 + + self.xc = self.xradius = self.nx // 2 + self.yc = self.yradius = self.ny // 2 + + # define the kernel on a 2D grid + yy, xx = np.mgrid[0:self.ny, 0:self.nx] + self.circular_radius = np.sqrt((xx - self.xc)**2 + (yy - self.yc)**2) + self.elliptical_radius = (self.a * (xx - self.xc)**2 + + 2.0 * self.b * (xx - self.xc) + * (yy - self.yc) + + self.c * (yy - self.yc)**2) + + self.mask = np.where( + (self.elliptical_radius <= self.f) + | (self.circular_radius <= 2.0), 1, 0).astype(int) + self.npixels = self.mask.sum() + + # NOTE: the central (peak) pixel of gaussian_kernel has a value of 1. + self.gaussian_kernel_unmasked = np.exp(-self.elliptical_radius) + self.gaussian_kernel = self.gaussian_kernel_unmasked * self.mask + + # denom = variance * npixels + denom = ((self.gaussian_kernel**2).sum() + - (self.gaussian_kernel.sum()**2 / self.npixels)) + self.relerr = 1.0 / np.sqrt(denom) + + # normalize the kernel to zero sum + if normalize_zerosum: + self.data = ((self.gaussian_kernel + - (self.gaussian_kernel.sum() / self.npixels)) + / denom) * self.mask + else: + self.data = self.gaussian_kernel + + self.shape = self.data.shape diff --git a/pool/shard001/Python/0013423_ICA_NKI.py b/pool/shard001/Python/0013423_ICA_NKI.py new file mode 100644 index 0000000000000000000000000000000000000000..5144d42d845ab3e9e99bb3442001d70f5d1e5022 --- /dev/null +++ b/pool/shard001/Python/0013423_ICA_NKI.py @@ -0,0 +1,79 @@ +import nibabel as nib +import numpy as np +from scipy.io import savemat +from nilearn.decomposition.canica import CanICA +from nibabel import gifti + +# LEFT indices +cort = nib.freesurfer.read_label('/afs/cbs.mpg.de/software/freesurfer/5.3.0/ubuntu-precise-amd64/subjects/fsaverage5/label/lh.cortex.label') + +# load data +#subs = ['A00028185'] # list of subject ids to include +subs = np.loadtxt("/scr/murg2/MachineLearning/partialcorr/NKI/subject_list_NKI.txt", dtype=str) +filenames = [] +for sub in subs: + print "SUBJECT ", sub + try: + data_file = gifti.giftiio.read('/scr/ilz1/nilearn_vol2surf_sink/fwhm6/%s_lh_preprocessed_fsaverage5_fwhm6.gii' % sub) + data = np.array([data_file.darrays[i].data for i in range(len(data_file.darrays))]) + data = data.T + data = data[cort, :] + data = np.expand_dims(data,axis=1) + data = np.expand_dims(data,axis=1) + filename = '/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/%s.nii.gz' % sub + img = nib.Nifti1Image(data, np.eye(4)) + img.to_filename(filename) + filenames.append(filename) + except: + print "subject " + sub + " cannot be run" + + +# create artificial mask: +mask = np.ones(len(cort)) +mask = np.expand_dims(mask,axis=1) +mask = np.expand_dims(mask,axis=1) +img = nib.Nifti1Image(mask, np.eye(4)) +img.to_filename('/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/mask.nii.gz') + +# run ICA on group level: +n_components = 20 +n_jobs = 20 #number of CPUs used +canica = CanICA(mask='/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/mask.nii.gz', + n_components=n_components, smoothing_fwhm=0., + threshold=None, verbose=10, random_state=0, n_jobs=n_jobs) + +canica.fit(filenames) + +# Retrieve the independent components in brain space +components_img = canica.masker_.inverse_transform(canica.components_) + +A = np.zeros((10242,n_components)) +A[cort,:] = components_img.get_data().squeeze() +#np.save('/scr/murg2/MachineLearning/partialcorr/ICA/ICA_HCP/ica_HCP500_output_%s.npy' % str(n_components), A) +savemat('/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/ica_NKI_output_%s.mat' % str(n_components), {'ic':A}) + +## RUN ICA ON INDIVIDUAL LEVEL: +for sub in subs: + try: + n_components = 20 + n_jobs = 20 #number of CPUs used + canica = CanICA(mask='/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/mask.nii.gz', + n_components=n_components, smoothing_fwhm=0., + threshold=None, verbose=10, random_state=0, n_jobs=n_jobs) + filename = '/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/%s.nii.gz' % sub + canica.fit(filename) + + # Retrieve the independent components in brain space + components_img = canica.masker_.inverse_transform(canica.components_) + + A = np.zeros((10242,n_components)) + # STILL NEED TO RESOLVE CORT INDICIES + A[cort,:] = components_img.get_data().squeeze() + #np.save('/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/ica_output_%s_%s.npy' % (sub, str(n_components)), A) + savemat('/scr/murg2/MachineLearning/partialcorr/ICA/ICA_NKI/ica_output_%s_%s.mat' % (sub, str(n_components)), {'ic':A}) + except: + print "subject " + sub + " cannot be run" + + + + diff --git a/pool/shard001/Python/0013424_test_payments_api.py b/pool/shard001/Python/0013424_test_payments_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3ccc8c4746ac6fe0d797b77d717863ec7d32fc4a --- /dev/null +++ b/pool/shard001/Python/0013424_test_payments_api.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +import json + +from rest_framework.test import APIClient +from rest_framework import status +from shuup.core.models import Order +from shuup.testing.factories import ( + create_order_with_product, get_default_product, + get_default_shop, get_default_supplier +) + + +def create_order(): + shop = get_default_shop() + product = get_default_product() + supplier = get_default_supplier() + order = create_order_with_product( + product, + shop=shop, + supplier=supplier, + quantity=1, + taxless_base_unit_price=10, + ) + order.cache_prices() + order.save() + return order + + +def get_client(admin_user): + client = APIClient() + client.force_authenticate(user=admin_user) + return client + + +def get_create_payment_url(order_pk): + return "/api/shuup/order/%s/create_payment/" % order_pk + + +def get_set_fully_paid_url(order_pk): + return "/api/shuup/order/%s/set_fully_paid/" % order_pk + + +def get_order_url(order_pk): + return "/api/shuup/order/%s/" % order_pk + + +def test_create_payment(admin_user): + order = create_order() + client = get_client(admin_user) + + payment_identifier = "some_identifier" + data = { + "amount_value": 1, + "payment_identifier": payment_identifier, + "description": "some_payment" + } + + response = client.post( + get_create_payment_url(order.pk), + data, + format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + assert order.get_total_paid_amount().value == 1 + + response = client.get( + get_order_url(order.pk), + format="json" + ) + assert response.status_code == status.HTTP_200_OK + order_data = json.loads(response.content.decode("utf-8")) + payments = order_data["payments"] + assert len(payments) == 1 + assert payments[0]["payment_identifier"] == payment_identifier + + +def test_set_fully_paid(admin_user): + order = create_order() + client = get_client(admin_user) + data = { + "payment_identifier": 1, + "description": "some_payment" + } + order_pk = order.pk + response = client.post( + get_set_fully_paid_url(order_pk), + data, + format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + order = Order.objects.get(pk=order_pk) + assert bool(order.is_paid()) + currently_paid_amount = order.get_total_paid_amount() + + # Make sure that api works with already fully paid orders + response = client.post( + "/api/shuup/order/%s/set_fully_paid/" % order_pk, + data, + format="json" + ) + assert response.status_code == status.HTTP_200_OK + order = Order.objects.get(pk=order_pk) + assert bool(order.is_paid()) + assert currently_paid_amount == order.get_total_paid_amount() + + +def test_set_paid_from_partially_paid_order(admin_user): + order = create_order() + client = get_client(admin_user) + + data = { + "amount_value": 1, + "payment_identifier": 1, + "description": "some_payment" + } + + response = client.post( + get_create_payment_url(order.pk), + data, + format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + assert order.get_total_paid_amount().value == 1 + + data = { + "payment_identifier": 2, + "description": "some_payment" + } + order_pk = order.pk + response = client.post( + get_set_fully_paid_url(order_pk), + data, + format="json" + ) + assert response.status_code == status.HTTP_201_CREATED + order = Order.objects.get(pk=order_pk) + assert bool(order.is_paid()) + assert bool(order.get_total_paid_amount() == order.taxful_total_price.amount) diff --git a/pool/shard001/Python/0013427_findbar.py b/pool/shard001/Python/0013427_findbar.py new file mode 100644 index 0000000000000000000000000000000000000000..2dae183141862eac6056526c83057eea6c830842 --- /dev/null +++ b/pool/shard001/Python/0013427_findbar.py @@ -0,0 +1,155 @@ +# Copyright (C) 2002-2009 Stephen Kennedy +# Copyright (C) 2012-2014 Kai Willadsen +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or (at +# your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from gi.repository import GtkSource + +from meld.ui import gnomeglade + + +class FindBar(gnomeglade.Component): + def __init__(self, parent): + gnomeglade.Component.__init__(self, "findbar.ui", "findbar", + ["arrow_left", "arrow_right"]) + self.set_text_view(None) + self.arrow_left.show() + self.arrow_right.show() + parent.connect('set-focus-child', self.on_focus_child) + + settings = GtkSource.SearchSettings() + self.match_case.bind_property('active', settings, 'case-sensitive') + self.whole_word.bind_property('active', settings, 'at-word-boundaries') + self.regex.bind_property('active', settings, 'regex-enabled') + self.find_entry.bind_property('text', settings, 'search-text') + settings.set_wrap_around(True) + self.search_settings = settings + + def on_focus_child(self, container, widget): + if widget is not None: + visible = self.widget.props.visible + if widget is not self.widget and visible: + self.hide() + return False + + def hide(self): + self.set_text_view(None) + self.wrap_box.set_visible(False) + self.widget.hide() + + def set_text_view(self, textview): + self.textview = textview + if textview is not None: + self.search_context = GtkSource.SearchContext.new( + textview.get_buffer(), self.search_settings) + self.search_context.set_highlight(True) + else: + self.search_context = None + + def start_find(self, textview, text=None): + self.set_text_view(textview) + self.replace_label.hide() + self.replace_entry.hide() + self.hbuttonbox2.hide() + self.find_entry.get_style_context().remove_class("not-found") + if text: + self.find_entry.set_text(text) + self.widget.set_row_spacing(0) + self.widget.show() + self.find_entry.grab_focus() + + def start_find_next(self, textview): + self.set_text_view(textview) + if self.find_entry.get_text(): + self.on_find_next_button_clicked(self.find_next_button) + else: + self.start_find(self.textview) + + def start_find_previous(self, textview, text=None): + self.set_text_view(textview) + if self.find_entry.get_text(): + self.on_find_previous_button_clicked(self.find_previous_button) + else: + self.start_find(self.textview) + + def start_replace(self, textview, text=None): + self.set_text_view(textview) + self.find_entry.get_style_context().remove_class("not-found") + if text: + self.find_entry.set_text(text) + self.widget.set_row_spacing(6) + self.widget.show_all() + self.find_entry.grab_focus() + self.wrap_box.set_visible(False) + + def on_find_next_button_clicked(self, button): + self._find_text() + + def on_find_previous_button_clicked(self, button): + self._find_text(backwards=True) + + def on_replace_button_clicked(self, entry): + buf = self.textview.get_buffer() + oldsel = buf.get_selection_bounds() + match = self._find_text(0) + newsel = buf.get_selection_bounds() + # Only replace if there is an already-selected match at the cursor + if (match and oldsel and oldsel[0].equal(newsel[0]) and + oldsel[1].equal(newsel[1])): + self.search_context.replace( + newsel[0], newsel[1], self.replace_entry.get_text(), -1) + self._find_text(0) + + def on_replace_all_button_clicked(self, entry): + buf = self.textview.get_buffer() + saved_insert = buf.create_mark( + None, buf.get_iter_at_mark(buf.get_insert()), True) + self.search_context.replace_all(self.replace_entry.get_text(), -1) + if not saved_insert.get_deleted(): + buf.place_cursor(buf.get_iter_at_mark(saved_insert)) + self.textview.scroll_to_mark( + buf.get_insert(), 0.25, True, 0.5, 0.5) + + def on_find_entry_changed(self, entry): + self.find_entry.get_style_context().remove_class("not-found") + self._find_text(0) + + def _find_text(self, start_offset=1, backwards=False): + assert self.textview + assert self.search_context + buf = self.textview.get_buffer() + insert = buf.get_iter_at_mark(buf.get_insert()) + + start, end = buf.get_bounds() + self.wrap_box.set_visible(False) + if not backwards: + insert.forward_chars(start_offset) + match, start_iter, end_iter = self.search_context.forward(insert) + if match and (start_iter.get_offset() < insert.get_offset()): + self.wrap_box.set_visible(True) + else: + match, start_iter, end_iter = self.search_context.backward(insert) + if match and (start_iter.get_offset() > insert.get_offset()): + self.wrap_box.set_visible(True) + if match: + buf.place_cursor(start_iter) + buf.move_mark(buf.get_selection_bound(), end_iter) + self.textview.scroll_to_mark( + buf.get_insert(), 0.25, True, 0.5, 0.5) + self.find_entry.get_style_context().remove_class("not-found") + return True + else: + buf.place_cursor(buf.get_iter_at_mark(buf.get_insert())) + self.find_entry.get_style_context().add_class("not-found") + self.wrap_box.set_visible(False) diff --git a/pool/shard001/Python/0013428_mcstatus.py b/pool/shard001/Python/0013428_mcstatus.py new file mode 100644 index 0000000000000000000000000000000000000000..0a0ec5f2a83dc919a78ced19b06c9f8841e2380f --- /dev/null +++ b/pool/shard001/Python/0013428_mcstatus.py @@ -0,0 +1,75 @@ +# +# Copyright (C) 2016-2017 Kamran Mackey and contributors +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +"""Minecraft Status + +Minecraft Status is a plugin that retrieves the current +Minecraft server status, and then displays it once a user +sends the /mcstatus command. +""" + +import json + +import requests +from telegram import ParseMode +from telegram.ext.dispatcher import run_async + + +@run_async +def mc_status(_, update): + """ + This plugin fetches the status of the Minecraft/Mojang + servers and then posts the retrieved status information + as a Telegram message. + """ + mcstatus_baseurl = "https://status.mojang.com/check" + mcstatus_request = requests.get(mcstatus_baseurl).text + + try: + mcstatus_request + except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as error: + update.message.reply_text( + text="Unable to get Minecraft server status: {}".format(error)) + + # Take the JSON Mojang's status site gives me + # and turn it into a nice format. + mc_req = mcstatus_request.replace("}", "").replace( + "{", "").replace("]", "}").replace("[", "{") + data = json.loads(mc_req) + out = [] + + # Use a fancy loop so I don't have to update + # this when Mojang adds new servers. + green = [] + yellow = [] + red = [] + for server, status in list(data.items()): + if status == "green": + checkmark = "✅ " + green.append(checkmark + server) + elif status == "yellow": + yellow.append(server) + else: + red_circle = "🔴 " + red.append(red_circle + server) + + if green: + green.sort() + out.append("*The following Mojang services are up and running*:\n" + + "\n".join(green)) + if yellow: + yellow.sort() + out.append("*The following Mojang services are currently having issues*:\n" + + ",\n".join(yellow)) + if red: + red.sort() + out.append("*The following Mojang services are currently offline*:" + + ",\n".join(red)) + + update.message.reply_text(parse_mode=ParseMode.MARKDOWN, + disable_web_page_preview=True, + text=" ".join(out)) diff --git a/pool/shard001/Python/0013440_generate_nodeid_header.py b/pool/shard001/Python/0013440_generate_nodeid_header.py new file mode 100644 index 0000000000000000000000000000000000000000..c6086329a70f81a700a6fb764fd21e42b6b84d2f --- /dev/null +++ b/pool/shard001/Python/0013440_generate_nodeid_header.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +from __future__ import print_function +import sys +import argparse +from io import open + +parser = argparse.ArgumentParser() +parser.add_argument('statuscodes', help='path/to/Opc.Ua.NodeIds.csv') +parser.add_argument('outfile', help='outfile w/o extension') +parser.add_argument('namespace', help='NS0') +args = parser.parse_args() + +rows = [] +with open(args.statuscodes, mode="rt") as f: + lines = f.readlines() + for l in lines: + rows.append(tuple(l.strip().split(','))) + +fh = open(args.outfile + ".h", "wt", encoding='utf8') +def printh(string): + print(string, end=u'\n', file=fh) + +######################### +# Print the header file # +######################### + +printh(u'''/*--------------------------------------------------------- + * Autogenerated -- do not modify + * Generated from {0} with script {1} + *-------------------------------------------------------*/ + +#ifndef UA_NODEIDS_{2}_H_ +#define UA_NODEIDS_{2}_H_ + +/** + * Namespace Zero NodeIds + * ---------------------- + * Numeric identifiers of standard-defined nodes in namespace zero. The + * following definitions are autogenerated from the ``{0}`` file */ +'''.format(args.statuscodes, sys.argv[0], args.namespace)) + +for row in rows: + printh(u"#define UA_{namespace}ID_{name} {id} /* {description} */".format(namespace=args.namespace, name=row[0].upper(), id=row[1], description=row[2])) + +printh(u'''#endif /* UA_NODEIDS_{0}_H_ */ '''.format(args.namespace)) + +fh.close() diff --git a/pool/shard001/Python/0013442_boto_dynamodb.py b/pool/shard001/Python/0013442_boto_dynamodb.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa756187b9ed81ed05ef028925e26598464c47 --- /dev/null +++ b/pool/shard001/Python/0013442_boto_dynamodb.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +''' +Connection module for Amazon DynamoDB + +.. versionadded:: 2015.5.0 + +:configuration: This module accepts explicit DynamoDB credentials but can also + utilize IAM roles assigned to the instance trough Instance Profiles. + Dynamic credentials are then automatically obtained from AWS API and no + further configuration is necessary. More Information available at: + + .. code-block:: text + + http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html + + If IAM roles are not used you need to specify them either in a pillar or + in the minion's config file: + + .. code-block:: yaml + + keyid: GKTADJGHEIQSXMKKRBJ08H + key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs + + A region may also be specified in the configuration: + + .. code-block:: yaml + + region: us-east-1 + + If a region is not specified, the default is us-east-1. + + It's also possible to specify key, keyid and region via a profile, either + as a passed in dict, or as a string to pull from pillars or minion config:: + + .. code-block:: yaml + + myprofile: + keyid: GKTADJGHEIQSXMKKRBJ08H + key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs + region: us-east-1 + +:depends: boto +''' +# keep lint from choking on _get_conn and _cache_id +#pylint: disable=E0602 + +# Import Python libs +from __future__ import absolute_import +import logging +import time + +logger = logging.getLogger(__name__) +logging.getLogger('boto').setLevel(logging.INFO) + +# Import third party libs +import salt.ext.six as six +from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin +try: + #pylint: disable=unused-import + import boto + import boto.dynamodb2 + #pylint: enable=unused-import + from boto.dynamodb2.fields import HashKey, RangeKey + from boto.dynamodb2.fields import AllIndex, GlobalAllIndex + from boto.dynamodb2.table import Table + from boto.exception import JSONResponseError + HAS_BOTO = True +except ImportError: + HAS_BOTO = False + + +def __virtual__(): + ''' + Only load if boto libraries exist. + ''' + if not HAS_BOTO: + return False + __utils__['boto.assign_funcs'](__name__, 'dynamodb2', pack=__salt__) + return True + + +def create_table(table_name, region=None, key=None, keyid=None, profile=None, + read_capacity_units=None, write_capacity_units=None, + hash_key=None, hash_key_data_type=None, range_key=None, + range_key_data_type=None, local_indexes=None, + global_indexes=None): + ''' + Creates a DynamoDB table. + + CLI Example: + + .. code-block:: bash + + salt myminion boto_dynamodb.create_table table_name / + region=us-east-1 / + hash_key=id / + hash_key_data_type=N / + range_key=created_at / + range_key_data_type=N / + read_capacity_units=1 / + write_capacity_units=1 + ''' + schema = [] + primary_index_fields = [] + primary_index_name = '' + if hash_key: + hash_key_obj = HashKey(hash_key, data_type=hash_key_data_type) + schema.append(hash_key_obj) + primary_index_fields.append(hash_key_obj) + primary_index_name += hash_key + if range_key: + range_key_obj = RangeKey(range_key, data_type=range_key_data_type) + schema.append(range_key_obj) + primary_index_fields.append(range_key_obj) + primary_index_name += '_' + primary_index_name += range_key + primary_index_name += '_index' + throughput = { + 'read': read_capacity_units, + 'write': write_capacity_units + } + local_table_indexes = [] + if local_indexes: + # Add the table's key + local_table_indexes.append( + AllIndex(primary_index_name, parts=primary_index_fields) + ) + for index in local_indexes: + local_table_indexes.append(_extract_index(index)) + global_table_indexes = [] + if global_indexes: + for index in global_indexes: + global_table_indexes.append( + _extract_index(index, global_index=True) + ) + + conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) + + Table.create( + table_name, + schema=schema, + throughput=throughput, + indexes=local_table_indexes, + global_indexes=global_table_indexes, + connection=conn + ) + + # Table creation can take several seconds to propagate. + # We will check MAX_ATTEMPTS times. + MAX_ATTEMPTS = 30 + for i in range(MAX_ATTEMPTS): + if exists( + table_name, + region, + key, + keyid, + profile + ): + return True + else: + time.sleep(1) # sleep for one second and try again + return False + + +def exists(table_name, region=None, key=None, keyid=None, profile=None): + ''' + Check to see if a table exists. + + CLI Example: + + .. code-block:: bash + + salt myminion boto_dynamodb.exists table_name region=us-east-1 + ''' + try: + conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) + conn.describe_table(table_name) + except JSONResponseError as e: + if e.error_code == 'ResourceNotFoundException': + return False + raise + return True + + +def delete(table_name, region=None, key=None, keyid=None, profile=None): + ''' + Delete a DynamoDB table. + + CLI Example: + + .. code-block:: bash + + salt myminion boto_dynamodb.delete table_name region=us-east-1 + ''' + conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) + + table = Table(table_name, connection=conn) + table.delete() + + # Table deletion can take several seconds to propagate. + # We will retry MAX_ATTEMPTS times. + MAX_ATTEMPTS = 30 + for i in range(MAX_ATTEMPTS): + if not exists(table_name, region, key, keyid, profile): + return True + else: + time.sleep(1) # sleep for one second and try again + return False + + +def _extract_index(index_data, global_index=False): + ''' + Instantiates and returns an AllIndex object given a valid index + configuration + ''' + parsed_data = {} + keys = [] + + for key, value in six.iteritems(index_data): + for item in value: + for field, data in six.iteritems(item): + if field == 'hash_key': + parsed_data['hash_key'] = data + elif field == 'hash_key_data_type': + parsed_data['hash_key_data_type'] = data + elif field == 'range_key': + parsed_data['range_key'] = data + elif field == 'range_key_data_type': + parsed_data['range_key_data_type'] = data + elif field == 'name': + parsed_data['name'] = data + elif field == 'read_capacity_units': + parsed_data['read_capacity_units'] = data + elif field == 'write_capacity_units': + parsed_data['write_capacity_units'] = data + + if parsed_data['hash_key']: + keys.append( + HashKey( + parsed_data['hash_key'], + data_type=parsed_data['hash_key_data_type'] + ) + ) + if parsed_data['range_key']: + keys.append( + RangeKey( + parsed_data['range_key'], + data_type=parsed_data['range_key_data_type'] + ) + ) + if ( + global_index and + parsed_data['read_capacity_units'] and + parsed_data['write_capacity_units']): + parsed_data['throughput'] = { + 'read': parsed_data['read_capacity_units'], + 'write': parsed_data['write_capacity_units'] + } + if parsed_data['name'] and len(keys) > 0: + if global_index: + return GlobalAllIndex( + parsed_data['name'], + parts=keys, + throughput=parsed_data['throughput'] + ) + else: + return AllIndex( + parsed_data['name'], + parts=keys + ) diff --git a/pool/shard001/Python/0013443_user_prompts.py b/pool/shard001/Python/0013443_user_prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd7d582bd3d80a3d3affc4052bc933d75bcbca6 --- /dev/null +++ b/pool/shard001/Python/0013443_user_prompts.py @@ -0,0 +1,119 @@ +# META: timeout=long + +import pytest + +from tests.support.asserts import assert_error, assert_dialog_handled, assert_success + + +def is_element_enabled(session, element_id): + return session.transport.send( + "GET", + "session/{session_id}/element/{element_id}/enabled".format( + session_id=session.session_id, + element_id=element_id + ) + ) + + +@pytest.fixture +def check_user_prompt_closed_without_exception(session, create_dialog, inline): + def check_user_prompt_closed_without_exception(dialog_type, retval): + session.url = inline("") + element = session.find.css("#foo", all=False) + + create_dialog(dialog_type, text=dialog_type) + + response = is_element_enabled(session, element.id) + assert_success(response, False) + + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + + return check_user_prompt_closed_without_exception + + +@pytest.fixture +def check_user_prompt_closed_with_exception(session, create_dialog, inline): + def check_user_prompt_closed_with_exception(dialog_type, retval): + session.url = inline("") + element = session.find.css("#foo", all=False) + + create_dialog(dialog_type, text=dialog_type) + + response = is_element_enabled(session, element.id) + assert_error(response, "unexpected alert open") + + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + + return check_user_prompt_closed_with_exception + + +@pytest.fixture +def check_user_prompt_not_closed_but_exception(session, create_dialog, inline): + def check_user_prompt_not_closed_but_exception(dialog_type): + session.url = inline("") + element = session.find.css("#foo", all=False) + + create_dialog(dialog_type, text=dialog_type) + + response = is_element_enabled(session, element.id) + assert_error(response, "unexpected alert open") + + assert session.alert.text == dialog_type + session.alert.dismiss() + + return check_user_prompt_not_closed_but_exception + + +@pytest.mark.capabilities({"unhandledPromptBehavior": "accept"}) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) + + +@pytest.mark.capabilities({"unhandledPromptBehavior": "accept and notify"}) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) + + +@pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss"}) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) + + +@pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss and notify"}) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) + + +@pytest.mark.capabilities({"unhandledPromptBehavior": "ignore"}) +@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) +def test_ignore(check_user_prompt_not_closed_but_exception, dialog_type): + check_user_prompt_not_closed_but_exception(dialog_type) + + +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_default(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) diff --git a/pool/shard001/Python/0013448_igf_ms_team.py b/pool/shard001/Python/0013448_igf_ms_team.py new file mode 100644 index 0000000000000000000000000000000000000000..84030ab501168c5bab26c434bfeeec112862b701 --- /dev/null +++ b/pool/shard001/Python/0013448_igf_ms_team.py @@ -0,0 +1,154 @@ +import os,requests,json,time,base64 +from igf_data.utils.dbutils import read_json_data +from igf_data.utils.fileutils import check_file_path + +class IGF_ms_team: + def __init__(self,webhook_conf_file): + try: + webhook_conf = read_json_data(webhook_conf_file)[0] + except Exception as e: + raise ValueError( + "Failed to parse webhook config file {0}, error: {1}".\ + format(webhook_conf_file,e)) + self.webhook_conf = webhook_conf + + def post_message_with_mention(self, message, aad_id, name, email_id): + try: + webhook_url = self.webhook_conf.get('webhook_url') + json_data = { + "type": "message", + "attachments": [ + { + "contentType": "application/vnd.microsoft.card.adaptive", + "content": { + "type": "AdaptiveCard", + "body": [ + { + "type": "TextBlock", + "text": "Hi {0}. {1}".format(aad_id, message), + "wrap": True, + "width": "stretch" + } + ], + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "version": "1.0", + "msteams": { + "entities": [ + { + "type": "mention", + "text": "{0}".format(aad_id), + "mentioned": { + "id": email_id, + "name": name + } + } + ] + } + } + }] + } + r = \ + requests.post( + url=webhook_url, + json=json_data) + if r.status_code != 200: + raise ValueError( + "Failed to post message to team, error code: {0},{1}".\ + format(r.status_code,r.json())) + time.sleep(2) + except Exception as e: + raise ValueError( + 'Failed to post message with mention, error: {0}'.format(e)) + + + def post_image_to_team(self,image_path,message='',reaction=''): + ''' + A method for posting image file to MS team chanel + + :param image_path: An image file path + :param message: An optional message, default '' + :param reaction: A text for image reacion theme, default '' + ''' + try: + webhook_url = self.webhook_conf.get('webhook_url') + check_file_path(image_path) + encoded_image = base64.b64encode(open(image_path, "rb").read()).decode() + formatted_image = "data:image/png;base64,{0}".format(encoded_image) + if reaction !='' or reaction is not None: + if reaction == 'pass': + reaction = 'good' + elif reaction == 'fail': + reaction = 'attention' + elif reaction == 'sleep': + reaction = 'default' + if reaction == '': + reaction = 'default' + #json_data = { + # "@context": "https://schema.org/extensions", + # "@type": "MessageText", + # "themeColor": themeColor, + # "TextFormat":"markdown", + # "text": formatted_message} + json_data = { + "type":"message", + "attachments":[{ + "contentType":"application/vnd.microsoft.card.adaptive", + "contentUrl":None, + "content":{ + "$schema":"http://adaptivecards.io/schemas/adaptive-card.json", + "type":"AdaptiveCard", + "version":"1.2", + "body":[{ + "type": "Image", + "url": formatted_image + },{ + "type":"TextBlock", + "text":message, + "color":reaction + }] + } + }] + } + r = requests.post(url=webhook_url,json=json_data) + if r.status_code != 200: + raise ValueError( + "Failed to post message to team, error code: {0},{1}".\ + format(r.status_code,r.json())) + time.sleep(2) + except Exception as e: + raise ValueError('Failed to send image file to team, error: {0}, file: {1}'.\ + format(e,image_path)) + + + def post_message_to_team(self,message,reaction=''): + try: + webhook_url = self.webhook_conf.get('webhook_url') + formatted_message = '' + themeColor = '#FFFFFF' + if reaction !='' or reaction is not None: + if reaction == 'pass': + reaction = '🟢' + themeColor = '#00cc44' + elif reaction == 'fail': + reaction = '🔴' + themeColor = '#DC143C' + elif reaction == 'sleep': + reaction = '😴' + themeColor = '#000080' + formatted_message = "{0}; {1}".format(reaction,message) + else: + formatted_message = message + json_data = { + "@context": "https://schema.org/extensions", + "@type": "MessageText", + "themeColor": themeColor, + "TextFormat":"markdown", + "text": formatted_message} + r = requests.post(url=webhook_url,json=json_data) + if r.status_code != 200: + raise ValueError( + "Failed to post message to team, error code: {0},{1}".\ + format(r.status_code,r.json())) + time.sleep(2) + except Exception as e: + raise ValueError('Failed to send message to team, error: {0}'.format(e)) diff --git a/pool/shard001/Python/0013460_test_bytecount.py b/pool/shard001/Python/0013460_test_bytecount.py new file mode 100644 index 0000000000000000000000000000000000000000..dc513913a0f4d0e0e390609b8f3608a03bf47636 --- /dev/null +++ b/pool/shard001/Python/0013460_test_bytecount.py @@ -0,0 +1,97 @@ +import unittest + +from myhdl import * +from myhdl_lib.stream import bytecount +import myhdl_lib.simulation as sim + +import random +from math import log, floor, ceil + + +class TestBytecount(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.simulators = ["myhdl", "icarus"] + + def testName(self): + ''' BYTECOUNT: ''' + MAX_NUM_BYTES = 200 + BYTES_PER_WORD = [1,2,3,4,5] + + getDut = sim.DUTer() + + def testbench(BYTES_PER_WORD): + MTY_WIDTH = int(floor(log(BYTES_PER_WORD,2))) + 1 + COUNT_WIDTH = int(floor(log(MAX_NUM_BYTES,2))) + 1 + + clk = sim.Clock(val=0, period=10, units="ns") + rst = sim.ResetSync(clk=clk, val=0, active=1) + + rx_vld = Signal(bool(0)) + rx_sop = Signal(bool(0)) + rx_eop = Signal(bool(0)) + rx_dat = Signal(intbv(0)[BYTES_PER_WORD*8:]) + rx_mty = Signal(intbv(0)[MTY_WIDTH:]) + count = Signal(intbv(0)[COUNT_WIDTH:]) + + argl = {"rst":rst, + "clk":clk, + "rx_vld":rx_vld, + "rx_sop":rx_sop, + "rx_eop":rx_eop, + "rx_dat":rx_dat, + "rx_mty":rx_mty, + "count":count, + "MAX_BYTES":MAX_NUM_BYTES} + + dut = getDut(bytecount, **argl) + clkgen = clk.gen() + + @instance + def _stim(): + rx_vld.next = 0 + rx_sop.next = 0 + rx_eop.next = 0 + rx_dat.next = 0 + rx_mty.next = 0 + yield rst.pulse(10) + yield clk.posedge + assert 0==count, "bytecount: expected {}, detected {}".format(0, count) + + for _ in range(10): + bytes = random.randint(1,MAX_NUM_BYTES) + words = int(ceil(float(bytes)/BYTES_PER_WORD)) + empty_n = bytes%BYTES_PER_WORD + empty = BYTES_PER_WORD - empty_n + C = 0 + for i in range(words): + rx_vld.next = 1 + rx_sop.next = (i==0) + rx_eop.next = (i==words-1) + rx_dat.next = random.randint(0,2**BYTES_PER_WORD*8-1) + rx_mty.next = empty if i==words-1 else 0 + C = C + (empty_n if i==words-1 else BYTES_PER_WORD) + yield clk.posedge + yield delay(1) + assert C==count, "bytecount: expected {}, detected {}".format(C, count) + # Gap + rx_vld.next = 0 + for _ in range(random.randint(0,3)): + yield clk.posedge + + yield clk.posedge + raise StopSimulation + return instances() + + for s in self.simulators: + getDut.selectSimulator(s) + for BPW in BYTES_PER_WORD: + tb = testbench(BPW) + Simulation(tb).run() + del tb + + +if __name__ == "__main__": + #import sys;sys.argv = ['', 'Test.testName'] + unittest.main() diff --git a/pool/shard001/Python/0013466_splat.py b/pool/shard001/Python/0013466_splat.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e12e10b4a0c31e60d9920adba6d80237c05ec1 --- /dev/null +++ b/pool/shard001/Python/0013466_splat.py @@ -0,0 +1,91 @@ +"""Support for Splat as a bug tracker.""" + +from __future__ import unicode_literals + +import logging + +from django import forms +from django.utils.translation import ugettext_lazy as _ + +from reviewboard.hostingsvcs.bugtracker import BugTracker +from reviewboard.hostingsvcs.forms import HostingServiceForm +from reviewboard.hostingsvcs.service import HostingService + + +class SplatForm(HostingServiceForm): + """The Splat bug tracker configuration form.""" + + splat_org_name = forms.SlugField( + label=_('Splat Organization Name'), + max_length=64, + required=True, + widget=forms.TextInput(attrs={'size': 60})) + + +class Splat(HostingService, BugTracker): + """The Splat bug tracker. + + Splat is a SaaS bugtracker hosted at https://hellosplat.com. It is owned + and run by Beanbag, Inc. and is used as the official bug tracker for + Review Board. + """ + + name = 'Splat' + form = SplatForm + bug_tracker_field = \ + 'https://hellosplat.com/s/%(splat_org_name)s/tickets/%%s/' + supports_bug_trackers = True + + def get_bug_info_uncached(self, repository, bug_id): + """Return the bug info from the server. + + Args: + repository (reviewboard.scmtools.model.Repository): + The repository that is using Splat as a bug tracker. + + bug_id (unicode): + The bug identifier. + + Returns: + dict: + A dictionary of the bug information. + """ + result = { + 'summary': '', + 'description': '', + 'description_text_format': '', + 'status': '', + } + + url = ( + 'https://hellosplat.com/api/orgs/%s/tickets/%s/?only-fields=status' + ',summary,text,text_format' + % (repository.extra_data['bug_tracker-splat_org_name'], bug_id) + ) + + try: + rsp = self.client.json_get(url)[0] + ticket = rsp['ticket'] + except Exception as e: + logging.warning('Unable to fetch Splat data from %s: %s', + url, e, exc_info=True) + else: + text = ticket['text'] + + # Normalize the text format. For Splat, this is going to look + # a bit silly, but we don't want to make the assumption in code + # that we can just pass through the text format here. + text_format = { + 'plain': 'plain', + 'markdown': 'markdown', + 'html': 'html', + }.get(ticket['text_format'], 'plain') + + result = { + 'description': text, + 'description_text_format': text_format, + 'status': ticket['status'], + 'summary': ticket['summary'], + } + + return result diff --git a/pool/shard001/Python/0013467_paint_select.py b/pool/shard001/Python/0013467_paint_select.py new file mode 100644 index 0000000000000000000000000000000000000000..9c9cb1fbdb77745b744fbaeacb6ac7acb4c606a2 --- /dev/null +++ b/pool/shard001/Python/0013467_paint_select.py @@ -0,0 +1,163 @@ +# [h] paint and select glyphs by color + +import hTools2.modules.color +reload(hTools2.modules.color) + +from mojo.roboFont import CurrentFont, CurrentGlyph +from vanilla import * +from AppKit import NSColor +from hTools2 import hDialog +from hTools2.modules.color import random_color, clear_color, convert_to_nscolor +from hTools2.modules.fontutils import get_glyphs +from hTools2.modules.messages import no_font_open, no_glyph_selected + +# objects + +class paintGlyphsDialog(hDialog): + + '''A dialog to apply a color to the selected glyph boxes, and to select glyphs by color. + + .. image:: imgs/glyphs/paint-select.png + + ''' + + # attributes + + mark_color = random_color() + + # methods + + def __init__(self): + self.title = 'color' + self.height = self.button_height*5 + self.padding*5 - 1 + self.w = FloatingWindow((self.width, self.height), self.title) + x = y = p = self.padding + # get color + self.w.button_get = SquareButton( + (x, y, -p, self.button_height), + "get", + callback=self.get_color_callback, + sizeStyle=self.size_style) + # color swatch + y += self.button_height + p + self.w.mark_color = ColorWell( + (x, y, -p, self.button_height), + color=NSColor.colorWithCalibratedRed_green_blue_alpha_(*self.mark_color)) + # paint button + y += self.button_height - 1 + self.w.button_paint = SquareButton( + (x, y, -p, self.button_height), + "paint", + callback=self.paint_callback, + sizeStyle=self.size_style) + # select button + y += self.button_height - 1 + p + self.w.button_select = SquareButton( + (x, y, -p, self.button_height), + "select", + callback=self.select_callback, + sizeStyle=self.size_style) + # clear button + y += self.button_height + p + self.w.button_clear = SquareButton( + (x, y, -p, self.button_height), + "clear", + callback=self.clear_callback, + sizeStyle=self.size_style) + # open window + self.w.open() + + # callbacks + + def get_color_callback(self, sender): + f = CurrentFont() + if f is not None: + glyph_names = get_glyphs(f) + if len(glyph_names) > 0: + g = f[glyph_names[0]] + # get glyph color + color = g.mark + print '%s: %s\n' % (g.name, color) + # convert rgba to NSColor + nscolor = convert_to_nscolor(*color) + # set swatch color + self.w.mark_color.set(nscolor) + # no glyph selected + else: + print no_glyph_selected + # no font open + else: + print no_font_open + + def paint_callback(self, sender): + f = CurrentFont() + if f is not None: + _mark_color = self.w.mark_color.get() + _mark_color = ( + _mark_color.redComponent(), + _mark_color.greenComponent(), + _mark_color.blueComponent(), + _mark_color.alphaComponent(), + ) + glyph_names = get_glyphs(f) + if len(glyph_names) > 0: + print 'painting selected glyphs...\n' + print '\tcolor: %s %s %s %s' % _mark_color + print + print '\t', + for glyph_name in glyph_names: + print glyph_name, + f[glyph_name].prepareUndo('paint glyph') + f[glyph_name].mark = _mark_color + f[glyph_name].performUndo() + print + print '\n...done.\n' + # no glyph selected + else: + print no_glyph_selected + # no font open + else: + print no_font_open + + def select_callback(self, sender): + f = CurrentFont() + if f is not None: + glyph_names = get_glyphs(f) + if len(glyph_names) > 0: + glyph_name = get_glyphs(f)[0] + color = f[glyph_name].mark + print 'selecting glyphs:\n' + print '\t', + glyph_names = [] + for glyph in f: + if glyph.mark == color: + print glyph.name, + glyph_names.append(glyph.name) + f.selection = glyph_names + print + print '\n...done.\n' + # no glyph selected + else: + print no_glyph_selected + # no font open + else: + print no_font_open + + def clear_callback(self, sender): + f = CurrentFont() + if f is not None: + glyph_names = get_glyphs(f) + if len(glyph_names) > 0: + print 'clearing colors from selected glyphs...\n' + print '\t\t', + for glyph_name in glyph_names: + print glyph_name, + clear_color(f[glyph_name]) + print + print '\n...done.\n' + # no glyph selected + else: + print no_glyph_selected + # no font open + else: + print no_font_open diff --git a/pool/shard001/Python/0013477_metrics.py b/pool/shard001/Python/0013477_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c465debdba42ec144642e8b8878d01e863c5b2 --- /dev/null +++ b/pool/shard001/Python/0013477_metrics.py @@ -0,0 +1,259 @@ +from __future__ import absolute_import + +import logging +import sys +import time +import threading + +from kafka.metrics import AnonMeasurable, KafkaMetric, MetricConfig, MetricName +from kafka.metrics.stats import Sensor + +logger = logging.getLogger(__name__) + + +class Metrics(object): + """ + A registry of sensors and metrics. + + A metric is a named, numerical measurement. A sensor is a handle to + record numerical measurements as they occur. Each Sensor has zero or + more associated metrics. For example a Sensor might represent message + sizes and we might associate with this sensor a metric for the average, + maximum, or other statistics computed off the sequence of message sizes + that are recorded by the sensor. + + Usage looks something like this: + # set up metrics: + metrics = Metrics() # the global repository of metrics and sensors + sensor = metrics.sensor('message-sizes') + metric_name = MetricName('message-size-avg', 'producer-metrics') + sensor.add(metric_name, Avg()) + metric_name = MetricName('message-size-max', 'producer-metrics') + sensor.add(metric_name, Max()) + + # as messages are sent we record the sizes + sensor.record(message_size); + """ + def __init__(self, default_config=None, reporters=None, + enable_expiration=False): + """ + Create a metrics repository with a default config, given metric + reporters and the ability to expire eligible sensors + + Arguments: + default_config (MetricConfig, optional): The default config + reporters (list of AbstractMetricsReporter, optional): + The metrics reporters + enable_expiration (bool, optional): true if the metrics instance + can garbage collect inactive sensors, false otherwise + """ + self._lock = threading.RLock() + self._config = default_config or MetricConfig() + self._sensors = {} + self._metrics = {} + self._children_sensors = {} + self._reporters = reporters or [] + for reporter in self._reporters: + reporter.init([]) + + if enable_expiration: + def expire_loop(): + while True: + # delay 30 seconds + time.sleep(30) + self.ExpireSensorTask.run(self) + metrics_scheduler = threading.Thread(target=expire_loop) + # Creating a daemon thread to not block shutdown + metrics_scheduler.daemon = True + metrics_scheduler.start() + + self.add_metric(self.metric_name('count', 'kafka-metrics-count', + 'total number of registered metrics'), + AnonMeasurable(lambda config, now: len(self._metrics))) + + @property + def config(self): + return self._config + + @property + def metrics(self): + """ + Get all the metrics currently maintained and indexed by metricName + """ + return self._metrics + + def metric_name(self, name, group, description='', tags=None): + """ + Create a MetricName with the given name, group, description and tags, + plus default tags specified in the metric configuration. + Tag in tags takes precedence if the same tag key is specified in + the default metric configuration. + + Arguments: + name (str): The name of the metric + group (str): logical group name of the metrics to which this + metric belongs + description (str, optional): A human-readable description to + include in the metric + tags (dict, optionals): additional key/value attributes of + the metric + """ + combined_tags = dict(self.config.tags) + combined_tags.update(tags or {}) + return MetricName(name, group, description, combined_tags) + + def get_sensor(self, name): + """ + Get the sensor with the given name if it exists + + Arguments: + name (str): The name of the sensor + + Returns: + Sensor: The sensor or None if no such sensor exists + """ + if not name: + raise ValueError('name must be non-empty') + return self._sensors.get(name, None) + + def sensor(self, name, config=None, + inactive_sensor_expiration_time_seconds=sys.maxsize, + parents=None): + """ + Get or create a sensor with the given unique name and zero or + more parent sensors. All parent sensors will receive every value + recorded with this sensor. + + Arguments: + name (str): The name of the sensor + config (MetricConfig, optional): A default configuration to use + for this sensor for metrics that don't have their own config + inactive_sensor_expiration_time_seconds (int, optional): + If no value if recorded on the Sensor for this duration of + time, it is eligible for removal + parents (list of Sensor): The parent sensors + + Returns: + Sensor: The sensor that is created + """ + sensor = self.get_sensor(name) + if sensor: + return sensor + + with self._lock: + sensor = self.get_sensor(name) + if not sensor: + sensor = Sensor(self, name, parents, config or self.config, + inactive_sensor_expiration_time_seconds) + self._sensors[name] = sensor + if parents: + for parent in parents: + children = self._children_sensors.get(parent) + if not children: + children = [] + self._children_sensors[parent] = children + children.append(sensor) + logger.debug('Added sensor with name %s', name) + return sensor + + def remove_sensor(self, name): + """ + Remove a sensor (if it exists), associated metrics and its children. + + Arguments: + name (str): The name of the sensor to be removed + """ + sensor = self._sensors.get(name) + if sensor: + child_sensors = None + with sensor._lock: + with self._lock: + val = self._sensors.pop(name, None) + if val and val == sensor: + for metric in sensor.metrics: + self.remove_metric(metric.metric_name) + logger.debug('Removed sensor with name %s', name) + child_sensors = self._children_sensors.pop(sensor, None) + if child_sensors: + for child_sensor in child_sensors: + self.remove_sensor(child_sensor.name) + + def add_metric(self, metric_name, measurable, config=None): + """ + Add a metric to monitor an object that implements measurable. + This metric won't be associated with any sensor. + This is a way to expose existing values as metrics. + + Arguments: + metricName (MetricName): The name of the metric + measurable (AbstractMeasurable): The measurable that will be + measured by this metric + config (MetricConfig, optional): The configuration to use when + measuring this measurable + """ + # NOTE there was a lock here, but i don't think it's needed + metric = KafkaMetric(metric_name, measurable, config or self.config) + self.register_metric(metric) + + def remove_metric(self, metric_name): + """ + Remove a metric if it exists and return it. Return None otherwise. + If a metric is removed, `metric_removal` will be invoked + for each reporter. + + Arguments: + metric_name (MetricName): The name of the metric + + Returns: + KafkaMetric: the removed `KafkaMetric` or None if no such + metric exists + """ + with self._lock: + metric = self._metrics.pop(metric_name, None) + if metric: + for reporter in self._reporters: + reporter.metric_removal(metric) + return metric + + def add_reporter(self, reporter): + """Add a MetricReporter""" + with self._lock: + reporter.init(list(self.metrics.values())) + self._reporters.append(reporter) + + def register_metric(self, metric): + with self._lock: + if metric.metric_name in self.metrics: + raise ValueError('A metric named "%s" already exists, cannot' + ' register another one.' % metric.metric_name) + self.metrics[metric.metric_name] = metric + for reporter in self._reporters: + reporter.metric_change(metric) + + class ExpireSensorTask(object): + """ + This iterates over every Sensor and triggers a remove_sensor + if it has expired. Package private for testing + """ + @staticmethod + def run(metrics): + items = list(metrics._sensors.items()) + for name, sensor in items: + # remove_sensor also locks the sensor object. This is fine + # because synchronized is reentrant. There is however a minor + # race condition here. Assume we have a parent sensor P and + # child sensor C. Calling record on C would cause a record on + # P as well. So expiration time for P == expiration time for C. + # If the record on P happens via C just after P is removed, + # that will cause C to also get removed. Since the expiration + # time is typically high it is not expected to be a significant + # concern and thus not necessary to optimize + with sensor._lock: + if sensor.has_expired(): + logger.debug('Removing expired sensor %s', name) + metrics.remove_sensor(name) + + def close(self): + """Close this metrics repository.""" + for reporter in self._reporters: + reporter.close() diff --git a/pool/shard001/Python/0013484_FeatureExtractor.py b/pool/shard001/Python/0013484_FeatureExtractor.py new file mode 100644 index 0000000000000000000000000000000000000000..849b26fcbfffd256897820c968db1aba7b08a501 --- /dev/null +++ b/pool/shard001/Python/0013484_FeatureExtractor.py @@ -0,0 +1,61 @@ +import numpy as np +from scipy.spatial import distance +speed = 3 + +def getAvgHeight(data): + try: + return np.mean(data[0 5: + continue + + side += euclidean_distance/2 + #print "euclidean distance: ", euclidean_distance, " side: " , side + + end = data[size - 1,1] + circumference = beg + end + 2 * side + return circumference + except ValueError: + return 0 + +def timeToDistance(sampling_rate): + try: + distancePerMillisecond = float(speed) *100000 / (3600*1000) + distance = 1000/sampling_rate * distancePerMillisecond + return distance + except ValueError: + return 0 \ No newline at end of file diff --git a/pool/shard001/Python/0013488_utils.py b/pool/shard001/Python/0013488_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9085cda9f65ef7f8b4f87cd26080854793fb945c --- /dev/null +++ b/pool/shard001/Python/0013488_utils.py @@ -0,0 +1,124 @@ +# Copyright 2015 Cloudbase Solutions. +# 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 os +import socket + +from neutron_lib.utils import runtime +from oslo_config import cfg +from oslo_log import log as logging +from oslo_utils import timeutils + +from neutron.conf.agent import common as config +from neutron.conf.agent.database import agents_db + + +if os.name == 'nt': + from neutron.agent.windows import utils +else: + from neutron.agent.linux import utils + + +LOG = logging.getLogger(__name__) +config.register_root_helper(cfg.CONF) +agents_db.register_db_agents_opts() + +INTERFACE_NAMESPACE = 'neutron.interface_drivers' + + +create_process = utils.create_process +kill_process = utils.kill_process +execute = utils.execute +get_root_helper_child_pid = utils.get_root_helper_child_pid +pid_invoked_with_cmdline = utils.pid_invoked_with_cmdline + + +def load_interface_driver(conf, get_networks_callback=None): + """Load interface driver for agents like DHCP or L3 agent. + + :param conf: Driver configuration object + :param get_networks_callback: A callback to get network information. + This will be passed as additional keyword + argument to the interface driver. + :raises SystemExit of 1 if driver cannot be loaded + """ + + try: + loaded_class = runtime.load_class_by_alias_or_classname( + INTERFACE_NAMESPACE, conf.interface_driver) + return loaded_class(conf, get_networks_callback=get_networks_callback) + except ImportError: + LOG.error("Error loading interface driver '%s'", + conf.interface_driver) + raise SystemExit(1) + + +def is_agent_down(heart_beat_time): + return timeutils.is_older_than(heart_beat_time, + cfg.CONF.agent_down_time) + + +def get_hypervisor_hostname(): + """Get hypervisor hostname + + This logic is implemented following the logic of virGetHostnameImpl + in libvirt. + """ + hypervisor_hostname = socket.gethostname() + if (hypervisor_hostname.startswith('localhost') or + '.' in hypervisor_hostname): + return hypervisor_hostname + + try: + addrinfo = socket.getaddrinfo(host=hypervisor_hostname, + port=None, + family=socket.AF_UNSPEC, + flags=socket.AI_CANONNAME) + # getaddrinfo returns a list of 5-tuples with; + # (family, type, proto, canonname, sockaddr) + if (addrinfo and addrinfo[0][3] and + not addrinfo[0][3].startswith('localhost')): + return addrinfo[0][3] + except OSError: + pass + + return hypervisor_hostname + + +# TODO(bence romsics): rehome this to neutron_lib.placement.utils +def default_rp_hypervisors(hypervisors, device_mappings, + default_hypervisor=None): + """Fill config option 'resource_provider_hypervisors' with defaults. + + Default hypervisor names to socket.gethostname() unless default_hypervisor + is set. + + :param hypervisors: Config option 'resource_provider_hypervisors' + as parsed by oslo.config, that is a dict with keys of physical devices + and values of hypervisor names. + :param device_mappings: Device mappings standardized to the list-valued + format. + :param default_hypervisor: Default hypervisor hostname. + """ + _default_hypervisor = default_hypervisor or get_hypervisor_hostname() + + rv = {} + for _physnet, devices in device_mappings.items(): + for device in devices: + if device in hypervisors: + rv[device] = hypervisors[device] + else: + rv[device] = _default_hypervisor + return rv diff --git a/pool/shard001/Python/0013494_socialaccount.py b/pool/shard001/Python/0013494_socialaccount.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7cd8ec0f0fa72d2570abfdc25d7c76ac7e186a --- /dev/null +++ b/pool/shard001/Python/0013494_socialaccount.py @@ -0,0 +1,93 @@ +from django.template.defaulttags import token_kwargs +from django import template + +from allauth.socialaccount import providers +from allauth.utils import get_request_param + +register = template.Library() + + +class ProviderLoginURLNode(template.Node): + def __init__(self, provider_id, params): + self.provider_id_var = template.Variable(provider_id) + self.params = params + + def render(self, context): + provider_id = self.provider_id_var.resolve(context) + request = context['request'] + provider = providers.registry.by_id(provider_id, request) + query = dict([(str(name), var.resolve(context)) for name, var + in self.params.items()]) + auth_params = query.get('auth_params', None) + scope = query.get('scope', None) + process = query.get('process', None) + if scope is '': + del query['scope'] + if auth_params is '': + del query['auth_params'] + if 'next' not in query: + next = get_request_param(request, 'next') + if next: + query['next'] = next + elif process == 'redirect': + query['next'] = request.get_full_path() + else: + if not query['next']: + del query['next'] + # get the login url and append query as url parameters + return provider.get_login_url(request, **query) + + +@register.tag +def provider_login_url(parser, token): + """ + {% provider_login_url "facebook" next=bla %} + {% provider_login_url "openid" openid="http://me.yahoo.com" next=bla %} + """ + bits = token.split_contents() + provider_id = bits[1] + params = token_kwargs(bits[2:], parser, support_legacy=False) + return ProviderLoginURLNode(provider_id, params) + + +class ProvidersMediaJSNode(template.Node): + def render(self, context): + request = context['request'] + ret = '\n'.join([p.media_js(request) + for p in providers.registry.get_list(request)]) + return ret + + +@register.tag +def providers_media_js(parser, token): + return ProvidersMediaJSNode() + + +@register.assignment_tag +def get_social_accounts(user): + """ + {% get_social_accounts user as accounts %} + + Then: + {{accounts.twitter}} -- a list of connected Twitter accounts + {{accounts.twitter.0}} -- the first Twitter account + {% if accounts %} -- if there is at least one social account + """ + accounts = {} + for account in user.socialaccount_set.all().iterator(): + providers = accounts.setdefault(account.provider, []) + providers.append(account) + return accounts + + +@register.assignment_tag +def get_providers(): + """ + Returns a list of social authentication providers. + + Usage: `{% get_providers as socialaccount_providers %}`. + + Then within the template context, `socialaccount_providers` will hold + a list of social providers configured for the current site. + """ + return providers.registry.get_list() diff --git a/pool/shard001/Python/0013497_main.py b/pool/shard001/Python/0013497_main.py new file mode 100644 index 0000000000000000000000000000000000000000..739bfdf4048cb82f93a8802e92cdd8f83aba1898 --- /dev/null +++ b/pool/shard001/Python/0013497_main.py @@ -0,0 +1,183 @@ +# Copyright 2014 Dan Kilman +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from StringIO import StringIO + +import argh + +import pysource +from pysource import daemonizer +from pysource import client +from pysource import config + + +class DaemonCommands(object): + """Daemon related commands""" + + namespace = 'daemon' + + @staticmethod + def start(): + """start the daemon process""" + started = daemonizer.start() + if not started: + return 'daemon already started' + + @staticmethod + def stop(): + """stop the daemon process""" + stopped = daemonizer.stop() + if stopped: + return 'daemon stopped' + else: + return 'daemon not running' + + @staticmethod + def restart(): + """restart the daemon process""" + daemonizer.restart() + + @staticmethod + def status(): + """check the daemon process status""" + status, pid = daemonizer.status() + if status == daemonizer.STATUS_STOPPED: + return 'daemon is (probably) stopped' + elif status == daemonizer.STATUS_CORRUPTED: + if pid: + return 'daemon pidfile exists but process does not seem ' \ + 'to be running (pid: {0}). you should probably clean ' \ + 'the files in {1} and manually check if there' \ + ' is a daemon running somewhere'\ + .format(pid, config.pysource_dir) + else: + return 'daemon seems to be in an unstable state. manually ' \ + 'remove the files in {0} and kill leftover daemon ' \ + 'processes (if there are any)'\ + .format(config.pysource_dir) + else: + return 'daemon is (probably) running (pid: {0})'.format(pid) + + @classmethod + def commands(cls): + return [cls.start, cls.stop, cls.restart, cls.status] + + +def list_registered(): + """list all functions currently registered""" + descriptors = client.list_registered() + if len(descriptors) == 0: + yield 'no functions registered' + else: + yield 'registered functions:' + for descriptor in descriptors: + name = descriptor['name'] + piped = descriptor['piped'] + suffix = ' (piped)' if piped else '' + yield '{}{}'.format(name, suffix) + + +def update_env(verbose=False): + """ + update environment variables at the daemon with the current client + environment + """ + status = client.update_env() + if status != 'updated': + raise pysource.error('failed updating environment') + if verbose: + return 'environment updated' + + +def source_registered(verbose=False): + """source all functions currently registered""" + return client.source_registered(verbose=verbose) + + +@argh.arg('function_name', help='the name of the function to source') +def source_named(function_name, piped=False, verbose=False): + """source a function named by the first positional argument""" + return client.source_named(function_name, + piped=piped, + verbose=verbose) + + +@argh.arg('def_content', help='the function definition itself') +def source_def(def_content, piped=False, verbose=False): + """source an inline function definition""" + return client.source_def(def_content, + piped=piped, + verbose=verbose) + + +@argh.arg('content', help='the code to execute at the daemon') +def source_inline(content, verbose=False): + """ + execute arbitrary code at the daemon. if code contains function + definitions, they will be sourced at the client + """ + return client.source_content(content, + verbose=verbose) + + +@argh.arg('source_path', help='the path to the file to source') +def source(source_path, verbose=False): + """source a file by its path""" + return client.source_path(source_path, + verbose=verbose) + + +@argh.arg('function_name', help='the name of the function to run') +def run(function_name, *args): + """run the function named by the first positional argument""" + result = client.run_function(function_name, args) + if result: + return result + + +@argh.arg('function_name', help='the name of the function to run') +def run_piped(function_name, *args): + """ + run the function named by the first positional argument as a piped + function + """ + client.run_piped_function(function_name, args) + + +def main(): + errors = StringIO() + parser = argh.ArghParser() + argh.add_commands(parser, [ + source, + run, + run_piped, + list_registered, + source_registered, + source_named, + source_def, + source_inline, + update_env + ], ) + argh.add_commands(parser, + functions=DaemonCommands.commands(), + namespace=DaemonCommands.namespace, + title=DaemonCommands.__doc__) + argh.dispatch(parser, completion=False, errors_file=errors) + if errors.len > 0: + sys.exit(errors.getvalue().strip()) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0013500_wiktionary-example.py b/pool/shard001/Python/0013500_wiktionary-example.py new file mode 100644 index 0000000000000000000000000000000000000000..f12b7c906395129a6364ce14f07988cfaa3498c5 --- /dev/null +++ b/pool/shard001/Python/0013500_wiktionary-example.py @@ -0,0 +1,9 @@ + +from wiktionaryparser import WiktionaryParser +parser = WiktionaryParser() +word = parser.fetch('test') +another_word = parser.fetch('test', 'french') +parser.set_default_language('french') +parser.exclude_part_of_speech('noun') +parser.include_relation('alternative forms') +print(word) diff --git a/pool/shard001/Python/0013516_storage.py b/pool/shard001/Python/0013516_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..14f7039753d35a8f453362a2551cd958b70241d5 --- /dev/null +++ b/pool/shard001/Python/0013516_storage.py @@ -0,0 +1,49 @@ +# -*- coding:utf-8 -*- + +""" +mongodb访问 +""" + +from motor import motor_asyncio +from . import config +import pymongo + + +_db_conn = None + + +async def create_connection(host, port, database, user, password, replicaset='', min_pool_size=1, max_pool_size=5): + client = motor_asyncio.AsyncIOMotorClient(host, port, replicaset=replicaset, minPoolSize=min_pool_size, maxPoolSize=max_pool_size) + db = client['admin'] + await db.authenticate(user, password) + db = client[database] + return db + + +async def create_connection_of_config(): + cfg = config.get_mongodb_config() + host = cfg['host'] + port = cfg['port'] + password = cfg['password'] + user = cfg['user'] + db = cfg['db'] + replicaset = cfg['replicaset'] + min_pool_size = cfg['min_pool_size'] + max_pool_size = cfg['max_pool_size'] + return await create_connection(host, port, db, user, password, replicaset, min_pool_size, max_pool_size) + + +async def initialize(): + global _db_conn + _db_conn = await create_connection_of_config() + + +def get_connection(): + return _db_conn + + +def get_database(): + return _db_conn + + + diff --git a/pool/shard001/Python/0013521_run_backend.py b/pool/shard001/Python/0013521_run_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..dce7d830c08306bc634da2c7a9933b6f06707e34 --- /dev/null +++ b/pool/shard001/Python/0013521_run_backend.py @@ -0,0 +1,24 @@ +#!venv/bin/python +from flask.ext.script import Manager +from backend import app,db +from flask.ext.migrate import Migrate, MigrateCommand + +app.host = '0.0.0.0' +app.debug = False + +migrate= Migrate(app,db) +manager = Manager(app) +manager.add_command('db',MigrateCommand) + +@manager.command +def runapp(debug=True): + if debug: + host = '0.0.0.0' + else: + host = '127.0.0.1' + return app.run(debug=debug,host=host,port=8080) + +#app.run(debug=True) +if __name__ == "__main__": + db.create_all() + manager.run() \ No newline at end of file diff --git a/pool/shard001/Python/0013522_serviceclass.py b/pool/shard001/Python/0013522_serviceclass.py new file mode 100644 index 0000000000000000000000000000000000000000..42685685325621f0e4ca19d2f2fdf8c00f485bbc --- /dev/null +++ b/pool/shard001/Python/0013522_serviceclass.py @@ -0,0 +1,27 @@ +import os +from django.db import models +from core.models import PlCoreBase + +def get_default_serviceclass(): + try: + return ServiceClass.objects.get(name="Best Effort") + except ServiceClass.DoesNotExist: + return None + +class ServiceClass(PlCoreBase): + name = models.CharField(max_length=32) + description = models.CharField(max_length=255) + commitment = models.IntegerField(default=365) + membershipFee = models.IntegerField(default=0) + membershipFeeMonths = models.IntegerField(default=12) + upgradeRequiresApproval = models.BooleanField(default=False) + upgradeFrom = models.ManyToManyField('self', blank=True, null=True) + + class Meta(PlCoreBase.Meta): + verbose_name_plural = "Service classes" + + def __unicode__(self): return u'%s' % (self.name) + + def save_by_user(self, user, *args, **kwds): + if self.can_update(user): + super(ServiceClass, self).save(*args, **kwds) diff --git a/pool/shard001/Python/0013524_model_in_rnn.py b/pool/shard001/Python/0013524_model_in_rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2f77aac34083ae65645c779eef4132303893f7 --- /dev/null +++ b/pool/shard001/Python/0013524_model_in_rnn.py @@ -0,0 +1,106 @@ +# Copyright 2017 The Chenmich Authors. 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. +# ============================================================================== +''' This modular is for model +''' +import datetime +import tensorflow as tf +import numpy as np +from matplotlib import pyplot as pyl +import data_reader as dr + + +#model parameters +BATCH_SIZE = 5 +NUM_BATCH = 2000 +SEQUENCE_LENGTH = 200 +FEATURE_SIZE = 5 +MU = 1.401157 +INIT_VALUE = 0.618 + +NUM_UNITS = 12 +NUM_CELL_STACK = 3 +ECHO = 400 +def printFn(content): + for _ in range(10): + print(content) +sess = tf.Session() +#model +cell = tf.contrib.rnn.BasicLSTMCell(num_units=NUM_UNITS, state_is_tuple=True) +cells = tf.contrib.rnn.MultiRNNCell([cell for _ in range(NUM_CELL_STACK)]) +init_state = state = cell.zero_state(BATCH_SIZE, dtype=tf.float32) + +W = tf.get_variable(name="weight", shape=[NUM_UNITS, FEATURE_SIZE], dtype=tf.float64) +B = tf.get_variable(name="bias", shape=[SEQUENCE_LENGTH, FEATURE_SIZE],dtype=tf.float64) +_X = tf.placeholder(dtype=tf.float64, shape=[BATCH_SIZE, SEQUENCE_LENGTH, FEATURE_SIZE]) +_Y = tf.placeholder(dtype=tf.float64, shape=[BATCH_SIZE, SEQUENCE_LENGTH, FEATURE_SIZE]) +outputs, state = tf.nn.dynamic_rnn(cell=cells, inputs=_X, + sequence_length=[SEQUENCE_LENGTH]*BATCH_SIZE, + dtype=tf.float64) +#computer predicted value +def predicted(outputs): + predict_values = [] + for i in range(BATCH_SIZE): + predicted_tensor = tf.matmul(outputs[i], W) + B + predict_values.append(predicted_tensor) + prediction = tf.stack([x for x in predict_values]) + return prediction + +def lossFn(predicted, real): + substract_tensor = predicted - real + substract_square_tensor = tf.square(substract_tensor) + loss = tf.reduce_sum(substract_square_tensor) / BATCH_SIZE + return loss +# + +loss = lossFn(predicted(outputs), _Y) +#prepare for train +optimizer = tf.train.GradientDescentOptimizer(0.01) +train = optimizer.minimize(loss) +init = tf.global_variables_initializer() +sess.run(init) +writer = tf.summary.FileWriter("c://tmp/data/graph", sess.graph) +#train +print() +print() +print() +print("Training the model......") +pyl_x = [] +pyl_y = [] +start = datetime.datetime.now() +print("start time is ", start) +for echo in range(0, ECHO+1): + losses = [] + + for x, y in dr.non_linear_parabolic_curve_map_data_reader(num_batch=NUM_BATCH, + batch_size=BATCH_SIZE, + sequence_length=SEQUENCE_LENGTH, + feature_size=FEATURE_SIZE): + sess.run(train, feed_dict={_X:x, _Y:y}) + _loss = sess.run(loss, feed_dict={_X:x, _Y:y}) + losses.append(_loss) + _loss_ = np.sum(losses, 0) / NUM_BATCH + if (echo) % 10 == 0: + print(echo, _loss_) + pyl_x.append(echo) + pyl_y.append(_loss_) + +end = datetime.datetime.now() +print() +print("The training is over") +print("The end time is ", end) +print("total time for training is ", end-start) + +pyl.plot(pyl_x, pyl_y) +pyl.show() diff --git a/pool/shard001/Python/0013525_sns_logger.py b/pool/shard001/Python/0013525_sns_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..33a8357d09764e40669f376f27bcfd39df8d83ec --- /dev/null +++ b/pool/shard001/Python/0013525_sns_logger.py @@ -0,0 +1,34 @@ +from __future__ import print_function +import time +import os +import json +import urlparse +import boto3 + +def handler(event, context): + """ + This function puts into dynamo and get from it. + """ + message = event['Records'][0]['Sns']['Message'] + + # xxx print("Started up") + # xxx print("message Below") + # xxx print(message) + # xxx print("CONTEXT") + # xxx print(context) + # xxx print(dir(context)) + # + # there is some jiggery pokery required to be able to accept any + # input from slack, which provides not json input but query params + # + url_to_parse = 'http://fake.url.com/?message='+ message + parsed = urlparse.urlparse(url_to_parse) + input_text = urlparse.parse_qs(parsed.query)['message'] + + + # Just log here, but we could do more + # we could also bring this back into slack with an inbound webhook + for word in input_text[0].split(): + print("LOG THIS WORD: %s" % (word)) + + print("This function could do much more than log") diff --git a/pool/shard001/Python/0013530_frequencia_consumer.py b/pool/shard001/Python/0013530_frequencia_consumer.py new file mode 100644 index 0000000000000000000000000000000000000000..203789fecbff02d2b7f1aaa8913ad588edaba4c3 --- /dev/null +++ b/pool/shard001/Python/0013530_frequencia_consumer.py @@ -0,0 +1,87 @@ +import pika +import sys +import requests, json +import urllib.request +from get_serial import get_serial + +IP_RABBIT = sys.argv[1] +IP_REST = "http://" + sys.argv[2] + ":8000/teste/" +SERIAL = "000000" + +headers = {'Content-type': 'application/json'} + +credentials = pika.PlainCredentials('qunews', 'qunews') +connection = pika.BlockingConnection(pika.ConnectionParameters( + IP_RABBIT, 5672, 'qunews_host', credentials)) + +channel = connection.channel() + +channel.exchange_declare(exchange='qunews.data', + type='topic', + durable=True) + +result = channel.queue_declare(exclusive=True) +queue_name = result.method.queue + + +channel.queue_bind(exchange='qunews.data', + queue=queue_name, + routing_key='qunews.frequencia.ceagri') + +print(' [*] Waiting for logs. To exit press CTRL+C') + +def calcula_total_macs(macs): + total = 0 + + for tipo in macs: + total += int(tipo[1]) + + return total + + +def calcula_frequencias(lista_macs): + total_macs = calcula_total_macs(lista_macs) + lista_frequencias = [] + + for tipo in lista_macs: + frequencia_relativa = float(tipo[1])/total_macs + frequencia_relativa_rounded = round(frequencia_relativa, 2) + lista_frequencias.append((tipo[0], int(frequencia_relativa_rounded*10))) + + return lista_frequencias + + +def callback(ch, method, properties, body): + global headers + global IP_REST + global SERIAL + texto = body.decode() + lista = calcula_frequencias(eval(texto)) + try: + print("Frequências: {} => {} || {} => {}".format(lista[0][0], lista[0][1], lista[1][0], lista[1][1])) + except: + print("Frequências: {} => {}".format(lista[0][0], lista[0][1])) + lista_formatada = [] + for tupla in lista: + nova_tupla = (tupla[0],tupla[1]) + lista_formatada.append(nova_tupla) + msg ='\"'+SERIAL+';'+str(lista_formatada)+'\"' + noticias = requests.post(IP_REST, data=msg, headers=headers) + dados = noticias.json() + nome_cont = 1 + for item in dados: + link = "http://192.168.0.104:8000"+item['image'] + nome_arq = "" + if nome_cont < 10: + nome_arq += '00' + str(nome_cont) + '.png' + else: + nome_arq += '0' + str(nome_cont) + '.png' + nome_cont += 1 + urllib.request.urlretrieve(link, nome_arq) + print("=====================================") + +channel.basic_consume(callback, + queue=queue_name, + no_ack=True) + +channel.start_consuming() diff --git a/pool/shard001/Python/0013532_trajectories2sql.py b/pool/shard001/Python/0013532_trajectories2sql.py new file mode 100644 index 0000000000000000000000000000000000000000..90ab94e544701292d4b36b1c4fa84efda513bc1a --- /dev/null +++ b/pool/shard001/Python/0013532_trajectories2sql.py @@ -0,0 +1,101 @@ +import argparse +import glob +import os +import subprocess +import xml.etree.ElementTree as ET +from os import listdir +from os.path import isdir, join + +from config import * + + +def create_table(): + conn = sqlite3.connect(database_file) + c = conn.cursor() + + c.execute('DROP TABLE IF EXISTS trajectories') + + c.execute('''CREATE TABLE trajectories + (dataset, strategy, generation, seed, time, error, configuration, + FOREIGN KEY(dataset) REFERENCES experiments(dataset), + FOREIGN KEY(strategy) REFERENCES experiments(strategy), + FOREIGN KEY(generation) REFERENCES experiments(generation), + UNIQUE(dataset, strategy, generation, seed, time) ON CONFLICT REPLACE + )''') + + conn.commit() + conn.close() + + +def parse_trajectories(folder, c): + os.chdir(folder) + + all_trajectories = glob.glob("*trajectories*") + if len(all_trajectories) == 0: + print "No trajectories found" + return + + print 'Parsing: ', folder + + for file in all_trajectories: + # file = absorber.TPE.CV-absorber.trajectories.0 + tmp = file.split('.') + dataset = tmp[0] + strategy = tmp[1] + generation = tmp[2].split('-')[0] + + if dataset in datasets: + e = ET.parse(file).getroot() + traj = e.find('trajectories') + if traj is not None: + seed = int(traj.find('seed').text) # should be only 1 element + # numEvaluatedEvaluations = traj.find('numEvaluatedEvaluations').text + # numMemOutEvaluations = traj.find('numMemOutEvaluations').text + # numTimeOutEvaluations = traj.find('numTimeOutEvaluations').text + + for point in traj.findall('point'): + time = float(point.find('time').text) + error = float(point.find('errorEstimate').text) + configuration = point.find('args').text + + # transform autoweka config to weka config + command = '$MY_JAVA_PATH/java -Xmx2000M -cp $AUTOWEKA_PATH/autoweka.jar autoweka.WekaArgumentConverter "%s"' % ( + configuration.lstrip().rstrip()) + try: + output = subprocess.check_output(command, shell=True) + configuration = output.rstrip() + except: + configuration = '' + + sql_query = '''INSERT OR REPLACE INTO trajectories( + dataset, strategy, generation, seed, time, error, configuration) + VALUES ('%s', '%s', '%s', %d, %f, %f, '%s')''' % ( + dataset, strategy, generation, seed, time, error, configuration) + c.execute(sql_query) + + +def main(): + parser = argparse.ArgumentParser(prog=os.path.basename(__file__)) + globals().update(load_config(parser)) + parser.add_argument('--create-table', action='store_true') + + args = parser.parse_args() + + if args.create_table: + create_table() + + conn = sqlite3.connect(database_file) + c = conn.cursor() + + mypath = '%s/%s' % (os.environ['AUTOWEKA_PATH'], experiments_folder) + experiments = [f for f in listdir(mypath) if isdir(join(mypath, f))] + for e in experiments: + folder = "%s/%s" % (mypath, e) + parse_trajectories(folder, c) + + conn.commit() + conn.close() + + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0013534_shared.py b/pool/shard001/Python/0013534_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..64459892043734365d33fc4dcf6d38cf6d1144e8 --- /dev/null +++ b/pool/shard001/Python/0013534_shared.py @@ -0,0 +1,149 @@ +"""Objects not specific to ligands or targets.""" + +import re +import html + +class DatabaseLink: + """A link to an external database, containing accession and species + information. + + :param json_data: A dictionary obtained from the web services.""" + + def __init__(self, json_data): + self.json_data = json_data + + self._accession = json_data["accession"] + self._database = json_data["database"] + self._url = json_data["url"] + self._species = None if json_data["species"] == "None" else json_data["species"] + + + def __repr__(self): + return "<%s link (%s)%s>" % ( + self._database, + self._accession, + " for " + self._species if self._species else "" + ) + + + def accession(self): + """The Accession code.""" + + return self._accession + + + def database(self): + """The Database being linked to.""" + + return self._database + + + def url(self): + """The URL for this database entry.""" + + return self._url + + + def species(self): + """The specific species the database entry refers to.""" + + return self._species + + + +class Gene: + """A gene for a pyGtoP target. + + :param json_data: A dictionary obtained from the web services.""" + + def __init__(self, json_data): + self.json_data = json_data + + self._target_id = json_data["targetId"] + self._species = json_data["species"] + self._gene_symbol = json_data["geneSymbol"] + self._gene_name = json_data["geneName"] + self._official_gene_id = json_data["officialGeneId"] + self._genomic_location = json_data["genomicLocation"] + self._amino_acids = int(json_data["aminoAcids"]) if json_data["aminoAcids"] else 0 + self._transmembrane_domains = int(json_data["transmembraneDomains"]) if json_data["transmembraneDomains"] else 0 + self._pore_loops = int(json_data["poreLoops"]) if json_data["poreLoops"] else 0 + + + def __repr__(self): + return "<%s Gene (%s)>" % (self._species, self._gene_symbol) + + + def target_id(self): + """The ID of the pyGtoP target derived from this gene.""" + + return self._target_id + + + def species(self): + """The species the gene is from.""" + + return self._species + + + def gene_symbol(self): + """The gene's code.""" + + return self._gene_symbol + + + def gene_name(self): + """The gene's name.""" + + return self._gene_name + + + def official_gene_id(self): + """The gene's official ID.""" + + return self._official_gene_id + + + def genomic_location(self): + """The gene's location in its genome.""" + + return self._genomic_location + + + def amino_acids(self): + """The number of amino acids the gene codes for.""" + + return self._amino_acids + + + def transmembrane_domains(self): + """The number of amino acids in the resultant protein.""" + + return self._transmembrane_domains + + + def pore_loops(self): + """The number of pore loops in the resultant protein.""" + + return self._pore_loops + + + +def strip_html(func): + """A decorator which, when applied to a function, will add a 'strip_html' + keyword argument - if set to True this will strip any HTML from the + function's output.""" + + cleaner = re.compile("<.*?>") + def new_func(*args, strip_html=False, **kwargs): + name = func(*args, **kwargs) + if strip_html: + if isinstance(name, str): + return html.unescape(re.sub(cleaner, "", name)) + elif isinstance(name, list) or isinstance(name, tuple): + return type(name)([html.unescape(re.sub(cleaner, "", n)) for n in name]) + else: + return name + new_func.__name__ = func.__name__ + new_func.__doc__ = func.__doc__ + return new_func diff --git a/pool/shard001/Python/0013544_component.py b/pool/shard001/Python/0013544_component.py new file mode 100644 index 0000000000000000000000000000000000000000..09be27ba5120caf97a67b194021e66e1da50296a --- /dev/null +++ b/pool/shard001/Python/0013544_component.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +# +# Component base class for ETL. +# +# Author: Just van den Broecke +# +import os +import sys +from time import time +from util import Util, ConfigSection +from packet import FORMAT + +log = Util.get_log('component') + + +class Config(object): + """ + Decorator class to tie config values from the .ini file to object instance + property values. Somewhat like the Python standard @property but with + the possibility to define default values, typing and making properties required. + + Each property is defined by @Config(type, default, required). + Basic idea comes from: https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties + """ + + def __init__(self, ptype=str, default=None, required=False): + """ + If there are no decorator arguments, the function + to be decorated is passed to the constructor. + """ + # print "Inside __init__()" + self.ptype = ptype + self.default = default + self.required = required + + def __call__(self, fget, doc=''): + """ + The __call__ method is not called until the + decorated function is called. self is returned such that __get__ below is called + with the Component instance. That allows us to cache the actual property value + in the Component itself. + """ + # Save the property name (is the name of the function calling us). + self.property_name = fget.__name__ + # print "Inside __call__() name=%s" % self.property_name + + # For Spinx documentation build we need the original function with docstring. + IS_SPHINX_BUILD = bool(os.getenv('SPHINX_BUILD')) + if IS_SPHINX_BUILD: + doc = doc.strip() + # TODO more detail, example below + # doc = '``Parameter`` - %s\n\n' % doc + doc += '* type: %s\n' % str(self.ptype).split("'")[1] + doc += '* required: %s\n' % self.required + doc += '* default: %s\n' % self.default + + # if self.value: + # doc += '* value: %s\n' % self.value + # else: + # doc += '* required: %s\n' % self.required + # doc += '* default: %s\n' % self.default + # doc += '* value_range: %s\n' % self.value_range + + fget.__doc__ = '``CONFIG`` %s\n%s' % (fget.__doc__, doc) + return fget + else: + return self + + def __get__(self, comp_inst, owner): + # print "Inside __get__() owner=%s" % owner + """ descr.__get__(obj[, type]) -> value """ + if self.property_name not in comp_inst.cfg_vals: + cfg, name, default_value = comp_inst.cfg, self.property_name, self.default + + # Do type conversion where needed from the string values + if self.ptype is str: + value = cfg.get(name, default=default_value) + elif self.ptype is bool: + value = cfg.get_bool(name, default=default_value) + elif self.ptype is list: + value = cfg.get_list(name, default=default_value) + elif self.ptype is dict: + value = cfg.get_dict(name, default=default_value) + elif self.ptype is int: + value = cfg.get_int(name, default=default_value) + elif self.ptype is tuple: + value = cfg.get_tuple(name, default=default_value) + else: + value = cfg.get(name, default=default_value) + + if self.required is True and value is None: + raise Exception('Config property: %s is required in config for %s' % (name, str(comp_inst))) + + comp_inst.cfg_vals[self.property_name] = value + + return comp_inst.cfg_vals[self.property_name] + + +class Component(object): + """ + Abstract Base class for all Input, Filter and Output Components. + + """ + + @Config(ptype=str, default=None, required=False) + def input_format(self): + """ + The specific input format if the consumes parameter is a list or the format to be converted to the output_format. + """ + pass + + @Config(ptype=str, default=None, required=False) + def output_format(self): + """ + The specific output format if the produces parameter is a list or the format to which the input format is converted. + """ + pass + + def __init__(self, configdict, section, consumes=FORMAT.none, produces=FORMAT.none): + # The raw config values from the cfg file + self.cfg = ConfigSection(configdict.items(section)) + + # The actual typed values as populated within Config Decorator + self.cfg_vals = dict() + self.next = None + self.section = section + self._max_time = -1 + self._min_time = sys.maxint + self._total_time = 0 + self._invoke_count = 0 + + # First assume single output provided by derived class + self._output_format = produces + + # We may have a configured output_format: use that value, when multiple formats it should be in that list + if self.output_format is not None: + self._output_format = self.output_format + if type(produces) is list and self._output_format not in produces: + raise ValueError('Configured output_format %s not in list: %s' % (self._output_format, str(produces))) + elif type(produces) is list: + # No output_format configured and a list: use the first as default + self._output_format = produces[0] + + # First assume single input provided by derived class + self._input_format = consumes + + # We may have a configured input_format: use that value, when multiple formats it should be in that list + if self.input_format is not None: + self._input_format = self.input_format + if type(consumes) is list and self._input_format not in consumes: + raise ValueError('Configured input_format %s not in list: %s' % (self._input_format, str(consumes))) + elif type(consumes) is list: + # No input_format configured and a list: use the first as default + self._input_format = consumes[0] + + def add_next(self, next_component): + self.next = next_component + + if not self.is_compatible(): + raise ValueError( + 'Incompatible components are linked: %s and %s' % (str(self), str(self.next))) + + # Get our id: currently the [section] name + def get_id(self): + return self.section + + # Get last Component in Chain + def get_last(self): + last = self + while last.next: + last = last.next + if isinstance(last, list): + last = last[0] + return last + + # Check our compatibility with the next Component in the Chain + def is_compatible(self): + + # Ok, nothing next in Chain + if self.next is None or self._output_format is FORMAT.none or self.next._input_format == FORMAT.any: + return True + + # return if our Output is compatible with the next Component's Input + return self._output_format == self.next._input_format + + def __str__(self): + return "%s: in=%s out=%s" % (str(self.__class__), self._input_format, self._output_format) + + def process(self, packet): + # Current processor of packet + packet.component = self + + start_time = self.timer_start() + self._invoke_count += 1 + + # Do something with the data + result = self.before_invoke(packet) + if result is False: + # Component indicates it does not want the chain to proceed + self.timer_stop(start_time) + return packet + + # Do component-specific processing, e.g. read or write or filter + packet = self.invoke(packet) + + result = self.after_invoke(packet) + if result is False: + # Component indicates it does not want the chain to proceed + self.timer_stop(start_time) + return packet + + self.timer_stop(start_time) + + # If there is a next component, let it process + if self.next: + # Hand-over data (line, doc whatever) to the next component + packet.format = self._output_format + packet = self.next.process(packet) + + result = self.after_chain_invoke(packet) + return packet + + def do_init(self): + # Some components may do one-time init + self.init() + + # If there is a next component, let it do its init() + if self.next: + self.next.do_init() + + def do_exit(self): + # Notify all comps that we exit + self.exit() + + # Simple performance stats in one line (issue #77) + # Calc average processing time, watch for 0 invoke-case + avg_time = 0.0 + if self._invoke_count > 0: + avg_time = self._total_time / self._invoke_count + + log.info("%s invokes=%d time(total, min, max, avg) = %.3f %.3f %.3f %.3f" % + (self.__class__.__name__, self._invoke_count, + self._total_time, self._min_time, self._max_time, + avg_time)) + + # If there is a next component, let it do its exit() + if self.next: + self.next.do_exit() + + def before_invoke(self, packet): + """ + Called just before Component invoke. + """ + return True + + def after_invoke(self, packet): + """ + Called right after Component invoke. + """ + return True + + def after_chain_invoke(self, packet): + """ + Called right after entire Component Chain invoke. + """ + return True + + def invoke(self, packet): + """ + Components override for Component-specific behaviour, typically read, filter or write actions. + """ + return packet + + def init(self): + """ + Allows derived Components to perform a one-time init. + """ + pass + + def exit(self): + """ + Allows derived Components to perform a one-time exit/cleanup. + """ + pass + + def timer_start(self): + return time() + + def timer_stop(self, start_time): + """ + Collect and calculate per-Component performance timing stats. + :param start_time: + :return: + """ + delta_time = time() - start_time + + # Calc timing stats for Component invocation + self._total_time += delta_time + + if delta_time > self._max_time: + self._max_time = delta_time + + if delta_time < self._min_time and '%.3f' % delta_time != '0.000': + self._min_time = delta_time diff --git a/pool/shard001/Python/0013555_pl_file_upload.py b/pool/shard001/Python/0013555_pl_file_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..77bd60ad570999d2f22f4b34c515ca1a17566cae --- /dev/null +++ b/pool/shard001/Python/0013555_pl_file_upload.py @@ -0,0 +1,103 @@ +import prairielearn as pl +import lxml.html +import chevron +import json +from io import StringIO +import csv +import hashlib + + +def get_file_names_as_array(raw_file_names): + raw_file_names = StringIO(raw_file_names) + reader = csv.reader(raw_file_names, delimiter=',', escapechar='\\', quoting=csv.QUOTE_NONE, skipinitialspace=True, strict=True) + for row in reader: + # Assume only one row + return row + + +# Each pl_file_upload element is uniquely identified by the SHA1 hash of its +# file_names attribute +def get_answer_name(file_names): + return '_file_upload_{0}'.format(hashlib.sha1(file_names.encode('utf-8')).hexdigest()) + + +def add_format_error(data, error_string): + if '_files' not in data['format_errors']: + data['format_errors']['_files'] = [] + data['format_errors']['_files'].append(error_string) + + +def prepare(element_html, element_index, data): + element = lxml.html.fragment_fromstring(element_html) + required_attribs = ['file_names'] + optional_attribs = [] + pl.check_attribs(element, required_attribs, optional_attribs) + + if '_required_file_names' not in data['params']: + data['params']['_required_file_names'] = [] + file_names = get_file_names_as_array(pl.get_string_attrib(element, 'file_names')) + data['params']['_required_file_names'].extend(file_names) + + +def render(element_html, element_index, data): + if data['panel'] != 'question': + return '' + + element = lxml.html.fragment_fromstring(element_html) + uuid = pl.get_uuid() + raw_file_names = pl.get_string_attrib(element, 'file_names', '') + file_names = get_file_names_as_array(raw_file_names) + file_names_json = json.dumps(file_names) + answer_name = get_answer_name(raw_file_names) + + html_params = {'name': answer_name, 'file_names': file_names_json, 'uuid': uuid} + + files = data['submitted_answers'].get('_files', None) + if files is not None: + # Filter out any files not part of this element's file_names + filtered_files = [x for x in files if x.get('name', '') in file_names] + html_params['has_files'] = True + html_params['files'] = json.dumps(filtered_files) + else: + html_params['has_files'] = False + + with open('pl_file_upload.mustache', 'r', encoding='utf-8') as f: + html = chevron.render(f, html_params).strip() + + return html + + +def parse(element_html, element_index, data): + element = lxml.html.fragment_fromstring(element_html) + raw_file_names = pl.get_string_attrib(element, 'file_names', '') + required_file_names = get_file_names_as_array(raw_file_names) + answer_name = get_answer_name(raw_file_names) + + # Get submitted answer or return parse_error if it does not exist + files = data['submitted_answers'].get(answer_name, None) + if not files: + add_format_error(data, 'No submitted answer for file upload.') + return + + try: + parsed_files = json.loads(files) + except ValueError: + add_format_error(data, 'Could not parse submitted files.') + + # Filter out any files that were not listed in file_names + parsed_files = [x for x in parsed_files if x.get('name', '') in required_file_names] + + if data['submitted_answers'].get('_files', None) is None: + data['submitted_answers']['_files'] = parsed_files + elif isinstance(data['submitted_answers'].get('_files', None), list): + data['submitted_answers']['_files'].extend(parsed_files) + else: + add_format_error(data, '_files was present but was not an array.') + + # Validate that all required files are present + if parsed_files is not None: + submitted_file_names = [x.get('name', '') for x in parsed_files] + missing_files = [x for x in required_file_names if x not in submitted_file_names] + + if len(missing_files) > 0: + add_format_error(data, 'The following required files were missing: ' + ', '.join(missing_files)) diff --git a/pool/shard001/Python/0013559_SocketUtils.py b/pool/shard001/Python/0013559_SocketUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..8a602dbe349647d1f7c50189343b79c7c1fb4ff6 --- /dev/null +++ b/pool/shard001/Python/0013559_SocketUtils.py @@ -0,0 +1,71 @@ +# +# General: +# This file is part of .NET Bridge +# +# Copyright: +# 2010 Jonathan Shore +# 2017 Jonathan Shore and Contributors +# +# License: +# 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 socket +import time + +class SocketUtils: + """ + Various socket convenience functions + """ + + @staticmethod + def connect (host: str, port: int, retries = 5, retrygap = 2, startup = None): + """ + Create TCP/IP stream-based connection to given host / port, with retries + + :param host: hostname to connect to + :param port: port # + :param retries: number of retries to connect + :param retrygap: time to sleep between retries in seconds + :param startup: function to be called to start server if server is down (only called once) + """ + for i in range(retries): + try: + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect((host, port)) + return client + except ConnectionRefusedError: + client.close() + if startup is not None and i == 0: + startup() + elif i == retries-1: + raise + else: + time.sleep(retrygap) + + + def is_running (host, port): + """ + Determine whether server at host:port is operational + + :param host: hostname of server + :param port: port # of server + """ + s = socket.socket() + try: + s.connect ((server, port)) + s.close() + return True + except e: + s.close() + return False diff --git a/pool/shard001/Python/0013561_analysedialog.py b/pool/shard001/Python/0013561_analysedialog.py new file mode 100644 index 0000000000000000000000000000000000000000..187c6d182ab9d80701562802e07673008eb64984 --- /dev/null +++ b/pool/shard001/Python/0013561_analysedialog.py @@ -0,0 +1,98 @@ +''' +Created on 27.02.2013 + +@author: gena +''' +from __future__ import division +from PyQt4 import QtCore, QtGui +from os.path import basename + + +class AnalyseDialog(QtGui.QDialog): + ''' + This is a simple dialog, used to select files for analysis: + filename to store analysis results + and list of files to analyse + ''' + def __init__(self, parent=None): + ''' + Constructor + ''' + super(AnalyseDialog, self).__init__(parent) + self.analyseFileName = QtCore.QString() # File name to save results + self.lastDirectory = QtCore.QString('.') + self.ltFilesList = None # List to store input lt files + layout = QtGui.QGridLayout() + # analyseFile elements + self.analyseFileEdit = QtGui.QLineEdit() + analyseFileLabel = QtGui.QLabel('Result file name') + layout.addWidget(analyseFileLabel,0,0) + layout.addWidget(self.analyseFileEdit,0,1) + browseButton = QtGui.QPushButton('Browse...') + browseButton.clicked.connect(self.browseAnalyseFile) + layout.addWidget(browseButton,0,2) + # ltFileList Elements + ltFileListLabel = QtGui.QLabel('Files to analyse:') + layout.addWidget(ltFileListLabel,1,0) + self.ltFilesList = QtGui.QListView() + self.model = QtGui.QStringListModel() + self.ltFilesList.setModel(self.model) + layout.addWidget(self.ltFilesList,2,0,1,3) + ltBrowseButton = QtGui.QPushButton('Browse...') + ltBrowseButton.clicked.connect(self.ltFilesOpen) + layout.addWidget(ltBrowseButton,3,2) + # Ok/Close buttonbox + self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Close | QtGui.QDialogButtonBox.Ok, + accepted=self.accept, + rejected=self.reject) + + self.validate() # + layout.addWidget(self.buttonBox) + self.setLayout(layout) + + def clearData(self): + self.analyseFileEdit.clear() + self.ltFilesList = None + self.validate() + + def browseAnalyseFile(self): + ''' + Select one file to save analyse results + ''' + formats = ["*.%s" % unicode(videoFormat).lower() \ + for videoFormat in ('txt', 'csv')] + # Setting last user dir + # Executing standard open dialog + self.analyseFileName = QtGui.QFileDialog.getSaveFileName(self, + "Choose file to save results", + self.lastDirectory, "Data files (%s)" % " ".join(formats)) + if not self.analyseFileName.isEmpty() : + fileInfo = QtCore.QFileInfo(self.analyseFileName) + self.lastDirectory = fileInfo.absolutePath() + self.analyseFileEdit.setText(self.analyseFileName) + self.validate() + + def ltFilesOpen(self): + ''' + Select list of lt files to analyse + ''' + dialog = QtGui.QFileDialog(self, 'Open input Files', + self.lastDirectory) + dialog.setFileMode(QtGui.QFileDialog.ExistingFiles); + dialog.setNameFilter("Locotrack chamber (*.lt1)") + if dialog.exec_() : + # Display selected list + self.ltFilesList = dialog.selectedFiles() + baseNames = [basename(unicode(fileName)) for fileName in self.ltFilesList] + self.model.setStringList(baseNames) + self.lastDirectory = dialog.directory().absolutePath () + else : + self.ltFilesList = None + self.validate() + + def validate(self): + ''' + Validate input data and enable Ok button if all fine + ''' + flag = (self.ltFilesList is not None) and (not self.analyseFileName.isEmpty()) + self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(flag) \ No newline at end of file diff --git a/pool/shard001/Python/0013562_dates.py b/pool/shard001/Python/0013562_dates.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7894d301ada839b55a26d02aeaecb2f8948a21 --- /dev/null +++ b/pool/shard001/Python/0013562_dates.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. +# +# This source code is licensed under the OSL-3.0 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +import datetime + +import six +from django.utils import timezone +from django.utils.translation import ugettext as _ +from django.utils.translation import ungettext + +__all__ = ("parse_date", "parse_time", "try_parse_date", "try_parse_time") + +_date_formats = ( + "%Y-%m-%d", + "%Y%m%d", + "%Y/%m/%d", + "%d.%m.%y", + "%d.%m.%Y", + "%Y %m %d", + "%m/%d/%Y", +) + +_time_formats = ( + "%H:%M:%S", + "%H:%M", +) + +locale_year_and_month_formats = { + # Sourced from the Unicode CLDR, version 27.1. + # All locales not listed here use "MMM y". + 'be': 'LLL y', + 'bg': "MM.y 'г'.", + 'bs': 'MMM y.', + 'ca': 'LLL y', + 'cs': 'LLLL y', + 'dz': 'y སྤྱི་ཟླ་MMM', + 'eu': 'y MMM', + 'fi': 'LLL y', + 'fo': 'y MMM', + 'hr': 'LLL y.', + 'hu': 'y. MMM', + 'hy': 'yթ. LLL', + 'ja': 'y年M月', + 'ka': 'MMM, y', + 'kea': "MMM 'di' y", + 'ko': 'y년 MMM', + 'ky': "y-'ж'. MMM", + 'lt': 'y-MM', + 'lv': "y. 'g'. MMM", + 'mk': "MMM y 'г'.", + 'ml': 'y MMM', + 'mn': 'y MMM', + 'ne': 'y MMM', + 'os': 'LLL y', + 'pl': 'MM.y', + 'pt': 'MM/y', + 'ru': 'LLL y', + 'seh': "MMM 'de' y", + 'si': 'y MMM', + 'sk': 'LLLL y', + 'sr': 'MMM y.', + 'uk': 'LLL y', + 'uz': 'y MMM', +} + + +def _parse_date_str(value): + value = value.strip() + for fmt in _date_formats: + try: + return datetime.datetime.strptime(value, fmt).date() + except: + pass + try: + return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S.%f").date() + except: + pass + + +def _parse_time_str(value): + value = value.strip() + for fmt in _time_formats: + try: + return datetime.datetime.strptime(value, fmt).time() + except: + pass + return None + + +def parse_date(value): + """ + Tries to make a date out of the value. If impossible, it raises an exception. + + :param value: A value of some ilk. + :return: Date + :rtype: datetime.date + :raise ValueError: + """ + # this should be first since `datetime.datetime` is subclass of `datetime.date` + if isinstance(value, datetime.datetime): + return value.date() + if isinstance(value, datetime.date): + return value + elif isinstance(value, six.string_types): + date = _parse_date_str(value) + if not date: + raise ValueError("Unable to parse %s as date." % value) + return date + raise ValueError("Unable to parse %s as date (unknown type)." % value) + + +def parse_time(value): + """ + Tries to make a time out of the value. If impossible, it raises an exception. + + :param value: A value of some ilk. + :return: Time + :rtype: datetime.time + :raise ValueError: + """ + if isinstance(value, datetime.time): + return value + if isinstance(value, datetime.datetime): + return value.time() + if isinstance(value, six.string_types): + time = _parse_time_str(value) + if not time: + raise ValueError("Unable to parse %s as date." % value) + return time + raise ValueError("Unable to parse %s as date (unknown type)." % value) + + +def try_parse_date(value): + """ + Tries to make a time out of the value. If impossible, returns None. + + :param value: A value of some ilk. + :return: Date + :rtype: datetime.date + """ + if value is None: + return None + try: + return parse_date(value) + except ValueError: + return None + + +def try_parse_time(value): + """ + Tries to make a time out of the value. If impossible, returns None. + + :param value: A value of some ilk. + :return: Time + :rtype: datetime.time + """ + if value is None: + return None + try: + return parse_time(value) + except ValueError: + return None + + +def get_year_and_month_format(locale): + """ + Get the Babel/Unicode format string for a "year and month" format + for the given locale. + + Only the "language" part of the locale is taken into account here. + + :param locale: Babel locale + :type locale: babel.Locale + :return: format string + :rtype: str + """ + return locale_year_and_month_formats.get(locale.language.lower(), "MMM y") + + +def to_aware(date, time=datetime.time.min, tz=None): + """ + Convert date or datetime to aware datetime. + + :type date: datetime.date|datetime.datetime + :param date: + Date or datetime object to convert + :type time: datetime.time + :param time: + Time value for supplementing dates to datetimes, default 0:00:00 + :type tz: datetime.tzinfo|None + Timezone to use, default ``timezone.get_current_timezone()`` + :rtype: datetime.datetime + :return: + Converted aware datetime object + """ + if isinstance(date, datetime.datetime): + if timezone.is_aware(date): + return date + return timezone.make_aware(date, timezone=tz) + assert isinstance(date, datetime.date), '%r should be date' % (date,) + combined = datetime.datetime.combine(date, time) + return timezone.make_aware(combined, timezone=tz) + + +def local_now(tz=None): + """ + Get current time as aware datetime in local timezone. + + :type tz: datetime.tzinfo|None + Timezone to use, default ``timezone.get_current_timezone()`` + :rtype: datetime.datetime + """ + return timezone.localtime(to_aware(timezone.now()), timezone=tz) + + +class DurationRange(object): + """ + Present duration range, min days to max days. + """ + def __init__(self, min_duration, max_duration=None): + assert isinstance(min_duration, datetime.timedelta) + assert max_duration is None or ( + isinstance(max_duration, datetime.timedelta)) + assert max_duration is None or max_duration >= min_duration + self.min_duration = min_duration + self.max_duration = (max_duration if max_duration is not None + else min_duration) + + @classmethod + def from_days(cls, min_days, max_days=None): + return cls( + datetime.timedelta(days=min_days), + (datetime.timedelta(days=max_days) + if max_days is not None else None)) + + def __str__(self): + if self.min_duration == self.max_duration: + days = self.max_duration.days + return ungettext("%s day", "%s days", days) % (days,) + return _("%(min)s--%(max)s days") % { + "min": self.min_duration.days, "max": self.max_duration.days} diff --git a/pool/shard001/Python/0013566_strongbox_fixity.py b/pool/shard001/Python/0013566_strongbox_fixity.py new file mode 100644 index 0000000000000000000000000000000000000000..282b2b15fa02fd601ab3373f0c0e62534fe40898 --- /dev/null +++ b/pool/shard001/Python/0013566_strongbox_fixity.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +''' +Analyses the CSV file reports from Strongbox. +Accepts an identifier input, at least the package ID but +the UUID would also be useful. +The script then finds the relevant entries, harvests the checksums and +stores them as a regular manifest. +It would make sense to also accept an existing sha512 manifest as an argparse +so that the script can tell if they are identical. + +''' +import os +import sys +import collections +import argparse +import unicodedata +import ififuncs + +def parse_args(args_): + ''' + Parse command line arguments. + ''' + parser = argparse.ArgumentParser( + description='Analyses the CSV file reports from Strongbox.' + 'Prints the output to the terminal if the -manifest option is not used' + 'if the -manifest option is used, just the differences, if any, will appear on screen' + ' Written by Kieran O\'Leary.' + ) + parser.add_argument( + '-csv', help='Path to the strongbox CSV file.' + ) + parser.add_argument( + '-i', + help='Path of the parent folder containing the accessioned packages' + ) + parsed_args = parser.parse_args(args_) + return parsed_args + +def diff_manifests(manifest, strongbox_list): + ''' + Compare the list of strongbox hashes to the original AIP manifest. + ''' + print('\nStrongbox_fixity - IFIscripts') + print('Analysing %s\n' % manifest) + with open(manifest, 'r') as original_manifest: + aip_manifest = original_manifest.read().splitlines() + # A list of items in strongbox, that are different in aip sha512 manifest + strongbox_check = [item for item in strongbox_list if unicodedata.normalize('NFD', item) not in aip_manifest] + new_manifest = [] + # A list of items in the AIP manifest, that are different in the strongbox manifest + aip_check = [item for item in aip_manifest if unicodedata.normalize('NFD', item) not in strongbox_list] + # check if the files are actually on the strongbox + if len(strongbox_list) == 0: + print('ERROR ***************************************') + print('ERROR ***************************************The files are not on strongbox!!') + # checks if everything in the strongbox list is in the aip manifest. + elif len(strongbox_check) == 0: + print('All files in the strongbox manifest are present in your AIP manifest and the hashes validate') + else: + for i in strongbox_check: + print('%s is different from the strongbox_csv to the AIP manifest' % i) + if len(aip_check) == 0: + print('All files in the AIP manifest are present in your strongbox manifest and the hashes validate') + else: + for i in strongbox_check: + print('%s is different from the AIP manifest to the Strongbox manifest' % i) + print('Analysis complete\n') +def find_checksums(csv_file, identifier): + ''' + Finds the relevant entries in the CSV and prints to terminal + ''' + csv_dict = ififuncs.extract_metadata(csv_file) + manifest_lines = [] + for items in csv_dict: + for x in items: + if type(x) in [collections.OrderedDict, dict]: + if identifier in x['path']: + identifier_string = "/%s/" % identifier + manifest_line = x['hash_code'] + ' ' + x['path'].replace(identifier_string, '') + manifest_lines.append(manifest_line) + strongbox_list = sorted(manifest_lines, key=lambda x: (x[130:])) + return strongbox_list + +def find_manifest(source): + ''' + Recursively search through a package for a sha512 package. + ''' + for root, dirnames, filenames in os.walk(source): + for files in filenames: + if files.endswith('_manifest-sha512.txt'): + return os.path.join(root, files) + +def main(args_): + args = parse_args(args_) + csv_file = args.csv + source = args.i + package_list = sorted(os.listdir(source)) + for package in package_list: + full_path = os.path.join(source, package) + if os.path.isdir(full_path): + basename = os.path.basename(package) + if package[:3] == 'aaa': + strongbox_list = find_checksums(csv_file, package) + manifest = find_manifest(full_path) + diff_manifests(manifest, strongbox_list) # manifest needs to be declared here + ''' + for i in strongbox_list: + print i + ''' +if __name__ == '__main__': + main(sys.argv[1:]) + diff --git a/pool/shard001/Python/0013582_best_splits_op_test.py b/pool/shard001/Python/0013582_best_splits_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..628b7f3dadc102622f1f35f6f8e7ca44a4052f9d --- /dev/null +++ b/pool/shard001/Python/0013582_best_splits_op_test.py @@ -0,0 +1,128 @@ +# Copyright 2016 The TensorFlow Authors. 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. +# ============================================================================== +"""Tests for tf.contrib.tensor_forest.ops.best_splits_op.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow # pylint: disable=unused-import + +from tensorflow.contrib.tensor_forest.python.ops import tensor_forest_ops + +from tensorflow.python.framework import test_util +from tensorflow.python.platform import googletest + + +class BestSplitsClassificationTests(test_util.TensorFlowTestCase): + + def setUp(self): + self.finished = [3, 5] + self.node_map = [-1, -1, -1, 0, -1, 3, -1, -1, -1] + self.candidate_counts = [[[153., 50., 60., 40., 3.], + [200., 70., 30., 70., 30.]], + [[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]], + [[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]], + [[40., 10., 10., 10., 10.], + [30., 10., 5., 5., 10.]]] + self.total_counts = [[400., 100., 100., 100., 100.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [400., 100., 100., 100., 100.]] + self.squares = [] + + def testSimple(self): + with self.test_session(): + split_indices = tensor_forest_ops.best_splits( + self.finished, + self.node_map, + self.candidate_counts, + self.squares, + self.total_counts, + self.squares, + regression=False) + + self.assertAllEqual([0, 1], split_indices.eval()) + + def testNoFinished(self): + with self.test_session(): + split_indices = tensor_forest_ops.best_splits( + [], + self.node_map, + self.candidate_counts, + self.squares, + self.total_counts, + self.squares, + regression=False) + + self.assertAllEqual([], split_indices.eval()) + + def testBadInput(self): + del self.total_counts[1] + + with self.test_session(): + with self.assertRaisesOpError( + 'Number of accumulators should be the same in split_sums ' + 'and accumulator_sums.'): + tensor_forest_ops.best_splits( + self.finished, + self.node_map, + self.candidate_counts, + self.squares, + self.total_counts, + self.squares, + regression=False).eval() + + +class BestSplitsRegressionTests(test_util.TensorFlowTestCase): + + def setUp(self): + self.finished = [3, 5] + self.node_map = [-1, -1, -1, 0, -1, 3, -1, -1, -1] + self.candidate_sums = [[[5., 8., 8., 8.], [5., 10., 10., 10.]], + [[0., 0., 0., 0.], [0., 0., 0., 0.]], + [[0., 0., 0., 0.], [0., 0., 0., 0.]], + [[10., 10., 20., 10.], [10., 5., 5., 5.]]] + + self.candidate_squares = [[[5., 50., 50., 50.], [5., 50., 50., 50.]], + [[0., 0., 0., 0.], [0., 0., 0., 0.]], + [[0., 0., 0., 0.], [0., 0., 0., 0.]], + [[10., 40., 50., 60.], [10., 40., 40., 40.]]] + + self.total_sums = [[15., 10., 10., 10.], + [0., 0., 0., 0.], + [0., 0., 0., 0.], + [20., 20., 20., 20.]] + + self.total_squares = [[15., 50., 50., 50.], + [0., 0., 0., 0.], + [0., 0., 0., 0.], + [20., 60., 60., 60.]] + + def testSimple(self): + with self.test_session(): + split_indices = tensor_forest_ops.best_splits( + self.finished, + self.node_map, + self.candidate_sums, + self.candidate_squares, + self.total_sums, + self.total_squares, + regression=True) + + self.assertAllEqual([1, 0], split_indices.eval()) + + +if __name__ == '__main__': + googletest.main() diff --git a/pool/shard001/Python/0013587_app2.py b/pool/shard001/Python/0013587_app2.py new file mode 100644 index 0000000000000000000000000000000000000000..3b163ebf284ce5a2537f5be4fbf0eef2d8406fdf --- /dev/null +++ b/pool/shard001/Python/0013587_app2.py @@ -0,0 +1,63 @@ +from flask import Flask +from flask_sqlalchemy import SQLAlchemy + +import flask_admin as admin +from flask_admin.contrib import sqla + + +# Create application +app = Flask(__name__) + + +# Create dummy secrey key so we can use sessions +app.config['SECRET_KEY'] = '123456790' + +# Create in-memory database +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db_2.sqlite' +app.config['SQLALCHEMY_ECHO'] = True +db = SQLAlchemy(app) + +# Flask views +@app.route('/') +def index(): + return 'Click me to get to Admin!' + + +class Car(db.Model): + __tablename__ = 'cars' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + desc = db.Column(db.String(50)) + + def __unicode__(self): + return self.desc + + +class Tyre(db.Model): + __tablename__ = 'tyres' + car_id = db.Column(db.Integer, db.ForeignKey('cars.id'), primary_key=True) + tyre_id = db.Column(db.Integer, primary_key=True) + car = db.relationship('Car', backref='tyres') + desc = db.Column(db.String(50)) + + +class CarAdmin(sqla.ModelView): + column_display_pk = True + form_columns = ['id', 'desc'] + + +class TyreAdmin(sqla.ModelView): + column_display_pk = True + form_columns = ['car', 'tyre_id', 'desc'] + +# Create admin +admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3') +admin.add_view(CarAdmin(Car, db.session)) +admin.add_view(TyreAdmin(Tyre, db.session)) + +if __name__ == '__main__': + + # Create DB + db.create_all() + + # Start app + app.run(debug=True) diff --git a/pool/shard001/Python/0013591_tasks.py b/pool/shard001/Python/0013591_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..8c1945b26841cc49ec8d03c18f9ee7212ccf28ab --- /dev/null +++ b/pool/shard001/Python/0013591_tasks.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +######################################################################### +# +# Copyright (C) 2017 OSGeo +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +######################################################################### + +"""celery tasks for geonode.layers.""" + +from celery.app import shared_task +from celery.utils.log import get_task_logger + +from geonode.layers.models import Layer + +logger = get_task_logger(__name__) + + +@shared_task(bind=True, queue='cleanup') +def delete_layer(self, object_id): + """ + Deletes a layer. + """ + logger.debug('Deleting Layer ID {0}'.format(object_id)) + try: + layer = Layer.objects.get(id=object_id) + except Layer.DoesNotExist: + return + + layer.delete() diff --git a/pool/shard001/Python/0013592_payara_configuration.py b/pool/shard001/Python/0013592_payara_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..f1470ba20ae1733a311ef52ef890a682c05df737 --- /dev/null +++ b/pool/shard001/Python/0013592_payara_configuration.py @@ -0,0 +1,117 @@ +from .configuration import Configuration +from .constants import Constants +from datetime import datetime +import os + +from uk_gov_phe_erdst_sc import constants + +class PayaraConfiguration(Configuration): + + """ Read-only Payara Server Configuration, setup once """ + + def __init__(self): + super().__init__() + self.output_filename = 'output-' + datetime.now().strftime('%Y-%m-%d-%H%M') + + + def validate(self): + assert self.payara_root_folder is not None + assert self.domain_name is not None + self.__setup_folders() + if self.file_jdbc_jar_path: + self.__setup_jdbc_path() + if self.jdbc_pools: + self.__setup_jdbc_detail() + if self.ldap_realm_name: + self.__setup_ldap_realm( + self.ldap_host, + self.ldap_base_dn, + self.ldap_search_bind_dn, + self.ldap_bind_password, + self.ldap_host_port_number) + + self._validated = True + super().validate() + + + """ Private methods """ + def __setup_folders(self): + self.__setup_asadmin() + + + def __setup_asadmin(self): + self.asadmin = f'{self.payara_root_folder}{os.sep}bin{os.sep}{Constants.ASADMIN}' + + + def __setup_jdbc_path(self): + assert os.path.exists(self.file_jdbc_jar_path) + self.domain_lib_path = \ + f'{self.payara_root_folder}{os.sep}glassfish{os.sep}domains{os.sep}{self.domain_name}{os.sep}lib{os.sep}' + \ + os.path.basename(self.file_jdbc_jar_path) + + + def __setup_jdbc_detail(self): + if self.jdbc_realm_name is None: + self.jdbc_realm_name = Constants.Payara.DEFAULT_JDBC_REALM + self.suffix + + + def __setup_ldap_realm(self, + ldap_host=str(), + base_dn=str(), + search_bind_dn=str(), + search_bind_password=str(), + ldap_port=Constants.DEFAULT_LDAP_PORT_NUMBER): + """ LDAP Connection String """ + + _ldap_host_and_port = \ + 'ldap\\://' + \ + ldap_host + \ + '\\:' + \ + str(ldap_port) + + # The base distinguished name parameter value replaces '=' with '\=' to allow the + # application to generate the configuration correctly. + self.ldap_realm_property = \ + 'directory=' + \ + _ldap_host_and_port + \ + ':base-dn=' + \ + base_dn.replace('=','\\=') + \ + ':jaas-context=ldapRealm' + \ + ':search-bind-dn=' + \ + search_bind_dn + \ + ':search-bind-password=' + \ + search_bind_password + \ + ':group-search-filter=(&(objectClass\\=group)(member\\=%d))' + \ + ':search-filter=(&(objectClass\\=user)(sAMAccountName\\=%s))' + \ + ':java.naming.referral=ignore' + + + """ Public members """ + output_to_console = False + output_command_to_file = False + execute_command = True + delete_default_domain = True + recreate_network_listener = True + recreate_bootstrap = False + + default_admin_listener_port = Constants.Payara.DEFAULT_ADMIN_LISTENER_PORT + http_listener_port = Constants.Payara.DEFAULT_HTTP_LISTENER_PORT + payara_root_folder = None + domain_name = None + output_filename = None + jdbc_realm_name = None + ldap_realm_name = None + jdbc_pools = None + system_properties = None + ldap_realm_name = None + ldap_host = None + ldap_host_port_number = None + ldap_base_dn = None + ldap_search_bind_dn = None + ldap_bind_password = None + + """ Members updated on validation """ + asadmin = None + file_jdbc_jar_path = None + domain_lib_path = None + ldap_realm_property = None \ No newline at end of file diff --git a/pool/shard001/Python/0013594_test_mnist.py b/pool/shard001/Python/0013594_test_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..5523d6438f638865f2b32c97958c6d1c0aaa80c4 --- /dev/null +++ b/pool/shard001/Python/0013594_test_mnist.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +import os +import sys +import tempfile + +import chainer +import chainer.functions as F +import chainer.links as L +import chainer.testing +from chainer import training +from chainer.training import extensions + +import chainermn +from chainermn.extensions.checkpoint import create_multi_node_checkpointer + + +class MLP(chainer.Chain): + def __init__(self, n_units, n_out): + super(MLP, self).__init__() + with self.init_scope(): + self.l1 = L.Linear(784, n_units) + self.l2 = L.Linear(n_units, n_units) + self.l3 = L.Linear(n_units, n_out) + + def __call__(self, x): + h1 = F.relu(self.l1(x)) + h2 = F.relu(self.l2(h1)) + return self.l3(h2) + + +def check_mnist(gpu, display_log=True): + epoch = 5 + batchsize = 100 + n_units = 100 + + comm = chainermn.create_communicator('naive') + if gpu: + device = comm.intra_rank + chainer.cuda.get_device_from_id(device).use() + else: + device = -1 + + model = L.Classifier(MLP(n_units, 10)) + if gpu: + model.to_gpu() + + optimizer = chainermn.create_multi_node_optimizer( + chainer.optimizers.Adam(), comm) + optimizer.setup(model) + + if comm.rank == 0: + train, test = chainer.datasets.get_mnist() + else: + train, test = None, None + + train = chainermn.scatter_dataset(train, comm, shuffle=True) + test = chainermn.scatter_dataset(test, comm, shuffle=True) + + train_iter = chainer.iterators.SerialIterator(train, batchsize) + test_iter = chainer.iterators.SerialIterator(test, batchsize, + repeat=False, + shuffle=False) + + updater = training.StandardUpdater( + train_iter, + optimizer, + device=device + ) + + trainer = training.Trainer(updater, (epoch, 'epoch')) + + # Wrap standard Chainer evaluators by MultiNodeEvaluator. + evaluator = extensions.Evaluator(test_iter, model, device=device) + evaluator = chainermn.create_multi_node_evaluator(evaluator, comm) + trainer.extend(evaluator) + + # Add checkpointer. This is just to check checkpointing runs + # without errors + path = tempfile.mkdtemp(dir='/tmp', prefix=__name__ + '-tmp-') + checkpointer = create_multi_node_checkpointer(name=__name__, comm=comm, + path=path) + trainer.extend(checkpointer, trigger=(1, 'epoch')) + + # Some display and output extensions are necessary only for one worker. + # (Otherwise, there would just be repeated outputs.) + if comm.rank == 0 and display_log: + trainer.extend(extensions.LogReport(trigger=(1, 'epoch')), + trigger=(1, 'epoch')) + trainer.extend(extensions.PrintReport(['epoch', + 'main/loss', + 'validation/main/loss', + 'main/accuracy', + 'validation/main/accuracy', + 'elapsed_time'], + out=sys.stderr), + trigger=(1, 'epoch')) + trainer.run() + + err = evaluator()['validation/main/accuracy'] + assert err > 0.95 + + # Check checkpointer successfully finalized snapshot directory + assert [] == os.listdir(path) + os.removedirs(path) + + +@chainer.testing.attr.slow +def test_mnist(): + check_mnist(False) + + +@chainer.testing.attr.gpu +def test_mnist_gpu(): + check_mnist(True) + + +if __name__ == '__main__': + test_mnist() diff --git a/pool/shard001/Python/0013598_kafka_test.py b/pool/shard001/Python/0013598_kafka_test.py new file mode 100644 index 0000000000000000000000000000000000000000..416c0665e2e91f16b7f276080af19781441c5157 --- /dev/null +++ b/pool/shard001/Python/0013598_kafka_test.py @@ -0,0 +1,70 @@ +import kafka + +print("kafka-python version: {}".format(kafka.__version__)) + +if kafka.__version__ == "0.9.5": + from kafka.client import KafkaClient + from kafka.consumer import SimpleConsumer + from kafka.producer import KeyedProducer +else: + from kafka.client import SimpleClient as KafkaClient + from kafka.consumer import SimpleConsumer + from kafka.producer import KeyedProducer + +import time +import json + +KAFKA_URL = '192.168.10.6:9092' +KAFKA_GROUP = 'kafka_python_perf' +KAFKA_TOPIC = 'raw-events' + +NUM_MESSAGES = 100000 +SIZE_MSG = 369 + + +def write(): + k_client = KafkaClient(KAFKA_URL) + p = KeyedProducer(k_client, + async=False, + req_acks=KeyedProducer.ACK_AFTER_LOCAL_WRITE, + ack_timeout=2000) + messages = [] + for i in xrange(NUM_MESSAGES): + message = json.dumps({'msg': 'X' * SIZE_MSG}) + messages.append(message) + if len(messages) >= 500: + key = int(time.time() * 1000) + p.send_messages(KAFKA_TOPIC, str(key), *messages) + messages = [] + key = int(time.time() * 1000) + p.send_messages(KAFKA_TOPIC, str(key), *messages) + + +def read(fetch_size): + k_client = KafkaClient(KAFKA_URL) + c = SimpleConsumer(k_client, + KAFKA_GROUP, + KAFKA_TOPIC, + auto_commit=False, + fetch_size_bytes=fetch_size, + buffer_size=fetch_size, + max_buffer_size=None) + start_time = None + start_time = time.time() + + i = 0 + for msg in c: + i = i + 1 + if i >= NUM_MESSAGES: + break + + end_time = time.time() + elapsed_time = end_time - start_time + num_messages_per_sec = NUM_MESSAGES / elapsed_time + + print("fetch size {} -> {} messages per second" + .format(fetch_size, num_messages_per_sec)) + +write() +for fetch_size in xrange((1024 * 50), (1024 * 1024 * 2), (1024 * 25)): + read(fetch_size) diff --git a/pool/shard001/Python/0013606_test.py b/pool/shard001/Python/0013606_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fce3feaa70ac219eba92641cb5a62dc8c0e9fef0 --- /dev/null +++ b/pool/shard001/Python/0013606_test.py @@ -0,0 +1,40 @@ +#-*- coding=utf-8 -*- +from flask import Flask, url_for, request, render_template + +app = Flask(__name__) + +@app.route('/hello') +@app.route('/hello/') +def hello_world(name=None): + return render_template('hello.html', name=name) + +@app.route('/index') +def index(): + pass + +@app.route('/login', methods=['GET', 'POST']) +def login(): + pass + +@app.route('/user/') +def profile(username): + pass + +@app.route('/urltest') +def urltest(): + s = "" + s = url_for('static', filename='Readme') +# with app.test_request_context(): +# s += url_for('index') +# s += url_for('login') +# s += url_for('login', next='/') +# s += url_for('profile', username='yang jinyun') + return s + + +if __name__ == '__main__': + app.debug = True + app.logger.debug('A value for debugging') + app.logger.warning('A warning occured (%d apples)', 42) + app.logger.error('An error occured') + app.run(host='0.0.0.0') diff --git a/pool/shard001/Python/0013610_dunehd.py b/pool/shard001/Python/0013610_dunehd.py new file mode 100644 index 0000000000000000000000000000000000000000..efa5e7e607983d943a11a1e2f27c71e8c6b58337 --- /dev/null +++ b/pool/shard001/Python/0013610_dunehd.py @@ -0,0 +1,171 @@ +""" +DuneHD implementation of the media player. + +For more details about this platform, please refer to the documentation +https://home-assistant.io/components/media_player.dunehd/ +""" +import voluptuous as vol + +import homeassistant.helpers.config_validation as cv +from homeassistant.components.media_player import ( + SUPPORT_PAUSE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_NEXT_TRACK, + SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, PLATFORM_SCHEMA, + SUPPORT_PLAY, MediaPlayerDevice) +from homeassistant.const import ( + CONF_HOST, CONF_NAME, STATE_OFF, STATE_PAUSED, STATE_ON, STATE_PLAYING) + +REQUIREMENTS = ['pdunehd==1.3'] + +DEFAULT_NAME = 'DuneHD' + +CONF_SOURCES = 'sources' + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ + vol.Required(CONF_HOST): cv.string, + vol.Optional(CONF_SOURCES): vol.Schema({cv.string: cv.string}), + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, +}) + +DUNEHD_PLAYER_SUPPORT = \ + SUPPORT_PAUSE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \ + SUPPORT_SELECT_SOURCE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \ + SUPPORT_PLAY + + +# pylint: disable=unused-argument +def setup_platform(hass, config, add_devices, discovery_info=None): + """Set up the DuneHD media player platform.""" + from pdunehd import DuneHDPlayer + + sources = config.get(CONF_SOURCES, {}) + host = config.get(CONF_HOST) + name = config.get(CONF_NAME) + + add_devices([DuneHDPlayerEntity(DuneHDPlayer(host), name, sources)], True) + + +class DuneHDPlayerEntity(MediaPlayerDevice): + """Implementation of the Dune HD player.""" + + def __init__(self, player, name, sources): + """Initialize entity to control Dune HD.""" + self._player = player + self._name = name + self._sources = sources + self._media_title = None + self._state = None + + def update(self): + """Update internal status of the entity.""" + self._state = self._player.update_state() + self.__update_title() + return True + + @property + def state(self): + """Return player state.""" + state = STATE_OFF + if 'playback_position' in self._state: + state = STATE_PLAYING + if self._state['player_state'] in ('playing', 'buffering'): + state = STATE_PLAYING + if int(self._state.get('playback_speed', 1234)) == 0: + state = STATE_PAUSED + if self._state['player_state'] == 'navigator': + state = STATE_ON + return state + + @property + def name(self): + """Return the name of the device.""" + return self._name + + @property + def volume_level(self): + """Return the volume level of the media player (0..1).""" + return int(self._state.get('playback_volume', 0)) / 100 + + @property + def is_volume_muted(self): + """Return a boolean if volume is currently muted.""" + return int(self._state.get('playback_mute', 0)) == 1 + + @property + def source_list(self): + """Return a list of available input sources.""" + return list(self._sources.keys()) + + @property + def supported_features(self): + """Flag media player features that are supported.""" + return DUNEHD_PLAYER_SUPPORT + + def volume_up(self): + """Volume up media player.""" + self._state = self._player.volume_up() + + def volume_down(self): + """Volume down media player.""" + self._state = self._player.volume_down() + + def mute_volume(self, mute): + """Mute/unmute player volume.""" + self._state = self._player.mute(mute) + + def turn_off(self): + """Turn off media player.""" + self._media_title = None + self._state = self._player.turn_off() + self.schedule_update_ha_state() + + def turn_on(self): + """Turn off media player.""" + self._state = self._player.turn_on() + self.schedule_update_ha_state() + + def media_play(self): + """Play media player.""" + self._state = self._player.play() + self.schedule_update_ha_state() + + def media_pause(self): + """Pause media player.""" + self._state = self._player.pause() + self.schedule_update_ha_state() + + @property + def media_title(self): + """Return the current media source.""" + self.__update_title() + if self._media_title: + return self._media_title + return self._state.get('playback_url', 'Not playing') + + def __update_title(self): + if self._state['player_state'] == 'bluray_playback': + self._media_title = 'Blu-Ray' + elif 'playback_url' in self._state: + sources = self._sources + sval = sources.values() + skey = sources.keys() + pburl = self._state['playback_url'] + if pburl in sval: + self._media_title = list(skey)[list(sval).index(pburl)] + else: + self._media_title = pburl + + def select_source(self, source): + """Select input source.""" + self._media_title = source + self._state = self._player.launch_media_url(self._sources.get(source)) + self.schedule_update_ha_state() + + def media_previous_track(self): + """Send previous track command.""" + self._state = self._player.previous_track() + self.schedule_update_ha_state() + + def media_next_track(self): + """Send next track command.""" + self._state = self._player.next_track() + self.schedule_update_ha_state() diff --git a/pool/shard001/Python/0013613_camera.py b/pool/shard001/Python/0013613_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad95e40d62f9b050768a0c84095e20b73894d84 --- /dev/null +++ b/pool/shard001/Python/0013613_camera.py @@ -0,0 +1,102 @@ +""" +Camera support for the Skybell HD Doorbell. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/camera.skybell/ +""" +from datetime import timedelta +import logging + +import requests +import voluptuous as vol + +from homeassistant.components.camera import PLATFORM_SCHEMA +from homeassistant.const import CONF_MONITORED_CONDITIONS +import homeassistant.helpers.config_validation as cv + +from homeassistant.components.camera import Camera +from homeassistant.components.skybell import ( + DOMAIN as SKYBELL_DOMAIN, SkybellDevice) + +DEPENDENCIES = ['skybell'] + +_LOGGER = logging.getLogger(__name__) + +SCAN_INTERVAL = timedelta(seconds=90) + +IMAGE_AVATAR = 'avatar' +IMAGE_ACTIVITY = 'activity' + +CONF_ACTIVITY_NAME = 'activity_name' +CONF_AVATAR_NAME = 'avatar_name' + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ + vol.Optional(CONF_MONITORED_CONDITIONS, default=[IMAGE_AVATAR]): + vol.All(cv.ensure_list, [vol.In([IMAGE_AVATAR, IMAGE_ACTIVITY])]), + vol.Optional(CONF_ACTIVITY_NAME): cv.string, + vol.Optional(CONF_AVATAR_NAME): cv.string, +}) + + +def setup_platform(hass, config, add_entities, discovery_info=None): + """Set up the platform for a Skybell device.""" + cond = config[CONF_MONITORED_CONDITIONS] + names = {} + names[IMAGE_ACTIVITY] = config.get(CONF_ACTIVITY_NAME) + names[IMAGE_AVATAR] = config.get(CONF_AVATAR_NAME) + skybell = hass.data.get(SKYBELL_DOMAIN) + + sensors = [] + for device in skybell.get_devices(): + for camera_type in cond: + sensors.append(SkybellCamera(device, camera_type, + names.get(camera_type))) + + add_entities(sensors, True) + + +class SkybellCamera(SkybellDevice, Camera): + """A camera implementation for Skybell devices.""" + + def __init__(self, device, camera_type, name=None): + """Initialize a camera for a Skybell device.""" + self._type = camera_type + SkybellDevice.__init__(self, device) + Camera.__init__(self) + if name is not None: + self._name = "{} {}".format(self._device.name, name) + else: + self._name = self._device.name + self._url = None + self._response = None + + @property + def name(self): + """Return the name of the sensor.""" + return self._name + + @property + def image_url(self): + """Get the camera image url based on type.""" + if self._type == IMAGE_ACTIVITY: + return self._device.activity_image + return self._device.image + + def camera_image(self): + """Get the latest camera image.""" + super().update() + + if self._url != self.image_url: + self._url = self.image_url + + try: + self._response = requests.get( + self._url, stream=True, timeout=10) + except requests.HTTPError as err: + _LOGGER.warning("Failed to get camera image: %s", err) + self._response = None + + if not self._response: + return None + + return self._response.content diff --git a/pool/shard001/Python/0013620_browser.py b/pool/shard001/Python/0013620_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..379eb5a811bf2ba2773d20bfe0570e7e4c13a74c --- /dev/null +++ b/pool/shard001/Python/0013620_browser.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +# Copyright(C) 2018 Phyks (Lucas Verney) +# +# This file is part of a weboob module. +# +# This weboob module is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This weboob module is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this weboob module. If not, see . + +from __future__ import unicode_literals + + +from weboob.browser import PagesBrowser, URL + +from .pages import RecipePage, SearchPage + + +class JournaldesfemmesBrowser(PagesBrowser): + BASEURL = 'http://cuisine.journaldesfemmes.fr' + + recipe = URL(r'/recette/(?P.+)', RecipePage) + search = URL(r'/s/\?f_recherche=(?P.+)', SearchPage) + + def get_recipe(self, id, obj=None): + return self.recipe.go(id=id).get_recipe(obj=obj) + + def get_comments(self, id): + return self.recipe.stay_or_go(id=id).get_comments() + + def search_recipes(self, pattern): + return self.search.go(search=pattern).get_recipes() diff --git a/pool/shard001/Python/0013623_cros_interface_unittest.py b/pool/shard001/Python/0013623_cros_interface_unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..994b05192c0d8dfaa00679f1466021a656af4638 --- /dev/null +++ b/pool/shard001/Python/0013623_cros_interface_unittest.py @@ -0,0 +1,158 @@ +# 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. + +# TODO(nduca): Rewrite what some of these tests to use mocks instead of +# actually talking to the device. This would improve our coverage quite +# a bit. +import unittest +import socket +import sys + +from telemetry.core import util +from telemetry.core.chrome import cros_browser_backend +from telemetry.core.chrome import cros_interface +from telemetry.unittest import options_for_unittests +from telemetry.unittest import RequiresBrowserOfType + +class CrOSInterfaceTest(unittest.TestCase): + @RequiresBrowserOfType('cros-chrome') + def testPushContents(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + cri.RunCmdOnDevice(['rm', '-rf', '/tmp/testPushContents']) + cri.PushContents('hello world', '/tmp/testPushContents') + contents = cri.GetFileContents('/tmp/testPushContents') + self.assertEquals(contents, 'hello world') + + @RequiresBrowserOfType('cros-chrome') + def testExists(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + self.assertTrue(cri.FileExistsOnDevice('/proc/cpuinfo')) + self.assertTrue(cri.FileExistsOnDevice('/etc/passwd')) + self.assertFalse(cri.FileExistsOnDevice('/etc/sdlfsdjflskfjsflj')) + + def testExistsLocal(self): + if not sys.platform.startswith('linux'): + return + + cri = cros_interface.CrOSInterface() + self.assertTrue(cri.FileExistsOnDevice('/proc/cpuinfo')) + self.assertTrue(cri.FileExistsOnDevice('/etc/passwd')) + self.assertFalse(cri.FileExistsOnDevice('/etc/sdlfsdjflskfjsflj')) + + @RequiresBrowserOfType('cros-chrome') + def testGetFileContents(self): # pylint: disable=R0201 + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + hosts = cri.GetFileContents('/etc/hosts') + assert hosts.startswith('# /etc/hosts') + + @RequiresBrowserOfType('cros-chrome') + def testGetFileContentsForSomethingThatDoesntExist(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + self.assertRaises( + OSError, + lambda: cri.GetFileContents('/tmp/209fuslfskjf/dfsfsf')) + + @RequiresBrowserOfType('cros-chrome') + def testIsServiceRunning(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + + self.assertTrue(cri.IsServiceRunning('openssh-server')) + + def testIsServiceRunningLocal(self): + if not sys.platform.startswith('linux'): + return + cri = cros_interface.CrOSInterface() + self.assertTrue(cri.IsServiceRunning('dbus')) + + @RequiresBrowserOfType('cros-chrome') + def testGetRemotePortAndIsHTTPServerRunningOnPort(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + + # Create local server. + sock = socket.socket() + sock.bind(('', 0)) + port = sock.getsockname()[1] + sock.listen(0) + + # Get remote port and ensure that it was unused. + remote_port = cri.GetRemotePort() + self.assertFalse(cri.IsHTTPServerRunningOnPort(remote_port)) + + # Forward local server's port to remote device's remote_port. + forwarder = cros_browser_backend.SSHForwarder( + cri, 'R', util.PortPair(port, remote_port)) + + # At this point, remote device should be able to connect to local server. + self.assertTrue(cri.IsHTTPServerRunningOnPort(remote_port)) + + # Next remote port shouldn't be the same as remote_port, since remote_port + # is now in use. + self.assertTrue(cri.GetRemotePort() != remote_port) + + # Close forwarder and local server ports. + forwarder.Close() + sock.close() + + # Device should no longer be able to connect to remote_port since it is no + # longer in use. + self.assertFalse(cri.IsHTTPServerRunningOnPort(remote_port)) + + @RequiresBrowserOfType('cros-chrome') + def testGetRemotePortReservedPorts(self): + remote = options_for_unittests.GetCopy().cros_remote + cri = cros_interface.CrOSInterface( + remote, + options_for_unittests.GetCopy().cros_ssh_identity) + + # Should return 2 separate ports even though the first one isn't technically + # being used yet. + remote_port_1 = cri.GetRemotePort() + remote_port_2 = cri.GetRemotePort() + + self.assertTrue(remote_port_1 != remote_port_2) + + # TODO(tengs): It would be best if we can filter this test and other tests + # that need to be run locally based on the platform of the system browser. + def testEscapeCmdArguments(self): + ''' Commands and their arguments that are executed through the cros + interface should follow bash syntax. This test needs to run on remotely + and locally on the device to check for consistency. + ''' + if not sys.platform.startswith('linux'): + return + + cri = cros_interface.CrOSInterface( + options_for_unittests.GetCopy().cros_remote, + options_for_unittests.GetCopy().cros_ssh_identity) + + # Check arguments with no special characters + stdout, _ = cri.RunCmdOnDevice(['echo', '--arg1=value1', '--arg2=value2', + '--arg3="value3"']) + assert(stdout.strip() == '--arg1=value1 --arg2=value2 --arg3=value3') + + # Check argument with special characters escaped + stdout, _ = cri.RunCmdOnDevice(['echo', '--arg=A\\; echo \\"B\\"']) + assert(stdout.strip() == '--arg=A; echo "B"') + + # Check argument with special characters in quotes + stdout, _ = cri.RunCmdOnDevice(['echo', "--arg='$HOME;;$PATH'"]) + assert(stdout.strip() == "--arg=$HOME;;$PATH") diff --git a/pool/shard001/Python/0013624_test_r_sub_scalar.py b/pool/shard001/Python/0013624_test_r_sub_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..48decc002b77d5a3d2998125f7cad15dc629887b --- /dev/null +++ b/pool/shard001/Python/0013624_test_r_sub_scalar.py @@ -0,0 +1,52 @@ +# Copyright 2017,2018,2019,2020,2021 Sony Corporation. +# +# 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 pytest +import numpy as np +import nnabla.functions as F +from nbla_test_utils import list_context + +ctxs = list_context('RSubScalar') + + +def ref_r_sub_scalar(x, val): + return val - x + + +@pytest.mark.parametrize("ctx, func_name", ctxs) +@pytest.mark.parametrize("seed", [315]) +@pytest.mark.parametrize("val", [0.5, 1, 2]) +def test_r_sub_scalar_forward_backward(seed, val, ctx, func_name): + from nbla_test_utils import cap_ignore_region, function_tester + rng = np.random.RandomState(seed) + inputs = [rng.randn(2, 3, 4).astype(np.float32)] + function_tester(rng, F.r_sub_scalar, ref_r_sub_scalar, + inputs, func_args=[val], ctx=ctx, func_name=func_name) + + +@pytest.mark.parametrize("ctx, func_name", ctxs) +@pytest.mark.parametrize("seed", [313]) +@pytest.mark.parametrize("val", [0.5, 1, 2]) +def test_r_sub_scalar_double_backward(seed, val, ctx, func_name): + from nbla_test_utils import backward_function_tester, cap_ignore_region + rng = np.random.RandomState(seed) + inputs = [ + cap_ignore_region( + rng.randn(2, 3).astype(np.float32) * 3, (-0.5, 0.5))] + backward_function_tester(rng, F.r_sub_scalar, + inputs=inputs, + func_args=[val], func_kwargs={}, + atol_accum=1e-3, + dstep=1e-3, + ctx=ctx) diff --git a/pool/shard001/Python/0013628_CompiledStateDict.py b/pool/shard001/Python/0013628_CompiledStateDict.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f7f7d1b13e4db3d2f23328f91d62ac1cd75525 --- /dev/null +++ b/pool/shard001/Python/0013628_CompiledStateDict.py @@ -0,0 +1,29 @@ +from collections import deque + +from WeightedRandomizer import WeightedRandomizer + + +class CompiledStateDict: + """ + A compiled state to future mapping representing a n-th order Markov chain. + """ + def __init__(self, states): + self._states = {s: WeightedRandomizer(f.most_common()) + for s, f in states.iteritems()} + + def __getitem__(self, state): + """ + Get a predictor for the future element given a state. + + Collapses the given state until it can find one for which probable + futures exist (in the event a state never present in the training data + is encountered). + """ + state = deque(state) + + # Not infinite because there are always predictions for the empty state + while True: + try: + return self._states[tuple(state)] + except KeyError: + state.popleft() diff --git a/pool/shard001/Python/0013637_test_rio_blocks.py b/pool/shard001/Python/0013637_test_rio_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..51397dd9179517e4605127849fbdd40ba0f9cf00 --- /dev/null +++ b/pool/shard001/Python/0013637_test_rio_blocks.py @@ -0,0 +1,156 @@ +"""Unittests for $ rio blocks""" + + +import json +import re + +import numpy as np + +import rasterio +from rasterio.warp import transform_bounds +from rasterio.compat import zip_longest +from rasterio.rio.main import main_group + + +def check_features_block_windows(features, src, bidx): + + """Compare GeoJSON features to a datasource's blocks + windows. + + Parameters + ---------- + features : iter + GeoJSON features. + src : RasterReader + Open input datasource. + + Returns + ------- + bool + ``True`` if the two block/window streams match and ``False`` otherwise. + """ + + out = [] + iterator = zip_longest(features, src.block_windows(bidx=bidx)) + for feat, (block, window) in iterator: + + out.append(np.array_equal( + json.loads(feat['properties']['block']), + block)) + + f_win = feat['properties']['window'] + assert f_win['col_off'] == window.col_off + assert f_win['row_off'] == window.row_off + + return all(out) + + +def test_windows(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', path_rgb_byte_tif]) + assert result.exit_code == 0 + + fc = json.loads(result.output) + + with rasterio.open(path_rgb_byte_tif) as src: + block_windows = tuple(src.block_windows()) + + # Check the coordinates of the first output feature + actual_first = fc['features'][0] + expected_first = block_windows[0] + bounds = src.window_bounds(expected_first[1]) + xmin, ymin, xmax, ymax = transform_bounds(src.crs, 'EPSG:4326', *bounds) + coordinates = [[xmin, ymin], [xmin, ymax], [xmax, ymax], [xmax, ymin]] + assert np.array_equal( + actual_first['geometry']['coordinates'][0], coordinates) + + assert len(fc['features']) == len(block_windows) + assert check_features_block_windows(fc['features'], src, bidx=1) + + +def test_windows_sequence(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--sequence']) + assert result.exit_code == 0 + + features = tuple(map(json.loads, result.output.splitlines())) + + with rasterio.open(path_rgb_byte_tif) as src: + + # Check the coordinates of the first output feature + actual_first = features[0] + expected_first = next(src.block_windows()) + bounds = src.window_bounds(expected_first[1]) + xmin, ymin, xmax, ymax = transform_bounds(src.crs, 'EPSG:4326', *bounds) + coordinates = [[xmin, ymin], [xmin, ymax], [xmax, ymax], [xmax, ymin]] + assert np.array_equal( + actual_first['geometry']['coordinates'][0], coordinates) + + assert check_features_block_windows(features, src, bidx=1) + + +def test_windows_precision(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--precision', 1]) + assert result.exit_code == 0 + assert result.output.count('"FeatureCollection"') == 1 + assert result.output.count('"Feature"') == 240 + assert re.search(r'\d*\.\d{2,}', result.output) is None + + +def test_windows_indent(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--indent', 4]) + assert result.exit_code == 0 + + lines = result.output.splitlines() + assert result.output.count('"FeatureCollection') == 1 + assert result.output.count('"Feature"') == 240 + assert len(lines) == 8651 + for l in lines: + if l.strip() not in ('{', '}'): + assert l.startswith(' ') + + +def test_windows_compact(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--compact']) + assert result.exit_code == 0 + + assert result.output.count('"FeatureCollection') == 1 + assert result.output.count('"Feature"') == 240 + assert result.output.count('", "') == 0 + assert result.output.count(': ') == 0 + + +def test_windows_exception(runner, path_rgb_byte_tif): + """Tests the try/except that wraps the command logic. The input file does + not have 4 bands. + """ + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--bidx', 4]) + assert result.exit_code == 2 + assert "Not a valid band index" in result.output + + +def test_windows_projected(runner, path_rgb_byte_tif): + result = runner.invoke(main_group, [ + 'blocks', + path_rgb_byte_tif, + '--projected']) + assert result.exit_code == 0 + + fc = json.loads(result.output) + + with rasterio.open(path_rgb_byte_tif) as src: + assert np.array_equal(fc['bbox'], src.bounds) + assert check_features_block_windows(fc['features'], src, bidx=1) diff --git a/pool/shard001/Python/0013640_royal_kino.py b/pool/shard001/Python/0013640_royal_kino.py new file mode 100644 index 0000000000000000000000000000000000000000..3e113df28ccd4ccad2550d309169ad3179571813 --- /dev/null +++ b/pool/shard001/Python/0013640_royal_kino.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +import json + +import scrapy + +from scraper.items import Movie + + +class RoyalKinoSpider(scrapy.Spider): + name = "royal_kino" + allowed_domains = ["kinoheld.de"] + start_urls = ( + 'https://www.kinoheld.de/kino-muenchen/royal-filmpalast?mode=widget&layout=movies&target=self&rb=1&ref=mobile', + ) + + def parse(self, response): + result = response.css("script#data-layer").re("dataLayer\.push\((.+?)\);") + if not result: + return + try: + result = json.loads(result[0]) + except json.JSONDecodeError: + return + for movie in result["movies"].values(): + yield self.process_movie(movie) + + def process_movie(self, movie): + return Movie(title=movie["name"], + cinema=self.name, + genre=movie["genre"]) diff --git a/pool/shard001/Python/0013647_test_exception.py b/pool/shard001/Python/0013647_test_exception.py new file mode 100644 index 0000000000000000000000000000000000000000..7b100daebc19bb92eabad149ce4b25b6fb886269 --- /dev/null +++ b/pool/shard001/Python/0013647_test_exception.py @@ -0,0 +1,66 @@ +from unittest.mock import Mock +import pytest + +from boxsdk.exception import BoxAPIException, BoxOAuthException +from boxsdk.network.default_network import DefaultNetworkResponse + + +def test_box_api_exception(): + status = 400 + code = 'code' + message = 'message' + request_id = '12345' + headers = {'header': 'value'} + url = 'https://example.com' + method = 'GET' + context_info = {'context': 'value'} + box_exception = BoxAPIException( + status, + code=code, + message=message, + request_id=request_id, + headers=headers, + url=url, + method=method, + context_info=context_info, + ) + assert box_exception.status == status + assert box_exception.code == code + assert box_exception.message == message + assert box_exception.request_id == request_id + assert box_exception.headers == headers # pylint:disable=protected-access + assert box_exception.url == url + assert box_exception.method == method + assert box_exception.context_info == context_info + assert str(box_exception) == f'''Message: {message} +Status: {status} +Code: {code} +Request ID: {request_id} +Headers: {headers} +URL: {url} +Method: {method} +Context Info: {context_info}''' + + +@pytest.mark.parametrize('has_network_response', [True, False]) +def test_box_oauth_exception(has_network_response): + status = 400 + message = 'message' + url = 'https://example.com' + method = 'GET' + headers = {'header': 'value'} + network_response = Mock(DefaultNetworkResponse, headers=headers) if has_network_response else None + box_exception = BoxOAuthException( + status, + message=message, + url=url, + method=method, + network_response=network_response, + ) + assert str(box_exception) == f''' +Message: {message} +Status: {status} +URL: {url} +Method: {method} +Headers: {headers if has_network_response else 'N/A'}''' + assert box_exception.network_response is network_response diff --git a/pool/shard001/Python/0013648_git.py b/pool/shard001/Python/0013648_git.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4b0aff3ed37611c50852d6a24aeedea7e29e4a --- /dev/null +++ b/pool/shard001/Python/0013648_git.py @@ -0,0 +1,194 @@ +import tempfile +import re +import os.path +from pip.util import call_subprocess +from pip.util import display_path, rmtree +from pip.vcs import vcs, VersionControl +from pip.log import logger +from pip.backwardcompat import url2pathname, urlparse +urlsplit = urlparse.urlsplit +urlunsplit = urlparse.urlunsplit + + +class Git(VersionControl): + name = 'git' + dirname = '.git' + repo_name = 'clone' + schemes = ('git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file') + bundle_file = 'git-clone.txt' + guide = ('# This was a Git repo; to make it a repo again run:\n' + 'git init\ngit remote add origin %(url)s -f\ngit checkout %(rev)s\n') + + def __init__(self, url=None, *args, **kwargs): + + # Works around an apparent Git bug + # (see http://article.gmane.org/gmane.comp.version-control.git/146500) + if url: + scheme, netloc, path, query, fragment = urlsplit(url) + if scheme.endswith('file'): + initial_slashes = path[:-len(path.lstrip('/'))] + newpath = initial_slashes + url2pathname(path).replace('\\', '/').lstrip('/') + url = urlunsplit((scheme, netloc, newpath, query, fragment)) + after_plus = scheme.find('+') + 1 + url = scheme[:after_plus] + urlunsplit((scheme[after_plus:], netloc, newpath, query, fragment)) + + super(Git, self).__init__(url, *args, **kwargs) + + def parse_vcs_bundle_file(self, content): + url = rev = None + for line in content.splitlines(): + if not line.strip() or line.strip().startswith('#'): + continue + url_match = re.search(r'git\s*remote\s*add\s*origin(.*)\s*-f', line) + if url_match: + url = url_match.group(1).strip() + rev_match = re.search(r'^git\s*checkout\s*-q\s*(.*)\s*', line) + if rev_match: + rev = rev_match.group(1).strip() + if url and rev: + return url, rev + return None, None + + def export(self, location): + """Export the Git repository at the url to the destination location""" + temp_dir = tempfile.mkdtemp('-export', 'pip-') + self.unpack(temp_dir) + try: + if not location.endswith('/'): + location = location + '/' + call_subprocess( + [self.cmd, 'checkout-index', '-a', '-f', '--prefix', location], + filter_stdout=self._filter, show_stdout=False, cwd=temp_dir) + finally: + rmtree(temp_dir) + + def check_rev_options(self, rev, dest, rev_options): + """Check the revision options before checkout to compensate that tags + and branches may need origin/ as a prefix. + Returns the SHA1 of the branch or tag if found. + """ + revisions = self.get_refs(dest) + + origin_rev = 'origin/%s' % rev + if origin_rev in revisions: + # remote branch + return [revisions[origin_rev]] + elif rev in revisions: + # a local tag or branch name + return [revisions[rev]] + else: + logger.warn("Could not find a tag or branch '%s', assuming commit." % rev) + return rev_options + + def switch(self, dest, url, rev_options): + call_subprocess( + [self.cmd, 'config', 'remote.origin.url', url], cwd=dest) + call_subprocess( + [self.cmd, 'checkout', '-q'] + rev_options, cwd=dest) + + self.update_submodules(dest) + + def update(self, dest, rev_options): + # First fetch changes from the default remote + call_subprocess([self.cmd, 'fetch', '-q'], cwd=dest) + # Then reset to wanted revision (maby even origin/master) + if rev_options: + rev_options = self.check_rev_options(rev_options[0], dest, rev_options) + call_subprocess([self.cmd, 'reset', '--hard', '-q'] + rev_options, cwd=dest) + #: update submodules + self.update_submodules(dest) + + def obtain(self, dest): + url, rev = self.get_url_rev() + if rev: + rev_options = [rev] + rev_display = ' (to %s)' % rev + else: + rev_options = ['origin/master'] + rev_display = '' + if self.check_destination(dest, url, rev_options, rev_display): + logger.notify('Cloning %s%s to %s' % (url, rev_display, display_path(dest))) + call_subprocess([self.cmd, 'clone', '-q', url, dest]) + #: repo may contain submodules + self.update_submodules(dest) + if rev: + rev_options = self.check_rev_options(rev, dest, rev_options) + # Only do a checkout if rev_options differs from HEAD + if not self.get_revision(dest).startswith(rev_options[0]): + call_subprocess([self.cmd, 'checkout', '-q'] + rev_options, cwd=dest) + + def get_url(self, location): + url = call_subprocess( + [self.cmd, 'config', 'remote.origin.url'], + show_stdout=False, cwd=location) + return url.strip() + + def get_revision(self, location): + current_rev = call_subprocess( + [self.cmd, 'rev-parse', 'HEAD'], show_stdout=False, cwd=location) + return current_rev.strip() + + def get_refs(self, location): + """Return map of named refs (branches or tags) to commit hashes.""" + output = call_subprocess([self.cmd, 'show-ref'], + show_stdout=False, cwd=location) + rv = {} + for line in output.strip().splitlines(): + commit, ref = line.split(' ', 1) + ref = ref.strip() + ref_name = None + if ref.startswith('refs/remotes/'): + ref_name = ref[len('refs/remotes/'):] + elif ref.startswith('refs/heads/'): + ref_name = ref[len('refs/heads/'):] + elif ref.startswith('refs/tags/'): + ref_name = ref[len('refs/tags/'):] + if ref_name is not None: + rv[ref_name] = commit.strip() + return rv + + def get_src_requirement(self, dist, location, find_tags): + repo = self.get_url(location) + if not repo.lower().startswith('git:'): + repo = 'git+' + repo + egg_project_name = dist.egg_name().split('-', 1)[0] + if not repo: + return None + current_rev = self.get_revision(location) + refs = self.get_refs(location) + # refs maps names to commit hashes; we need the inverse + # if multiple names map to a single commit, this arbitrarily picks one + names_by_commit = dict((commit, ref) for ref, commit in refs.items()) + + if current_rev in names_by_commit: + # It's a tag + full_egg_name = '%s-%s' % (egg_project_name, names_by_commit[current_rev]) + else: + full_egg_name = '%s-dev' % egg_project_name + + return '%s@%s#egg=%s' % (repo, current_rev, full_egg_name) + + def get_url_rev(self): + """ + Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. + That's required because although they use SSH they sometimes doesn't + work with a ssh:// scheme (e.g. Github). But we need a scheme for + parsing. Hence we remove it again afterwards and return it as a stub. + """ + if not '://' in self.url: + assert not 'file:' in self.url + self.url = self.url.replace('git+', 'git+ssh://') + url, rev = super(Git, self).get_url_rev() + url = url.replace('ssh://', '') + else: + url, rev = super(Git, self).get_url_rev() + + return url, rev + + def update_submodules(self, location): + if not os.path.exists(os.path.join(location, '.gitmodules')): + return + call_subprocess([self.cmd, 'submodule', 'update', '--init', '--recursive', '-q'], + cwd=location) + +vcs.register(Git) diff --git a/pool/shard001/Python/0013651_engagement.py b/pool/shard001/Python/0013651_engagement.py new file mode 100644 index 0000000000000000000000000000000000000000..61dca9d4a3f3f73ebb1bb9fd7751143daae4d308 --- /dev/null +++ b/pool/shard001/Python/0013651_engagement.py @@ -0,0 +1,165 @@ +import logging + +from django.conf import settings +from django.http import Http404 +from django.utils.translation import ugettext_lazy as _ + +from analyticsclient.exceptions import NotFoundError + +from courses.presenters.engagement import (CourseEngagementActivityPresenter, CourseEngagementVideoPresenter) +from courses.views import (CourseStructureMixin, CourseStructureExceptionMixin, CourseTemplateWithNavView) + + +logger = logging.getLogger(__name__) + + +class EngagementTemplateView(CourseTemplateWithNavView): + """ + Base view for course engagement pages. + """ + secondary_nav_items = [ + # Translators: Content as in course content (e.g. things, not the feeling) + {'name': 'content', 'label': _('Content'), 'view': 'courses:engagement:content'}, + {'name': 'videos', 'label': _('Videos'), 'view': 'courses:engagement:videos', + 'switch': 'enable_engagement_videos_pages'}, + ] + active_primary_nav_item = 'engagement' + presenter = None + + +class EngagementContentView(EngagementTemplateView): + template_name = 'courses/engagement_content.html' + page_title = _('Engagement Content') + page_name = 'engagement_content' + active_secondary_nav_item = 'content' + + # Translators: Do not translate UTC. + update_message = _('Course engagement data was last updated %(update_date)s at %(update_time)s UTC.') + + def get_context_data(self, **kwargs): + context = super(EngagementContentView, self).get_context_data(**kwargs) + self.presenter = CourseEngagementActivityPresenter(self.course_id) + + summary = None + trends = None + last_updated = None + try: + summary, trends = self.presenter.get_summary_and_trend_data() + last_updated = summary['last_updated'] + except NotFoundError: + logger.error("Failed to retrieve engagement content data for %s.", self.course_id) + + context['js_data']['course']['engagementTrends'] = trends + context.update({ + 'summary': summary, + 'update_message': self.get_last_updated_message(last_updated) + }) + context['page_data'] = self.get_page_data(context) + + return context + + +class EngagementVideoContentTemplateView(CourseStructureMixin, CourseStructureExceptionMixin, EngagementTemplateView): + page_title = _('Engagement Videos') + active_secondary_nav_item = 'videos' + section_id = None + subsection_id = None + # Translators: Do not translate UTC. + update_message = _('Video data was last updated %(update_date)s at %(update_time)s UTC.') + no_data_message = _('Looks like no one has watched any videos in these sections.') + + def get_context_data(self, **kwargs): + self.presenter = CourseEngagementVideoPresenter(self.access_token, self.course_id) + context = super(EngagementVideoContentTemplateView, self).get_context_data(**kwargs) + context.update({ + 'sections': self.presenter.sections(), + 'update_message': self.get_last_updated_message(self.presenter.last_updated), + 'no_data_message': self.no_data_message + }) + + return context + + +class EngagementVideoCourse(EngagementVideoContentTemplateView): + template_name = 'courses/engagement_video_course.html' + page_name = 'engagement_videos' + + def get_context_data(self, **kwargs): + context = super(EngagementVideoCourse, self).get_context_data(**kwargs) + self.set_primary_content(context, self.presenter.sections()) + context['js_data']['course']['contentTableHeading'] = _('Section Name') + context.update({ + 'page_data': self.get_page_data(context) + }) + return context + + +class EngagementVideoSection(EngagementVideoContentTemplateView): + template_name = 'courses/engagement_video_by_section.html' + page_name = 'engagement_videos' + + def get_context_data(self, **kwargs): + context = super(EngagementVideoSection, self).get_context_data(**kwargs) + sub_sections = self.presenter.subsections(self.section_id) + self.set_primary_content(context, sub_sections) + context['js_data']['course']['contentTableHeading'] = _('Subsection Name') + context.update({ + 'page_data': self.get_page_data(context) + }) + return context + + +class EngagementVideoSubsection(EngagementVideoContentTemplateView): + template_name = 'courses/engagement_video_by_subsection.html' + page_name = 'engagement_videos' + + def get_context_data(self, **kwargs): + context = super(EngagementVideoSubsection, self).get_context_data(**kwargs) + videos = self.presenter.subsection_children(self.section_id, self.subsection_id) + self.set_primary_content(context, videos) + context['js_data']['course'].update({ + 'contentTableHeading': _('Video Name'), + }) + context.update({ + 'page_data': self.get_page_data(context) + }) + return context + + +class EngagementVideoTimeline(EngagementVideoContentTemplateView): + template_name = 'courses/engagement_video_timeline.html' + page_name = 'engagement_videos' + video_id = None + + def dispatch(self, request, *args, **kwargs): + self.video_id = kwargs.get('video_id', None) + return super(EngagementVideoTimeline, self).dispatch(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + context = super(EngagementVideoTimeline, self).get_context_data(**kwargs) + + video_data_id = self.presenter.module_id_to_data_id({'id': self.video_id}) + video_module = self.presenter.subsection_child(self.section_id, self.subsection_id, video_data_id) + if video_module: + timeline = self.presenter.get_video_timeline(video_module) + + videos = self.presenter.subsection_children(self.section_id, self.subsection_id) + self.set_primary_content(context, videos) + context.update({ + 'video': self.presenter.block(self.video_id), + 'summary_metrics': video_module, + 'view_live_url': self.presenter.build_view_live_url(settings.LMS_COURSE_SHORTCUT_BASE_URL, + self.video_id), + 'page_data': self.get_page_data(context) + }) + + context['js_data']['course'].update({ + 'videoTimeline': timeline, + }) + context.update({ + 'page_data': self.get_page_data(context) + }) + else: + raise Http404 + + return context diff --git a/pool/shard001/Python/0013653_flaskrestful_example.py b/pool/shard001/Python/0013653_flaskrestful_example.py new file mode 100644 index 0000000000000000000000000000000000000000..b2edf69c596ec497c1264c20e8540f7c75541087 --- /dev/null +++ b/pool/shard001/Python/0013653_flaskrestful_example.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +"""A simple number and datetime addition JSON API. +Run the app: + + $ python examples/flaskrestful_example.py + +Try the following with httpie (a cURL-like utility, http://httpie.org): + + $ pip install httpie + $ http GET :5001/ + $ http GET :5001/ name==Ada + $ http POST :5001/add x=40 y=2 + $ http POST :5001/dateadd value=1973-04-10 addend=63 + $ http POST :5001/dateadd value=2014-10-23 addend=525600 unit=minutes +""" +import datetime as dt + +from dateutil import parser as dateparser +from flask import Flask +from flask.ext import restful + +from webargs import Arg, ValidationError +from webargs.flaskparser import use_args, use_kwargs, parser + +app = Flask(__name__) +api = restful.Api(app) + + +class IndexResource(restful.Resource): + """A welcome page.""" + + hello_args = { + 'name': Arg(str, default='Friend') + } + + @use_args(hello_args) + def get(self, args): + return {'message': 'Welcome, {}!'.format(args['name'])} + + +class AddResource(restful.Resource): + """An addition endpoint.""" + + add_args = { + 'x': Arg(float, required=True), + 'y': Arg(float, required=True), + } + + @use_kwargs(add_args) + def post(self, x, y): + """An addition endpoint.""" + return {'result': x + y} + + +def string_to_datetime(val): + return dateparser.parse(val) + +def validate_unit(val): + if val not in ['minutes', 'days']: + raise ValidationError("Unit must be either 'minutes' or 'days'.") + +class DateAddResource(restful.Resource): + + dateadd_args = { + 'value': Arg(default=dt.datetime.utcnow, use=string_to_datetime), + 'addend': Arg(int, required=True, validate=lambda val: val >= 0), + 'unit': Arg(str, validate=validate_unit) + } + + @use_kwargs(dateadd_args) + def post(self, value, addend, unit): + """A datetime adder endpoint.""" + if unit == 'minutes': + delta = dt.timedelta(minutes=addend) + else: + delta = dt.timedelta(days=addend) + result = value + delta + return {'result': result.isoformat()} + +# This error handler is necessary for usage with Flask-RESTful +@parser.error_handler +def handle_request_parsing_error(err): + """webargs error handler that uses Flask-RESTful's abort function to return + a JSON error response to the client. + """ + code, msg = getattr(err, 'status_code', 400), getattr(err, 'message', 'Invalid Request') + restful.abort(code, message=msg) + +if __name__ == '__main__': + api.add_resource(IndexResource, '/') + api.add_resource(AddResource, '/add') + api.add_resource(DateAddResource, '/dateadd') + app.run(port=5001, debug=True) diff --git a/pool/shard001/Python/0013658_getnames.py b/pool/shard001/Python/0013658_getnames.py new file mode 100644 index 0000000000000000000000000000000000000000..a153ab905971f72d3e1b7819c1df3c8a3dfdd4a1 --- /dev/null +++ b/pool/shard001/Python/0013658_getnames.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +from SPARQLWrapper import SPARQLWrapper, JSON +import sys + + +def query_dbpedia(query): + """Makes SPARQL query against dbpedia.""" + sparql = SPARQLWrapper("http://dbpedia.org/sparql") + sparql.setQuery(query) + sparql.setReturnFormat(JSON) + try: + results = sparql.query().convert() + return results['results']['bindings'] + except ValueError: + return None + + +def get_count(ont_class): + """Returns count of 'ont_class' names from dbpedia.""" + results = query_dbpedia(""" + SELECT COUNT(?n) AS ?c WHERE { + ?p a . + ?p foaf:name ?n . + } + """) + return int(results[0]['c']['value']) + + +def dump(ont_class, limit=1000, offset=0): + """Dumps 'limit' names of 'ont_class' objects from 'offset'.""" + results = query_dbpedia(""" + SELECT ?n, ?s, ?b, ?t WHERE { + ?p a . + ?p dbpedia-owl:wikiPageID ?s . + ?p dbpedia-owl:birthDate ?b . + ?p dbpedia-owl:thumbnail ?t . + ?p foaf:name ?n . + } LIMIT """ + str(limit) + ' OFFSET ' + str(offset) + ) + if results: + res = set() + for result in results: + tmp = result['n']['value'].split(',') + out = tmp[0].strip() + if len(tmp) > 1: + out = tmp[1][1:].strip() + ' ' + tmp[0].strip() + out += '\t' + result['s']['value'] + out += '\t' + result['b']['value'] + out += '\t' + result['t']['value'] + res.add(out.replace('"', '')) + for result in sorted(res): + print(result.encode('utf-8')) + else: + sys.stderr.write('Error in offset: ' + str(offset) + '\n') + + +if __name__ == '__main__': + for arg in sys.argv[1:]: + sys.stderr.write(arg + ': ' + str(get_count(arg)) + '\n') + for offset in range(0, get_count(arg), 10000): + if offset % 100000 == 0: + sys.stderr.write('Offset: ' + str(offset) + '\n') + dump(arg, 10000, offset) + +# vi:set et sts=4 sw=4 ts=4: diff --git a/pool/shard001/Python/0013660_vlan.py b/pool/shard001/Python/0013660_vlan.py new file mode 100644 index 0000000000000000000000000000000000000000..9b8d1a0705be537cb9dfbc792b837181c57caab2 --- /dev/null +++ b/pool/shard001/Python/0013660_vlan.py @@ -0,0 +1,33 @@ +""" +vlan.py: Host subclass that uses a VLAN tag for the default interface. +Dependencies: + This class depends on the "vlan" package + $ sudo apt-get install vlan +""" + +from mininet.node import Host + +class VLANHost(Host): + "Host connected to VLAN interface" + + def config(self, vlan=100, **params): + """Configure VLANHost according to (optional) parameters: + vlan: VLAN ID for default interface""" + + r = super(VLANHost, self).config(**params) + + intf = self.defaultIntf() + # remove IP from default, "physical" interface + self.cmd('ifconfig %s inet 0' % intf) + # create VLAN interface + self.cmd('vconfig add %s %d' % (intf, vlan)) + # assign the host's IP to the VLAN interface + self.cmd('ifconfig %s.%d inet %s' % (intf, vlan, params['ip'])) + # update the intf name and host's intf map + new_name = '%s.%d' % (intf, vlan) + # update the (Mininet) interface to refer to VLAN interface name + intf.name = new_name + # add VLAN interface to host's name to intf map + self.nameToIntf[new_name] = intf + + return r diff --git a/pool/shard001/Python/0013666_extract_patch.py b/pool/shard001/Python/0013666_extract_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6f44a1d6a958f4fde4cf91c7a3bae81244e8a8 --- /dev/null +++ b/pool/shard001/Python/0013666_extract_patch.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# -- coding: iso-8859-1 -- + +############################################################################ +# +# W phase source inversion package +# ------------- +# +# Main authors: Zacharie Duputel, Luis Rivera and Hiroo Kanamori +# +# (c) California Institute of Technology and Universite de Strasbourg / CNRS +# April 2013 +# +# Neither the name of the California Institute of Technology (Caltech) +# nor the names of its contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################ + +from sys import stdin, stdout, stderr +from os.path import exists, isdir +from shutil import rmtree +from os import mkdir, unlink, environ, chdir, rename +from os.path import join +from glob import glob +from subprocess import call +import sacpy + +# Avoid writing pyc files +import sys +sys.dont_write_bytecode = True + +def RM(name): + if exists(name): + if isdir(name): + rmtree(name) + else: + unlink(name) + # All done + return; + + +def mkdir_new(name): + if exists(name): + RM(name) + mkdir(name) + # All done + return; + + +def get_sac_header(file, var): + tmpfile = '_tmp_' + WPBIN = join(environ['WPHASE_HOME'],'bin') + oo=open(tmpfile,'w') + cmd = join(WPBIN,'saclst')+' %s f %s'%(var,file) + call(cmd, shell=True, stdin=stdin, stdout=oo, stderr=oo) + oo.close() + val = open(tmpfile,'r').readlines()[0].strip().split()[1] + unlink(tmpfile) + # All done + return val + + +def ch_kcmpnm(ifile,kcmpnm): + s = sacpy.Sac() + s.read(ifile) + s.kcmpnm = kcmpnm + s.wsac(ifile) + +def ch_sac_header(file, var, value): + cmd = 'sac< %s\n'%(sac, newname)) + rename(sac, newname) + + # PZ (only renaming) + PZs = glob('SAC_PZs_%s_%s_%s_%s_*'%(knetwk,kstnm,kcmpnm,locid)) + for pz in PZs: + newname = pz.replace('_'+kcmpnm+'_','_'+newcmp+'_') + stdout.write('Renaming: %s\n -------> %s\n'%(pz, newname)) + rename(pz, newname) + + # Print Reject files + print('Rejected files in extract_patch.py:') + for sactuple in list_reject: + print(' ** %s (rejected due to cmpaz = %3.0f deg)'%sactuple) + + # All done + return 0 + +if __name__=='__main__': + main() + + + + + + diff --git a/pool/shard001/Python/0013669_gen_unvis_fixtures.py b/pool/shard001/Python/0013669_gen_unvis_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3132d6f7eb8a8aef94a09ba68c27842fc36302 --- /dev/null +++ b/pool/shard001/Python/0013669_gen_unvis_fixtures.py @@ -0,0 +1,94 @@ +#! /usr/bin/env python3 +import sys +from os.path import abspath, expanduser, dirname, join +from itertools import chain +import json +import argparse + +from vis import vis, unvis, VIS_WHITE + + +__dir__ = dirname(abspath(__file__)) + +OUTPUT_FILE = join(__dir__, '..', 'fixtures', 'unvis_fixtures.json') + +# Add custom fixtures here +CUSTOM_FIXTURES = [ + # test long multibyte string + ''.join(chr(cp) for cp in range(1024)), + 'foo bar', + 'foo\nbar', + "$bar = 'baz';", + r'$foo = "\x20\\x20\\\x20\\\\x20"', + '$foo = function($bar) use($baz) {\n\treturn $baz->getFoo()\n};' +] + +RANGES = { + # All valid codepoints in the BMP + 'bmp': chain(range(0x0000, 0xD800), range(0xE000, 0xFFFF)), + # Smaller set of pertinent? codepoints inside BMP + # see: http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane + 'small': chain( + # latin blocks + range(0x0000, 0x0250), + # Greek, Cyrillic + range(0x0370, 0x0530), + # Hebrew, Arabic + range(0x590, 0x0700), + # CJK radicals + range(0x2E80, 0x2F00), + # Hiragana, Katakana + range(0x3040, 0x3100) + ) +} + + +if __name__ == '__main__': + + argp = argparse.ArgumentParser( + description='Generates test data for Psy\\Test\\Util\\StringTest') + argp.add_argument('-f', '--format-output', action='store_true', + help='Indent JSON output to ease debugging') + argp.add_argument('-a', '--all', action='store_true', + help="""Generates test data for all codepoints of the BMP. + (same as --range=bmp). WARNING: You will need quite + a lot of RAM to run the testsuite ! + """) + argp.add_argument('-r', '--range', + help="""Choose the range of codepoints used to generate + test data.""", + choices=list(RANGES.keys()), + default='small') + argp.add_argument('-o', '--output-file', + help="""Write test data to OUTPUT_FILE + (defaults to PSYSH_DIR/test/fixtures)""") + args = argp.parse_args() + + cp_range = RANGES['bmp'] if args.all else RANGES[args.range] + indent = 2 if args.format_output else None + if args.output_file: + OUTPUT_FILE = abspath(expanduser(args.output_file)) + + fixtures = [] + + # use SMALL_RANGE by default, it should be enough. + # use BMP_RANGE for a more complete smoke test + for codepoint in cp_range: + char = chr(codepoint) + encoded = vis(char, VIS_WHITE) + decoded = unvis(encoded) + fixtures.append((encoded, decoded)) + + # Add our own custom fixtures at the end, + # since they would fail anyway if one of the previous did. + for fixture in CUSTOM_FIXTURES: + encoded = vis(fixture, VIS_WHITE) + decoded = unvis(encoded) + fixtures.append((encoded, decoded)) + + with open(OUTPUT_FILE, 'w') as fp: + # dump as json to avoid backslashin and quotin nightmare + # between php and python + json.dump(fixtures, fp, indent=indent) + + sys.exit(0) diff --git a/pool/shard001/Python/0013673_base_gui.py b/pool/shard001/Python/0013673_base_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf972ddbabfc0e7a03463829b99418c3069b86d --- /dev/null +++ b/pool/shard001/Python/0013673_base_gui.py @@ -0,0 +1,253 @@ +from PySide import QtGui, QtWebKit +from . import settings, descriptors, unicode +import abc +import sys + + +RIGHT_CLICK_SETTING_KEY = "RIGHT_CLICK" +RIGHT_CLICK_ENABLE = "document.oncontextmenu = null;" +RIGHT_CLICK_DISABLE = "document.oncontextmenu = function(e) { return false; };" +RIGHT_CLICK_INPUTS_ONLY = "document.oncontextmenu = function(e) {" + \ + "return e.target.nodeName == 'INPUT' || e.target.nodeName == 'TEXTAREA'};" + +TEXT_SELECTION_SETTING_KEY = "TEXT_SELECTION" +TEXT_SELECTION_ENABLE = "document.onselectstart = null;" + \ + "document.body.style.webkitUserSelect = '';" + \ + "document.body.style.cursor = '';" +TEXT_SELECTION_DISABLE = "document.onselectstart = function(e) " + \ + "{ return false; }; document.body.style.webkitUserSelect = 'none';" + \ + "document.body.style.cursor = 'default';" + + +class BaseGUI(object): + """ Abstract GUI class for creating apps using PySide's Qt and HTML. + + This class shouldn't be used directly. It serves as a parent to other + GUI classes. Use :py:class:`htmlPy.AppGUI` and + :py:class:`htmlPy.WebAppGUI` for developing applications. + + Arguments: + No args: This is an abstract base class. It must not be instantiated. + + Attributes: + app (PySide.QtGui.QApplication): The singleton Qt application object. + This can be instantiated only once in the entire process. + window (PySide.QtGui.QMainWindow): The window being displayed in the + ``app``. + web_app (PySide.QtWebKit.QWebView): The web view widget which renders + and displays HTML in the a ``window``. + maximized (bool property): A boolean which describes whether the + ``window`` is maximized or not. Can be set to ``True`` to maximize + the window and set to ``False`` to restore. + width (int property): Width of the ``window`` in pixels. Set the value + of this property in pixels to change the width. + height (int property): Height of the ``window`` in pixels. Set the + value of this property in pixels to change the height. + x_pos (int property): The X-coordinate for top-left corner of the + ``window`` in pixels. Set the value of this property in pixels to + move the ``window`` horizontally. + y_pos (int property): The Y-coordinate for top-left corner of the + ``window`` in pixels. Set the value of this property in pixels to + move the ``window`` vertically. + title (unicode property): The title of the ``window``. Set the value of + this property to change the title. + plugins (bool property): A boolean flag which indicates whether plugins + like flash are enabled or not. Set the value to ``True`` or + ``False`` as required. + developer_mode (bool property): A boolean flag which indicated whether + developer mode is active or not. The developer mode gives access + to web inspector and other development tools and enables + right-click on the webpage. Set the value to ``True`` or ``False`` + as required. + + """ + + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def __init__(self, title=u"Application", width=800, height=600, + x_pos=10, y_pos=10, maximized=False, + plugins=False, developer_mode=False, + allow_overwrite=False): + """ Abstract constructor for the :py:class:`htmlPy.BaseGUI` class """ + + app = QtGui.QApplication.instance() + if app is not None and not allow_overwrite: + raise RuntimeError("Another htmlPy application is already running") + elif app is not None: + self.app = app + else: + self.app = QtGui.QApplication(sys.argv) + + self.web_app = QtWebKit.QWebView() + self.window = QtGui.QMainWindow() + self.window.setCentralWidget(self.web_app) + self.web_app.settings().setAttribute( + QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, True) + + self._javascript_settings = {} + self.web_app.loadFinished.connect(self.__javascript_setting_call) + + self._width = width + self._height = height + self._x = x_pos + self._y = y_pos + + self.title = title + self.plugins = plugins + self.developer_mode = developer_mode + + self.maximized = maximized + self.auto_resize() + + width = descriptors.IntegralGeometricProperty("width") + height = descriptors.IntegralGeometricProperty("height") + x_pos = descriptors.IntegralGeometricProperty("x") + y_pos = descriptors.IntegralGeometricProperty("y") + + maximized = descriptors.LiveProperty( + bool, + lambda instance: instance.window.isMaximized(), + lambda instance, value: instance.window.showMaximized() if value else + instance.window.showNormal() and instance.auto_resize()) + + title = descriptors.LiveProperty( + unicode, + lambda instance: instance.window.windowTitle(), + lambda instance, value: instance.window.setWindowTitle(value)) + + plugins = descriptors.LiveProperty( + bool, + lambda instance: instance.web_app.settings().testAttribute( + QtWebKit.QWebSettings.PluginsEnabled), + lambda instance, value: instance.web_app.settings().setAttribute( + QtWebKit.QWebSettings.PluginsEnabled, value)) + + developer_mode = descriptors.LiveProperty( + bool, + lambda instance: instance.web_app.settings().testAttribute( + QtWebKit.QWebSettings.WebAttribute.DeveloperExtrasEnabled), + lambda instance, value: instance.web_app.settings().setAttribute( + QtWebKit.QWebSettings.WebAttribute.DeveloperExtrasEnabled, value)) + + def __javascript_setting_call(self): + """ Re-evaluate javascript settings + + This function re-evaluates all the javascript settings defined in the + dictionary ``_javascript_settings``. This should be connected + to the slot ``web_app.loadFinished``. + """ + javascript_string = ";".join(self._javascript_settings.values()) + if len(javascript_string) > 0: + self.evaluate_javascript(javascript_string) + + def auto_resize(self): + """ Resizes and relocates the ``window`` to previous state + + If the ``window`` is not maximized, this function resizes it to the + stored dimensions, moves it to the stored location. + """ + if not self.maximized: + self.window.resize(self._width, self._height) + self.window.move(self._x, self._y) + + def start(self): + """ Starts the application. + + This is not asynchronous. Starting the application will halt the + further processes. DO NOT start outside the + ``if __name__ == "__main__":`` conditional + """ + self.window.show() + sys.exit(self.app.exec_()) + + def stop(self): + """ Stops the application. Use only to bind with signals. + + The Qt application does not have to be manually stopped. Also, after + starting the application is stuck in the execution loop and will not go + further until it is stopped. Calling this function manually is + redundant. This function exits only to be binded with QSignals to stop + the application when that signal is emitted. + """ + self.app.quit() + + def execute(self): + """ Executes the application without ending the process on its end. + + DO NOT execute this process directly. Use only when + :py:meth:`htmlPy.BaseGUI.stop` is connected to some signal. + """ + self.app.exec_() + + def evaluate_javascript(self, javascript_string): + """ Evaluates javascript in web page currently displayed + + Arguments: + javascript_string (str): The string of javascript code that has to + be evaluated. + """ + self.web_app.page().mainFrame().evaluateJavaScript(javascript_string) + + def right_click_setting(self, value): + """ Javascript based setting for right click on the application. + + This function changes the web page's behaviour on right click. Normal + behaviour is to open a context menu. Enabling right click exhibits that + behaviour. Right click is enabled by default. Disabling right click + suppresses context menu for entire page. Enabling right click for + only inputs suppresses context menu for all elements excepts inputs and + textarea, which is the recommended option. The arguments provided + should be from :py:mod:`htmlPy.settings` module as explained further. + + Arguments: + value (int): should be either ``htmlPy.settings.ENABLE`` (default) + or ``htmlPy.settings.DISABLE`` or + ``htmlPy.settings.INPUTS_ONLY`` (recommended) + + """ + if value == settings.ENABLE: + self.evaluate_javascript(RIGHT_CLICK_ENABLE) + self._javascript_settings.pop(RIGHT_CLICK_SETTING_KEY, None) + elif value == settings.DISABLE: + self.evaluate_javascript(RIGHT_CLICK_DISABLE) + self._javascript_settings[RIGHT_CLICK_SETTING_KEY] = \ + RIGHT_CLICK_DISABLE + elif value == settings.INPUTS_ONLY: + self.evaluate_javascript(RIGHT_CLICK_INPUTS_ONLY) + self._javascript_settings[RIGHT_CLICK_SETTING_KEY] = \ + RIGHT_CLICK_INPUTS_ONLY + else: + raise ValueError("The argument should be either " + + "htmlPy.settings.ENABLE or " + + "htmlPy.settings.DISABLE or " + + "htmlPy.settings.INPUTS_ONLY") + + def text_selection_setting(self, value): + """ Javascript based setting for text selection in the application. + + This function changes the web page's behaviour on selection of text. + Normal behaviour is to highlight the selected text. Enabling text + selection exhibits that behaviour. Text selection is enabled by + default. Disabling text selection disallows user to select any text on + the page except for inputs and disables the I-beam cursor for text + selection. The arguments provided should be from + :py:mod:`htmlPy.settings` module as explained further. + + Arguments: + value (int): should be either ``htmlPy.settings.ENABLE`` (default) + or ``htmlPy.settings.DISABLE`` or + + """ + + if value == settings.ENABLE: + self.evaluate_javascript(TEXT_SELECTION_ENABLE) + self._javascript_settings.pop(TEXT_SELECTION_SETTING_KEY, None) + elif value == settings.DISABLE: + self.evaluate_javascript(TEXT_SELECTION_DISABLE) + self._javascript_settings[TEXT_SELECTION_SETTING_KEY] = \ + TEXT_SELECTION_DISABLE + else: + raise ValueError("The argument should be either " + + "htmlPy.settings.ENABLE or " + + "htmlPy.settings.DISABLE") diff --git a/pool/shard001/Python/0013679_simple_planner.py b/pool/shard001/Python/0013679_simple_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..257685e8ff51fb530d8d21380bc856a903c37e54 --- /dev/null +++ b/pool/shard001/Python/0013679_simple_planner.py @@ -0,0 +1,87 @@ +import logging +import random +from datetime import datetime +from chaosmonkey.planners.planner import Planner + + +class SimplePlanner(Planner): + """ + Schedule an attack for today, N times between two given times + + Planner config must contain the following args: + """ + + ref = "simple_planner:SimplePlanner" + schema = { + "type": "object", + "properties": { + "ref": {"type": "string"}, + "args": { + "type": "object", + "properties": { + "min_time": {"type": "string"}, + "max_time": {"type": "string"}, + "times": {"type": "number"}, + } + } + } + } + example = { + "ref": "simple_planner:SimplePlanner", + "args": { + "min_time": "10:00", + "max_time": "15:00", + "times": 4 + } + } + + def __init__(self, name): + super(SimplePlanner, self).__init__(name) + + self.log = logging.getLogger(__name__) + self.planner_config = None + + def plan(self, planner_config, attack_config): + self.planner_config = planner_config + + plan = self.add_plan(self.name) + + attack_dates = self._get_day_attack_schedule() + self.log.debug("Day Planner in %s", attack_dates) + for i, date in enumerate(attack_dates): + self._add_executor(date, "-".join((self.name, str(i + 1))), attack_config, plan.id) + self.log.info("Job scheduled for %s", date) + + def _get_day_attack_schedule(self): + """ + Return an array of datetimes according to the planner args + """ + planer_args = self.planner_config["args"] + start_time = datetime.strptime(planer_args["min_time"], "%H:%M").time() + start_date = datetime.combine(datetime.today().date(), start_time) + end_time = datetime.strptime(planer_args["max_time"], "%H:%M").time() + end_date = datetime.combine(datetime.today().date(), end_time) + + random.seed() + attack_schedule = [] + for start, end in self._split_date_range(start_date, end_date, planer_args["times"]): + attack_schedule.append(random.uniform(start, end)) + + return attack_schedule + + @staticmethod + def _split_date_range(start, end, intv): + """ + Splits a daterange in even buckets + """ + previous = start + diff = (end - start) / intv + for i in range(1, intv): + current = start + diff * i + yield (previous, current) + previous = current + yield (previous, end) + + @staticmethod + def to_dict(): + return Planner._to_dict(SimplePlanner.ref, SimplePlanner.schema, SimplePlanner.example) diff --git a/pool/shard001/Python/0013681_test_std_enkf_debug.py b/pool/shard001/Python/0013681_test_std_enkf_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..01fd52cd7d07205c7b3c34fae8ce2a1971f1df0f --- /dev/null +++ b/pool/shard001/Python/0013681_test_std_enkf_debug.py @@ -0,0 +1,62 @@ +# Copyright (C) 2016 Equinor ASA, Norway. +# +# The file 'test_analysis_module.py' is part of ERT - Ensemble based Reservoir Tool. +# +# ERT is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# ERT is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. +# +# See the GNU General Public License at +# for more details. +import sys +import os + +from tests import ResTest +from res.analysis import AnalysisModule, AnalysisModuleLoadStatusEnum, AnalysisModuleOptionsEnum +from ecl.util.enums import RngAlgTypeEnum, RngInitModeEnum +from ecl.util.util.rng import RandomNumberGenerator + +def find_file(path, filter): + import fnmatch + for root, dirnames, filenames in os.walk(path): + for filename in fnmatch.filter(filenames, filter): + return os.path.join(root, filename) + return None + +class StdEnKFDebugTest(ResTest): + + def setUp(self): + self.rng = RandomNumberGenerator(RngAlgTypeEnum.MZRAN, RngInitModeEnum.INIT_DEFAULT) + if sys.platform.lower() == 'darwin': + self.libname = find_file(self.SOURCE_ROOT, "std_enkf_debug.dylib") + else: + self.libname = find_file(self.SOURCE_ROOT, "std_enkf_debug.so") + self.module = AnalysisModule(lib_name = self.libname) + + + def toggleKey(self, key): + self.assertTrue( self.module.hasVar( key )) + + # check it is true + self.assertTrue( self.module.setVar( key , True ) ) + self.assertTrue( self.module.getBool(key) ) + + # set it to false + self.assertTrue( self.module.setVar( key , False ) ) + self.assertFalse( self.module.getBool(key) ) + + def test_EE_option(self): + self.toggleKey( 'USE_EE' ) + + + def test_scaledata_option(self): + self.toggleKey( 'ANALYSIS_SCALE_DATA' ) + + def test_prefix(self): + self.assertTrue( self.module.hasVar("PREFIX")) + self.assertTrue( self.module.setVar( "PREFIX" , "Path") ) diff --git a/pool/shard001/Python/0013682_abiword.py b/pool/shard001/Python/0013682_abiword.py new file mode 100644 index 0000000000000000000000000000000000000000..57e1f839bef4ae8d1788bc4c0292b3b932883576 --- /dev/null +++ b/pool/shard001/Python/0013682_abiword.py @@ -0,0 +1,95 @@ +__kupfer_name__ = _("Abiword") +__kupfer_sources__ = ("RecentsSource", ) +__description__ = _("Recently used documents in Abiword") +__version__ = "" +__author__ = "Ulrik Sverdrup " + +import os +import xml.etree.cElementTree as ElementTree + +import gio + +from kupfer.objects import Source, FileLeaf, UrlLeaf +from kupfer.obj.helplib import PicklingHelperMixin +from kupfer.obj.apps import AppLeafContentMixin + +def get_abiword_files(xmlpth, application="abiword"): + """ + Yield URLs to abiword's recent files from XML file @xmlpth + """ + inside = False + for event, entry in ElementTree.iterparse(xmlpth, events=("start", "end")): + if entry.tag == "AbiPreferences" and entry.get("app") == application: + if event == "start": + inside = True + elif not inside and event != "end": + continue + if entry.tag == "Recent": + return (entry.get(a) for a in entry.attrib if a.startswith("name")) + +class RecentsSource (AppLeafContentMixin, Source, PicklingHelperMixin): + appleaf_content_id = "abiword" + def __init__(self, name=None): + if not name: + name = _("Abiword Recent Items") + super(RecentsSource, self).__init__(name) + self.unpickle_finish() + + def pickle_prepare(self): + # monitor is not pickleable + self.monitor = None + + def unpickle_finish(self): + """Set up change monitor""" + abifile = self._get_abiword_file() + if not abifile: return + gfile = gio.File(abifile) + self.monitor = gfile.monitor_file(gio.FILE_MONITOR_NONE, None) + if self.monitor: + self.monitor.connect("changed", self._changed) + + def _changed(self, monitor, file1, file2, evt_type): + """Change callback; something changed""" + if evt_type in (gio.FILE_MONITOR_EVENT_CREATED, + gio.FILE_MONITOR_EVENT_DELETED, + gio.FILE_MONITOR_EVENT_CHANGED): + self.mark_for_update() + + def _get_abiword_file(self): + abifile = os.path.expanduser("~/.AbiSuite/AbiWord.Profile") + if not os.path.exists(abifile): + return None + return abifile + + def get_items(self): + abifile = self._get_abiword_file() + if not abifile: + self.output_debug("Abiword profile not found at", abifile) + return + + try: + uris = list(get_abiword_files(abifile)) + except EnvironmentError, exc: + self.output_error(exc) + return + + for uri in uris: + gfile = gio.File(uri) + if not gfile.query_exists(): + continue + + if gfile.get_path(): + leaf = FileLeaf(gfile.get_path()) + else: + leaf = UrlLeaf(gfile.get_uri(), gfile.get_basename()) + yield leaf + + def get_description(self): + return _("Recently used documents in Abiword") + + def get_icon_name(self): + return "document-open-recent" + def provides(self): + yield FileLeaf + yield UrlLeaf + diff --git a/pool/shard001/Python/0013683_circular_list.py b/pool/shard001/Python/0013683_circular_list.py new file mode 100644 index 0000000000000000000000000000000000000000..182036de3c1aaa95107ecc1b153b00dececc6b1a --- /dev/null +++ b/pool/shard001/Python/0013683_circular_list.py @@ -0,0 +1,209 @@ +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# circular doubly linked list +# +# by Greg Hazel + +import random + + +class Link(object): + + __slots__ = ['prev', 'data', 'next'] + + def __init__(self, data): + self.prev = self + self.data = data + self.next = self + + def __str__(self): + p = id(self.prev) + n = id(self.next) + return 'link:(%s, (%s, %s), %s)' % (p, id(self), self.data, n) + + +class CircularList(object): + + def __init__(self): + self.iter = None + self.link_refs = {} # data: link + + def prepend(self, data): + link = Link(data) + assert data not in self.link_refs + self.link_refs[data] = link + if not self.iter: + self.iter = link + else: + self._insert_before(self.iter, link) + + def append(self, data): + link = Link(data) + assert data not in self.link_refs + self.link_refs[data] = link + if not self.iter: + self.iter = link + else: + self._insert_after(self.iter, link) + + def remove(self, data): + link = self.link_refs.pop(data) + if len(self.link_refs) == 0: + self.iter = None + return + prev = link.prev + next = link.next + assert next is not None and prev is not None + prev.next = next + next.prev = prev + if link == self.iter: + self.iter = next + + ## stuff I consider to be link-related + ######## + def _double_link(self, link1, link2): + # was a single item loop, move to a double + assert link1.prev == link1 and link1.next == link1 + link1.prev = link2 + link1.next = link2 + link2.next = link1 + link2.prev = link1 + + def _insert_after(self, link1, link2): + assert link1 != link2 + if link1.next == link1: + self._double_link(link1, link2) + else: + link2.next = link1.next + link2.prev = link1 + link1.next.prev = link2 + link1.next = link2 + + def _insert_before(self, link1, link2): + assert link1 != link2 + if link1.prev == link1: + self._double_link(link1, link2) + else: + link2.prev = link1.prev + link2.next = link1 + link1.prev.next = link2 + link1.prev = link2 + ######## + + def iterator(self): + for i in iter(self): + yield i + + def __iter__(self): + if not self.iter: + return + while True: + yield self.iter.data + # someone could remove an item during iteration + if not self.iter: + return + self.iter = self.iter.next + + def __len__(self): + return len(self.link_refs) + + def __str__(self): + n = len(self.link_refs) + a = [] + # don't interrupt iteration for a print + first = self.iter + next = first + while next: + a.append(str(next)) + next = next.next + if next.data == first.data: + break + items = '\n'.join(a) + return "iter: %s \n[\n%s\n]" % (self.iter, items) + + +if __name__ == '__main__': + import time + + length = 80000 + class ltype(list): + def prepend(self, i): + self.insert(0, i) + from BTL.Lists import QList + class qtype(QList): + def prepend(self, i): + self.append(i) + def iterator(self): + if len(self) == 0: + return + while True: + yield self[0] + if len(self) == 0: + return + self.append(self.popleft()) + + #CircularList = ltype + #CircularList = qtype + print CircularList + + s = time.clock() + l = CircularList() + for i in xrange(length): + l.append(i) + #print l + print 'append ', time.clock() - s + + s = time.clock() + l = CircularList() + for i in xrange(length): + l.prepend(i) + #print l + print 'prepend', time.clock() - s + + s = time.clock() + l = CircularList() + for i in xrange(length): + if i % 2 == 0: + l.prepend(i) + else: + l.append(i) + #print l + print 'sort ', time.clock() - s + + #fair = {} + s = time.clock() + l = CircularList() + it = l.iterator() + for i in xrange(length): + l.prepend(i) + #fair[i] = 0 + x = it.next() + #print x, i + #fair[x] += 1 + #assert x == i, '%s %s' % (x, i) + #print l + print 'iter ', time.clock() - s + #for k in fair: + # print k, fair[k] + + l = CircularList() + print l + l.prepend(0) + print l + l.prepend(1) + print l + l.remove(1) + print l + l.remove(0) + print l diff --git a/pool/shard001/Python/0013684_applications_test.py b/pool/shard001/Python/0013684_applications_test.py new file mode 100644 index 0000000000000000000000000000000000000000..957fd5c7a824006aedd531266784be2b3879f1f8 --- /dev/null +++ b/pool/shard001/Python/0013684_applications_test.py @@ -0,0 +1,68 @@ +# Copyright 2018 The TensorFlow Authors. 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. +# ============================================================================== +"""Integration tests for Keras applications.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl.testing import parameterized + +from tensorflow.python.keras.applications import densenet +from tensorflow.python.keras.applications import inception_resnet_v2 +from tensorflow.python.keras.applications import inception_v3 +from tensorflow.python.keras.applications import mobilenet +from tensorflow.python.keras.applications import mobilenet_v2 +from tensorflow.python.keras.applications import nasnet +from tensorflow.python.keras.applications import resnet +from tensorflow.python.keras.applications import resnet_v2 +from tensorflow.python.keras.applications import vgg16 +from tensorflow.python.keras.applications import vgg19 +from tensorflow.python.keras.applications import xception +from tensorflow.python.platform import test + + +MODEL_LIST = [ + (resnet.ResNet50, 2048), + (resnet.ResNet101, 2048), + (resnet.ResNet152, 2048), + (resnet_v2.ResNet50V2, 2048), + (resnet_v2.ResNet101V2, 2048), + (resnet_v2.ResNet152V2, 2048), + (vgg16.VGG16, 512), + (vgg19.VGG19, 512), + (xception.Xception, 2048), + (inception_v3.InceptionV3, 2048), + (inception_resnet_v2.InceptionResNetV2, 1536), + (mobilenet.MobileNet, 1024), + (mobilenet_v2.MobileNetV2, 1280), + (densenet.DenseNet121, 1024), + (densenet.DenseNet169, 1664), + (densenet.DenseNet201, 1920), + (nasnet.NASNetMobile, 1056), +] + + +class ApplicationsTest(test.TestCase, parameterized.TestCase): + + @parameterized.parameters(*MODEL_LIST) + def test_feature_extration_model(self, model_fn, output_dim): + model = model_fn(include_top=False, weights=None) + self.assertLen(model.output_shape, 4) + self.assertEqual(model.output_shape[-1], output_dim) + + +if __name__ == '__main__': + test.main() diff --git a/pool/shard001/Python/0013691_package.py b/pool/shard001/Python/0013691_package.py new file mode 100644 index 0000000000000000000000000000000000000000..e4010735198b0a193465014a88b1a06240e41d3e --- /dev/null +++ b/pool/shard001/Python/0013691_package.py @@ -0,0 +1,27 @@ + +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from spack import * + + +class Libibumad(CMakePackage): + """This package installs the user-space libraries and headers for libibumad. + This is a subset of the linux-rdma distribution.""" + + homepage = "https://github.com/linux-rdma/" + url = "https://github.com/linux-rdma/rdma-core/archive/v25.0.tar.gz" + + version('25.0', sha256='d735bd091d13e8a68ce650e432b5bdc934fc7f1d5fb42a6045278a5b3f7fe48b') + + depends_on('libnl') + + def build(self, spec, prefix): + with working_dir(join_path(self.build_directory, 'libibumad')): + make() + + def install(self, spec, prefix): + with working_dir(join_path(self.build_directory, 'libibumad')): + make('install') diff --git a/pool/shard001/Python/0013693_rc4.py b/pool/shard001/Python/0013693_rc4.py new file mode 100644 index 0000000000000000000000000000000000000000..3853f5beaf4cf0e4068930846511d63f3a514825 --- /dev/null +++ b/pool/shard001/Python/0013693_rc4.py @@ -0,0 +1,20 @@ +# Author: Trevor Perrin +# See the LICENSE file for legal information regarding use of this file. + +"""Abstract class for RC4.""" + + +class RC4(object): + def __init__(self, keyBytes, implementation): + if len(keyBytes) < 16 or len(keyBytes) > 256: + raise ValueError() + self.isBlockCipher = False + self.isAEAD = False + self.name = "rc4" + self.implementation = implementation + + def encrypt(self, plaintext): + raise NotImplementedError() + + def decrypt(self, ciphertext): + raise NotImplementedError() diff --git a/pool/shard001/Python/0013695_selectionSort.py b/pool/shard001/Python/0013695_selectionSort.py new file mode 100644 index 0000000000000000000000000000000000000000..3979aa74af83d18f5a781fe2f401cff743fe9c47 --- /dev/null +++ b/pool/shard001/Python/0013695_selectionSort.py @@ -0,0 +1,71 @@ +import timeit + +ls = [3, 4, 8, 2, 9, 6, 5, 3, 2] + + +"""def minimum(l): + low = l[0] + for n in l: + if n < low: + low = n + return low + +while len(ls) > 0: + print(minimum(ls)) + list_min_pos = minimum(ls) + ls.remove(list_min_pos) + ls_sorted.append(list_min_pos) +print(ls_sorted)""" + +def selection_sort(ls): + for l in range(len(ls)-1, 0, -1): + max_pos = 0 + for loc in range(1, l+1): + if ls[loc] > ls[max_pos]: + max_pos = loc + + temp = ls[l] + ls[l] = ls[max_pos] + ls[max_pos] = temp + return ls + + + + + + + + + + + + + + + + + + + + + + + + + + + +def sel_sort(ls): + for l in range(len(ls)-1, 0, -1): + max_pos = 0 + for loc in range(1, l+1): + if ls[loc] > ls[max_pos]: + max_pos = loc + + temp = ls[l] + ls[l] = ls[max_pos] + ls[max_pos] = temp + print(ls) + return ls + +print(sel_sort([9,8,7,6,5,4,5,4,5])) diff --git a/pool/shard001/Python/0013697_library.py b/pool/shard001/Python/0013697_library.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf93ec7b6ef4f417972b07435c7ea5eaa421abf --- /dev/null +++ b/pool/shard001/Python/0013697_library.py @@ -0,0 +1,94 @@ +import functools + +from django.template.loader import render_to_string +from django.utils.safestring import mark_safe + + +# Global register dict for third party +# template functions, filters and extensions. +_local_env = { + "globals": {}, + "tests": {}, + "filters": {}, + "extensions": set([]), +} + + +def _update_env(env): + """ + Given a jinja environment, update it with third party + collected environment extensions. + """ + + env.globals.update(_local_env["globals"]) + env.tests.update(_local_env["tests"]) + env.filters.update(_local_env["filters"]) + + for extension in _local_env["extensions"]: + env.add_extension(extension) + + +def _attach_function(attr, func, name=None): + if name is None: + name = func.__name__ + + global _local_env + _local_env[attr][name] = func + return func + + +def _register_function(attr, name=None, fn=None): + if name is None and fn is None: + def dec(func): + return _attach_function(attr, func) + return dec + + elif name is not None and fn is None: + if callable(name): + return _attach_function(attr, name) + else: + def dec(func): + return _register_function(attr, name, func) + return dec + + elif name is not None and fn is not None: + return _attach_function(attr, fn, name) + + raise RuntimeError("Invalid parameters") + + +def extension(extension): + global _local_env + _local_env["extensions"].add(extension) + return extension + + +def global_function(*args, **kwargs): + return _register_function("globals", *args, **kwargs) + + +def test(*args, **kwargs): + return _register_function("tests", *args, **kwargs) + + +def filter(*args, **kwargs): + return _register_function("filters", *args, **kwargs) + + +def render_with(template, fn=None): + """ + Makes simple function works like + django's default inclusion_tag: render + specified template with context returned + by decorated function. + """ + + if fn is None: + return functools.partial(render_with, template) + + @functools.wraps(fn) + def _wrapper(*args, **kwargs): + data = render_to_string(template, fn(*args, **kwargs)) + return mark_safe(data) + + return _wrapper diff --git a/pool/shard001/Python/0013711_pubsub_manager.py b/pool/shard001/Python/0013711_pubsub_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..4810728b2fece12aaa4ee50e8f144ebae881e365 --- /dev/null +++ b/pool/shard001/Python/0013711_pubsub_manager.py @@ -0,0 +1,151 @@ +from functools import partial +import uuid + +import json +import pickle +import six + +from .base_manager import BaseManager + + +class PubSubManager(BaseManager): + """Manage a client list attached to a pub/sub backend. + + This is a base class that enables multiple servers to share the list of + clients, with the servers communicating events through a pub/sub backend. + The use of a pub/sub backend also allows any client connected to the + backend to emit events addressed to Socket.IO clients. + + The actual backends must be implemented by subclasses, this class only + provides a pub/sub generic framework. + + :param channel: The channel name on which the server sends and receives + notifications. + """ + name = 'pubsub' + + def __init__(self, channel='socketio', write_only=False): + super(PubSubManager, self).__init__() + self.channel = channel + self.write_only = write_only + self.host_id = uuid.uuid4().hex + + def initialize(self): + super(PubSubManager, self).initialize() + if not self.write_only: + self.thread = self.server.start_background_task(self._thread) + self.server.logger.info(self.name + ' backend initialized.') + + def emit(self, event, data, namespace=None, room=None, skip_sid=None, + callback=None, **kwargs): + """Emit a message to a single client, a room, or all the clients + connected to the namespace. + + This method takes care or propagating the message to all the servers + that are connected through the message queue. + + The parameters are the same as in :meth:`.Server.emit`. + """ + if kwargs.get('ignore_queue'): + return super(PubSubManager, self).emit( + event, data, namespace=namespace, room=room, skip_sid=skip_sid, + callback=callback) + namespace = namespace or '/' + if callback is not None: + if self.server is None: + raise RuntimeError('Callbacks can only be issued from the ' + 'context of a server.') + if room is None: + raise ValueError('Cannot use callback without a room set.') + id = self._generate_ack_id(room, namespace, callback) + callback = (room, namespace, id) + else: + callback = None + self._publish({'method': 'emit', 'event': event, 'data': data, + 'namespace': namespace, 'room': room, + 'skip_sid': skip_sid, 'callback': callback}) + + def close_room(self, room, namespace=None): + self._publish({'method': 'close_room', 'room': room, + 'namespace': namespace or '/'}) + + def _publish(self, data): + """Publish a message on the Socket.IO channel. + + This method needs to be implemented by the different subclasses that + support pub/sub backends. + """ + raise NotImplementedError('This method must be implemented in a ' + 'subclass.') # pragma: no cover + + def _listen(self): + """Return the next message published on the Socket.IO channel, + blocking until a message is available. + + This method needs to be implemented by the different subclasses that + support pub/sub backends. + """ + raise NotImplementedError('This method must be implemented in a ' + 'subclass.') # pragma: no cover + + def _handle_emit(self, message): + # Events with callbacks are very tricky to handle across hosts + # Here in the receiving end we set up a local callback that preserves + # the callback host and id from the sender + remote_callback = message.get('callback') + if remote_callback is not None and len(remote_callback) == 3: + callback = partial(self._return_callback, self.host_id, + *remote_callback) + else: + callback = None + super(PubSubManager, self).emit(message['event'], message['data'], + namespace=message.get('namespace'), + room=message.get('room'), + skip_sid=message.get('skip_sid'), + callback=callback) + + def _handle_callback(self, message): + if self.host_id == message.get('host_id'): + try: + sid = message['sid'] + namespace = message['namespace'] + id = message['id'] + args = message['args'] + except KeyError: + return + self.trigger_callback(sid, namespace, id, args) + + def _return_callback(self, host_id, sid, namespace, callback_id, *args): + # When an event callback is received, the callback is returned back + # the sender, which is identified by the host_id + self._publish({'method': 'callback', 'host_id': host_id, + 'sid': sid, 'namespace': namespace, 'id': callback_id, + 'args': args}) + + def _handle_close_room(self, message): + super(PubSubManager, self).close_room( + room=message.get('room'), namespace=message.get('namespace')) + + def _thread(self): + for message in self._listen(): + data = None + if isinstance(message, dict): + data = message + else: + if isinstance(message, six.binary_type): # pragma: no cover + try: + data = pickle.loads(message) + except: + pass + if data is None: + try: + data = json.loads(message) + except: + pass + if data and 'method' in data: + if data['method'] == 'emit': + self._handle_emit(data) + elif data['method'] == 'callback': + self._handle_callback(data) + elif data['method'] == 'close_room': + self._handle_close_room(data) diff --git a/pool/shard001/Python/0013717_apocalypse.py b/pool/shard001/Python/0013717_apocalypse.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9c9cd01db69e00938f98d69ee1632a657a6163 --- /dev/null +++ b/pool/shard001/Python/0013717_apocalypse.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +""" +apocalypse.py + +Remove all private data from pc. + +""" + +import os +import argparse + + +# all my secret files go in here +targets = [ +] + + +parser = argparse.ArgumentParser( + description='Remove all private data from this computer.' +) + +parser.add_argument( + '-a', '--all', action='store_true', + help='process without confirmation' +) + +parser.add_argument( + '--dry', action='store_true', + help='dryrun' +) + + +def try_delete(filename): + res = False + try: + os.remove(filename) + except FileNotFoundError as e: + print('File "{}"...not found'.format(filename)) + except Exception as e: + print(e) + else: + print('File "{}"...deleted'.format(filename)) + res = True + return res + + +def delete_data(dryrun, confirm=True): + for target in targets: + if dryrun: + print('File "{}"'.format(target), end='') + if os.path.isfile(target): + print('...found') + else: + print('...not found') + continue + + if confirm: + res = input('Delete file "{}" (Y/n/a)?'.format(target)) + + if res.lower() in ('y', 'a', ''): + try_delete(target) + + if res.lower() == 'a': + confirm = False + else: + try_delete(target) + +if __name__ == '__main__': + args = parser.parse_args() + delete_data(args.dry, not args.all) diff --git a/pool/shard001/Python/0013718_graph_importer.py b/pool/shard001/Python/0013718_graph_importer.py new file mode 100644 index 0000000000000000000000000000000000000000..78162cde0ef4f13330c2f09c5ffa4ea358ecc368 --- /dev/null +++ b/pool/shard001/Python/0013718_graph_importer.py @@ -0,0 +1,55 @@ +from f8a_worker.base import BaseTask +import requests +from os import environ + + +class GraphImporterTask(BaseTask): + _SERVICE_HOST = environ.get("BAYESIAN_DATA_IMPORTER_SERVICE_HOST", "bayesian-data-importer") + _SERVICE_PORT = environ.get("BAYESIAN_DATA_IMPORTER_SERVICE_PORT", "9192") + _INGEST_SERVICE_ENDPOINT = "api/v1/ingest_to_graph" + _SELECTIVE_SERVICE_ENDPOINT = "api/v1/selective_ingest" + _INGEST_API_URL = "http://{host}:{port}/{endpoint}".format(host=_SERVICE_HOST, + port=_SERVICE_PORT, + endpoint=_INGEST_SERVICE_ENDPOINT) + + _SELECTIVE_API_URL = "http://{host}:{port}/{endpoint}".format( + host=_SERVICE_HOST, + port=_SERVICE_PORT, + endpoint=_SELECTIVE_SERVICE_ENDPOINT) + + def execute(self, arguments): + self._strict_assert(arguments.get('ecosystem')) + self._strict_assert(arguments.get('name')) + self._strict_assert(arguments.get('document_id')) + + package_list = [ + { + 'ecosystem': arguments['ecosystem'], + 'name': arguments['name'], + 'version': arguments.get('version') + } + ] + + # If we force graph sync, sync all task results, otherwise only + # finished in this analysis run + if not arguments.get('force_graph_sync'): + # Tasks that need sync to graph start lowercase. + param = { + 'select_ingest': [task_name + for task_name in self.storage.get_finished_task_names( + arguments['document_id']) + if task_name[0].islower()], + 'package_list': package_list + } + endpoint = self._SELECTIVE_API_URL + else: + param = package_list + endpoint = self._INGEST_API_URL + + self.log.info("Invoke graph importer at url: '%s' for %s", endpoint, param) + response = requests.post(endpoint, json=param) + + if response.status_code != 200: + raise RuntimeError("Failed to invoke graph import at '%s' for %s" % (endpoint, param)) + + self.log.info("Graph import succeeded with response: %s", response.text) diff --git a/pool/shard001/Python/0013724_dirac-dms-pfn-metadata.py b/pool/shard001/Python/0013724_dirac-dms-pfn-metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ce147f09ecd8160968ad0036a02a697d8726c1 --- /dev/null +++ b/pool/shard001/Python/0013724_dirac-dms-pfn-metadata.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +######################################################################## +# $HeadURL$ +# File : dirac-dms-pfn-metadata +# Author : Stuart Paterson +######################################################################## +""" + Retrieve metadata for a PFN given a valid DIRAC SE +""" +from __future__ import print_function +__RCSID__ = "$Id$" +import DIRAC +from DIRAC.Core.Base import Script + +Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1], + 'Usage:', + ' %s [option|cfgfile] ... PFN SE' % Script.scriptName, + 'Arguments:', + ' PFN: Physical File Name or file containing PFNs', + ' SE: Valid DIRAC SE' ] ) ) +Script.parseCommandLine( ignoreErrors = True ) +args = Script.getPositionalArgs() + +if len( args ) < 2: + Script.showHelp() + +if len( args ) > 2: + print('Only one PFN SE pair will be considered') + +from DIRAC.Interfaces.API.Dirac import Dirac +dirac = Dirac() +exitCode = 0 + +pfn = args[0] +seName = args[1] +try: + f = open( pfn, 'r' ) + pfns = f.read().splitlines() + f.close() +except: + pfns = [pfn] + +for pfn in pfns: + result = dirac.getPhysicalFileMetadata( pfn, seName, printOutput = True ) + if not result['OK']: + print('ERROR: ', result['Message']) + exitCode = 2 + +DIRAC.exit( exitCode ) diff --git a/pool/shard001/Python/0013726_parameter.py b/pool/shard001/Python/0013726_parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fadb00c7979e37bfecf71d0e9f3718bfb006e4 --- /dev/null +++ b/pool/shard001/Python/0013726_parameter.py @@ -0,0 +1,126 @@ +from choose_matrix_library import * +import deepnet_pb2 +import logging +import numpy as np +import os.path +import util +import visualize +import pdb + +class Parameter(object): + + def __init__(self): + self.num_shares = 1 + self.num_grads_received = 0 + self.transpose = False + + def SaveParameters(self): + for param in self.proto.param: + param.mat = util.NumpyAsParameter(self.params[param.name].asarray()) + + def LoadParams(self, proto, t_op=None, tied_to=None): + """Load the parameters for this edge. + + Load the parameters if present in self.proto. Otherwise initialize them + appropriately. + """ + param_names = [param.name for param in proto.param] + for param in proto.param: + assert param.dimensions, 'Empty dimensions' + if tied_to: + if self.transpose: + self.params[param.name] = tied_to.params[param.name].T + else: + self.params[param.name] = tied_to.params[param.name] + mat = self.params[param.name] + else: + if param.mat: + mat = util.ParameterAsNumpy(param) + else: + mat = self.InitializeParameter(param) + self.params[param.name] = cm.CUDAMatrix(mat) + + def InitializeParameter(self, param): + if param.initialization == deepnet_pb2.Parameter.CONSTANT: + return np.zeros(tuple(param.dimensions)) + param.constant + elif param.initialization == deepnet_pb2.Parameter.DENSE_GAUSSIAN: + return param.sigma * np.random.randn(*tuple(param.dimensions)) + elif param.initialization == deepnet_pb2.Parameter.DENSE_UNIFORM: + return param.sigma * (2 * np.random.rand(*tuple(param.dimensions)) - 1) + elif param.initialization == deepnet_pb2.Parameter.DENSE_GAUSSIAN_SQRT_FAN_IN: + assert len(param.dimensions) > 1 + if param.conv or param.local: + fan_in = np.prod(param.dimensions[0]) + else: + fan_in = np.prod(param.dimensions[1]) + stddev = param.sigma / np.sqrt(fan_in) + return stddev * np.random.randn(*tuple(param.dimensions)) + elif param.initialization == deepnet_pb2.Parameter.DENSE_UNIFORM_SQRT_FAN_IN: + assert len(param.dimensions) > 1 + if param.conv or param.local: + fan_in = np.prod(param.dimensions[0]) + else: + fan_in = np.prod(param.dimensions[1]) + stddev = param.sigma / np.sqrt(fan_in) + return stddev * (2 * np.random.rand(*tuple(param.dimensions)) - 1) + elif param.initialization == deepnet_pb2.Parameter.PRETRAINED: + return self.LoadPretrained(param) + else: + raise Exception('Unknown parameter initialization.') + + def LoadPretrained(self, param): + pass + + def GetGlobalInfo(self, net): + pass + + def ApplyL2Decay(self, w_delta, w, lambdaa, **kwargs): + w_delta.add_mult(w, lambdaa) + + def Update(self, param_name, step, no_reg=False): + h = self.hyperparams + momentum, epsilon = self.GetMomentumAndEpsilon(step) + + w = self.params[param_name] # Parameter to be updated. + w_delta = self.gradient_history # Previous update. + gradient = self.gradient # Current gradient. + + # Compute update. + if h.adapt == deepnet_pb2.Hyperparams.NONE: + w_delta.mult(momentum) + if not no_reg and h.apply_l2_decay: + self.ApplyL2Decay(w_delta, w, h.l2_decay, step=step, eps=epsilon, mom=momentum) + if not no_reg and h.apply_l1_decay and step > h.apply_l1decay_after: + w_delta.add_mult_sign(w, h.l1_decay) + else: + raise Exception('Not implemented.') + w_delta.add_mult(gradient) + + # Apply update. + w.add_mult(w_delta, -epsilon) + if not no_reg and h.apply_weight_norm: + w.norm_limit(h.weight_norm, axis=0) + + # Reset. + self.num_grads_received = 0 + gradient.assign(0) + + def GetMomentumAndEpsilon(self, step): + """ + if h.momentum_change_steps > step: + f = float(step) / h.momentum_change_steps + momentum = (1.0 - f) * h.initial_momentum + f * h.final_momentum + else: + momentum = h.final_momentum + """ + h = self.hyperparams + momentum = h.final_momentum - (h.final_momentum - h.initial_momentum)*np.exp(-float(step)/h.momentum_change_steps) + epsilon = h.base_epsilon + if h.epsilon_decay == deepnet_pb2.Hyperparams.INVERSE_T: + epsilon = h.base_epsilon / (1 + float(step) / h.epsilon_decay_half_life) + elif h.epsilon_decay == deepnet_pb2.Hyperparams.EXPONENTIAL: + epsilon = h.base_epsilon / np.power(2, float(step) / h.epsilon_decay_half_life) + if step < h.start_learning_after: + epsilon = 0.0 + return momentum, epsilon + diff --git a/pool/shard001/Python/0013729_api.py b/pool/shard001/Python/0013729_api.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dbf243aa962415e899660b3a73743964f54d4a --- /dev/null +++ b/pool/shard001/Python/0013729_api.py @@ -0,0 +1,383 @@ +# coding: utf8 +# api.py +# 8/10/2014 + +__all__ = 'MachineTranslator', + +if __name__ == '__main__': + import sys + sys.path.append('..') + +from sakurakit.skdebug import dwarn + +from rule import RuleBuilder +RULE_BUILDER = RuleBuilder() + +INPUT_LANGUAGE = 'ja' +INPUT_SEPARATOR = '' + +# Rule + +def createrule(source, target, language): + """ + @param source unicode + @param target unicode + @param language str + @return rule.Rule or None + """ + return RULE_BUILDER.createRule(INPUT_LANGUAGE, language, source, target) + +# Analyzer + +class _MachineAnalyzer: + + def __init__(self, cabocha): + from frontend import Lexer + self.lexer = Lexer(cabocha) + + #from midend import TreeBuilder + #self.parser = TreeBuilder() + +class MachineAnalyzer(object): + + def __init__(self, cabocha): + """ + @param cabocha CaboCha.Parser + """ + self.__d = _MachineAnalyzer(cabocha) + + def parseToString(self, text): + """ + @param text unicode + @return unicode + """ + ll = self.__d.lexer + stream = ll.parse(text) + return ll.dump(stream) if stream else '' + +# Translator + +class _MachineTranslator: + + def __init__(self, cabocha, language, tr, escape, sep, underline): + self.language = language # str language + self.escape = escape # bool + self.translateFunction = tr # function or None + self.sep = sep # bool + self.underline = underline # bool + + from frontend import Lexer + self.lexer = Lexer(cabocha) + + from midend import TreeBuilder + self.parser = TreeBuilder() + + from midend import RuleBasedTranslator + self.rt = RuleBasedTranslator(fr=INPUT_LANGUAGE, to=language) + + from backend import MachineTranslator + self.mt = MachineTranslator(tr=tr, + fr=INPUT_LANGUAGE, frsep=INPUT_SEPARATOR, + to=language, tosep=sep, + escape=escape, underline=underline) + + # Translate + + def directTranslate(self, text): # unicode -> unicode + return self.translateFunction(text, fr=INPUT_LANGUAGE, to=self.language) if self.translateFunction else "" + + def translate(self, source, tr=None): # unicode -> unicode + if not source: + return "" + if not self.rt.rules: + return self.directTranslate(source) + + stream = self.lexer.parse(source) + if not stream: + return self.directTranslate(source) + #print self.lexer.dump(stream) + + stree = self.parser.parse(stream) + if not stree: + return self.directTranslate(source) + #print stree.dumpTree() + + ttree = self.rt.translate(stree) + if not ttree: + stree.clearTree() + return self.directTranslate(source) + #print ttree.dumpTree() + + if ttree.language == self.language: + target = ttree.unparseTree(self.sep) + else: + target = self.mt.translate(ttree, tr=tr) + + stree.clearTree() + ttree.clearTree() + + return target + + def dumpTranslate(self, source): # unicode -> unicode + ret = '' + stree = ttree = None + if source: + if self.rt.rules: + stream = self.lexer.parse(source) + if stream: + stree = self.parser.parse(stream) + if stree: + ttree = self.rt.translate(stree) + if ttree: + ret = ttree.dumpTree() + for it in stree, ttree: + if it: + it.clearTree() + return ret + +class MachineTranslator(object): + + def __init__(self, cabocha, language, tr=None, escape=True, sep="", underline=True): + """ + @param cabocha CaboCha.Parser + @param language str target language + @param* r function (unicode text, str fr, str to) -> unicode + @param* escape bool + @param* sep str + @param* underline bool + """ + self.__d = _MachineTranslator(cabocha, language, tr, escape, sep, underline) + + # Properties + + def language(self): return self.__d.language # -> str + def setLanguage(self, v): + d = self.__d + if d.language != v: + d.language = d.mt.to = d.rt.to = v + for rule in d.rt.rules: + rule.targetLanguage = v + + def isUnderline(self): return self.__d.underline # -> bool + def setUnderline(self, t): + d = self.__d + if d.underline != t: + d.underline = d.mt.underline = t + + def isEscape(self): return self.__d.escape # -> bool + def setEscape(self, t): + d = self.__d + if d.escape != t: + d.escape = d.mt.escape = t + + def separator(self): return self.__d.sep # -> str + def setSeparator(self, v): + d = self.__d + if d.sep != v: + d.sep = d.mt.tosep = v + + # Rule + + def ruleCount(self): return len(self.__d.rt.rules) + def setRules(self, v): self.__d.rt.rules = v + + #def clearRules(self): self.__d.rt.rules = [] #.clear() # clear not used for thread-safety + + #def addRule(self, source, target): + # """ + # @param source unicode + # @param target unicode + # """ + # rule = self.__d.createRule(source, target) + # if rule: + # self.__d.rt.rules.append(rule) + # else: + # dwarn("failed to parse rule:", source, target) + + # Lexical utilities + + def splitSentences(self, text): + """ + @param text unicode + @return [unicode] + """ + return self.__d.lexer.splitSentences(text) + + # Translate + + def translate(self, text, tr=None): + """ + @param text unicode + @param* tr function or None + @return unicode + """ + return self.__d.translate(text, tr=tr) + + def dumpTranslate(self, text): + """ + @param text unicode + @param* tr function or None + @return unicode + """ + return self.__d.dumpTranslate(text) + +if __name__ == '__main__': + # Example (link, surface) pairs: + # 太郎は花子が読んでいる本を次郎に渡した + # 5 太郎 + # none は + # 2 花子 + # none が + # 3 読ん + # none で + # none いる + # 5 本 + # none を + # 5 次郎 + # none に + # -1 渡し + # none た + #text = u"太郎は花子が読んでいる本を次郎に渡した。" + #text = u"立派な太郎は、可愛い花子が読んでいる本を立派な次郎に渡した。" + #text = u"あたしは、日本人です。" + #text = u"あたしは日本人です。" + + #text = u"【綾波レイ】「ごめんなさい。こう言う時どんな顔すればいいのか分からないの。」" + #text = u"ごめんなさい。こう言う時どんな顔すればいいのか分からないの。" + #text = u"こう言う時どんな顔すればいいのか分からないの。" + #text = u"こう言う時どんな顔すればいいのか分からないのか?" + #text = u"こう言う時どんな顔すればいいのか分からないのか?" + + #text = u"私のことを好きですか?" + #text = u"憎しみは憎しみしか生まない" + + #text = u"近未来の日本、多くの都市で大小の犯罪が蔓延。" + #text = u"近未来の日本は、多くの都市で大小の犯罪が蔓延。" + + # baidu: 未来日本在许多城市,大大小小的犯罪蔓延。警察为主的治安机构功能正在逐渐失去了,晓東市是各种各样的犯罪对策进行的事在国内最高水平的治安,保持着。因此,寻求安全的人们聚积晓东市的物价高涨,其结果是资产家大量居住的街道。在这样的状况,所以资产家的女儿和她们(校长,护卫对象)保护保镖同时培养教育机关存在着。 + #text = u"近未来の日本、多くの都市で大小の犯罪が蔓延。警察を主とした治安機関は機能を失いつつあったが、暁東市は様々な犯罪対策を行なう事で国内でもトップクラスの治安を保っていた。そのため、安全を求める人々が集り暁東市の物価は高騰、その結果資産家が多く住む街となった。そのような状況のため、資産家の令嬢と彼女ら(プリンシパル、護衛対象者)を守るボディーガードを同時に育成する教育機関が存在している。" + + # baidu: 未来日本在许多城市,大大小小的犯罪蔓延。 + # manual: 近未来的日本,大大小小的犯罪在许多城市蔓延。 + #text = u"近未来の日本、多くの都市で大小の犯罪が蔓延。" + #text = u"警察を主とした治安機関は機能を失いつつあったが、暁東市は様々な犯罪対策を行なう事で国内でもトップクラスの治安を保っていた。" + #text = u"憎しみは憎しみしか生まない。" + #text = u"あなたは誰ですか?" + + #text = u"こう言う時どんな顔すればいいのかわからないの。" + text = u"こう言う" + + #text = u"お前の物は俺の物、俺の物も俺の物" + #text = u"お前の物は俺の物" + + #self.rules = [rp.createRule(fr, to, *it) for it in ( + # (u"顔", u"表情"), + # (u"(分から ない の 。)", u"不知道的。"), + # (u"どんな", u"怎样的"), + #)] + + #from google import googletrans + #f = googletrans.translate + + to = 'zhs' + + from sakurakit.skprof import SkProfiler + from kingsoft import iciba + tr = iciba.translate + tr = None + + import CaboCha + cabocha = CaboCha.Parser() + + ma = MachineAnalyzer(cabocha) + + mt = MachineTranslator(cabocha, language=to, underline=False, escape=True, tr=tr) + + rules = [createrule(k, v, to) + for k,v in ( + #(u"顔", u"(表情)"), + #(u"どんな", u"怎样的"), + (u"(分から ない の 。)", u"(不 知道 的 。)"), + #(u"(分から ない の 。)", u"不 知道 的 。"), + #(u"(分から ない の 。)", u"不知道的。"), + #(u"分から @x 。", u"不知道的。 @x"), + #(u"(分から @x 。)", u"不知道的。 @x"), + #(u"顔", u"表情"), + #(u"(@x すれ ば いい の か)", u"不知道的。"), + + #(u"(顔 すれ ば いい の か)", u"不知道的。"), + #(u"(@x すれ @y いい @z か)", u"不知道的。 @z"), + #(u"@x すれ @y いい @z か", u"不知道的。 @z"), + #(u"(こう $x)", u"这么 $x"), + #(u"ない の 。", u"(不 知道 的 。)"), + #(u"ない の 。", u"不知道的。"), + + #(u"((@x の) $y)", u"((@x 的) $y)"), + + #(u"($x どんな)", u"什么样的表情"), + #(u"(顔 @y)", u"什么样的表情 @y"), + #(u"($x どんな)(顔 @y)", u"($x 什么样的) (表情 @y)"), + + #(u"($x すれ ば いい の か)", u"($x 才好呢)"), + #(u"(顔 @y)", u"(表情 @y)"), + #(u"顔", u"表情"), + #(u"($x どんな) (顔 @y)", u"($x 什么样的)(表情 @y)"), + #(u"(わから ない の 。)", u"(不知道的 。)"), + #(u"((こう 言う) 時)", u"这么说的时候"), + + #(u"($x 言う)", "$x debug"), + #(u"(こう $y)", "test $y"), + )] + + # ("($x 言う)", u"($x 说的)"), + #import rule + #rules.append(rule.Rule('ja', 'zhs', + # rule.PatternList((rule.PatternVariable(u"x"), u"言う")), + # rule.PatternList((rule.PatternVariable(u"x"), u"说的")), + #)) + + #rules.append(createrule(u"こう", u"这样", 'zhs')) + + mt.setRules(rules) + + #sys.setrecursionlimit(0x1000) + + #for s in mt.splitSentences(text): + if True: + s = text + + print "-- analysis --\n", ma.parseToString(s) + + print "-- sentence --\n", s + + print "-- dump-- \n", mt.dumpTranslate(s) + + with SkProfiler(): + t = mt.translate(s) + + print "-- output-- \n", t + + #stream = lexer.parse(s) + #t = lexer.unparse(stream) + #print "-- token stream == text ? %s --\n" % (s == t), t + #print "-- token stream --\n", lexer.dump(stream) + + #tree = parser.parse(stream) + #print "-- parse tree --\n", tree.dumpTree() + + #print "-- unparse tree --\n", tree.unparseTree() + + #newtree = tr.translate(tree) + #print "-- rule-based translated tree (lang = %s)--\n" % newtree.language, newtree.dumpTree() + + #if newtree.language == 'ja': + # ret = newtree.unparseTree() + # print "-- unparsed output --\n", ret + #else: + # ret = mt.translate(newtree) + # print "-- machine translated output --\n", ret + + #tree.clearTree() + #newtree.clearTree() + +# EOF diff --git a/pool/shard001/Python/0013734_mcm2bin.py b/pool/shard001/Python/0013734_mcm2bin.py new file mode 100644 index 0000000000000000000000000000000000000000..a24a6cf00ee825c7ab419e0314e593466052aaaa --- /dev/null +++ b/pool/shard001/Python/0013734_mcm2bin.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +import sys + +if len(sys.argv) < 3: + print("Usage: ./mcm2bin.py clarity.mcm clarity.bin") + exit() + +with open(sys.argv[1]) as inp: + content = inp.readlines() + +content.pop(0) + +with open(sys.argv[2], 'wb') as out: + for i, line in enumerate(content): + if i % 64 < 54: + b = int(line, 2) + out.write(bytearray([b])) diff --git a/pool/shard001/Python/0013735_HappyNetworkRoute.py b/pool/shard001/Python/0013735_HappyNetworkRoute.py new file mode 100644 index 0000000000000000000000000000000000000000..11d4e473283cda291cb21fc49554cd4735c81440 --- /dev/null +++ b/pool/shard001/Python/0013735_HappyNetworkRoute.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 + +# +# Copyright (c) 2016-2017 Nest Labs, 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. +# + +## +# @file +# Implements HappyNetworkRoute class that controls network gateway. +# +# A virtual network is logical representation of a virtual ethernet +# bridge that acts like a hub. +# + +from __future__ import absolute_import +import os +import sys + +from happy.ReturnMsg import ReturnMsg +from happy.Utils import * +from happy.utils.IP import IP +from happy.HappyNetwork import HappyNetwork +from happy.HappyNode import HappyNode +import happy.HappyNodeRoute + +options = {} +options["quiet"] = False +options["network_id"] = None +options["add"] = False +options["delete"] = False +options["to"] = None +options["via"] = None +options["prefix"] = None +options["record"] = True +options["isp"] = None +options["seed"] = None + + +def option(): + return options.copy() + + +class HappyNetworkRoute(HappyNetwork, HappyNode): + """ + Manages virtual network IP routes. + + happy-network-route [-h --help] [-q --quiet] [-a --add] [-d --delete] + [-i --id ] [-t --to (|default)] + [-v --via (||)] [-p --prefix ] + [-s --isp ] [-e --seed ] + + -i --id Required. Network to add routes to. Find using happy-network-list or + happy-state. + -t --to Optional. Default value is 'default'. The destination address. Can be + an IP address or 'default'. Use 'default' to ensure compatability of a + saved Happy topology across different Linux hosts. + -v --via The gateway of a target network, if the route spans multiple networks. + Can be an IP address, , or . Use or + to ensure compatability of a saved Happy topology across + different Linux hosts. + -p --prefix Gateway route prefix. Required if the gateway has more than one IP + address. + -s --isp Optional. The in --current ethernet's provider. + -e --seed Optional. Route priority in the routing table. Range: 0-255 + + Examples: + $ happy-network-route -i HomeThread -t default -v BorderRouter -p 2001:db8:111:1::/64 + Adds routes for all nodes in the HomeThread network to the default routes of all nodes + accessible via the 2001:db8:111:1::/64 prefix on the BorderRouter gateway. + + $ happy-network-route HomeWiFi onhub -p 10.0.1.0 + Adds routes for all nodes in the HomeWiFi network to the default routes of all nodes + accessible via the 10.0.1.0 prefix on the onhub gateway. + + $ happy-network-route -d HomeWiFi onhub -p 10.0.1.0 + Delete routes from all nodes in the HomeWiFi network to the default routes of all nodes + accessible via the 10.0.1.0 prefix on the onhub gateway. + + return: + 0 success + 1 fail + """ + + def __init__(self, opts=options): + HappyNetwork.__init__(self) + HappyNode.__init__(self) + + self.quiet = opts["quiet"] + self.network_id = opts["network_id"] + self.add = opts["add"] + self.delete = opts["delete"] + self.to = opts["to"] + self.via = opts["via"] + self.prefix = opts["prefix"] + self.record = opts["record"] + self.isp = opts["isp"] + self.seed = opts["seed"] + self.via_node = None + + def __pre_check(self): + # Check if the name of the new network is given + if not self.network_id: + emsg = "Missing name of the virtual network that should be configured with a route." + self.logger.error("[localhost] HappyNetworkRoute: %s" % (emsg)) + self.exit() + + # Check if the name of new network is not a duplicate (that it does not already exists). + if not self._networkExists(): + emsg = "virtual network %s does not exist." % (self.network_id) + self.logger.error("[%s] HappyNetworkRoute: %s" % (self.network_id, emsg)) + self.exit() + + if not self.delete: + self.add = True + + # Check if 'to' is given + if not self.to: + emsg = "Missing destination address for virtual network (to)." + self.logger.error("[%s] HappyNetworkRoute: %s" % (self.node_id, emsg)) + self.exit() + + # Check if 'via' is given + if not self.via: + emsg = "Missing gateway address for virtual network (via)." + self.logger.error("[%s] HappyNetworkRoute: %s" % (self.node_id, emsg)) + self.exit() + + # Check for mix IP addresses + if IP.isIpAddress(self.to) and IP.isIpAddress(self.via) and IP.isIpv6(self.to) != IP.isIpv6(self.via): + emsg = "Mixing addresses %s and %s." % (self.to, self.via) + self.logger.error("[%s] HappyNetworkRoute: %s" % (self.node_id, emsg)) + self.exit() + + # Check if destination is a node + if self.to != "default" and not IP.isIpAddress(self.to): + if not self._nodeExists(self.to): + emsg = "Don't know what %s to-address is. If it is a node, it can't be found." % (self.to) + self.logger.error("[localhost] HappyNetworkRoute: %s" % (emsg)) + self.exit() + else: + # 'to' is a node + emsg = "Destination address must be 'default' or a IP address." + self.logger.error("[localhost] HappyNetworkRoute: %s" % (emsg)) + self.exit() + + if IP.isIpAddress(self.to): + self.to = IP.paddingZeros(self.to) + + # Check if gateway is an address or a node + if IP.isIpAddress(self.via): + self.via = IP.paddingZeros(self.via) + self.via_node = self.getNodeIdFromAddress(self.via) + + if self.via_node is None or not self._nodeExists(self.via_node): + emsg = "Cannot find a node that would match %s." % (self.via) + self.logger.error("[localhost] HappyNetworkRoute: %s" % (emsg)) + self.exit() + + return + + if self._nodeExists(self.via): + self.via_node = self.via + + def __configure_nodes_routes(self): + for node_id in self.getNetworkNodesIds(self.network_id): + if self.via_node is not None and node_id == self.via_node: + continue + + options = happy.HappyNodeRoute.option() + options["quiet"] = self.quiet + options["node_id"] = node_id + options["to"] = self.to + options["via"] = self.via + options["prefix"] = self.prefix + options["record"] = self.record + options["isp"] = self.isp + options["seed"] = self.seed + + if self.add: + options["add"] = True + else: + options["delete"] = True + + routeCtrl = happy.HappyNodeRoute.HappyNodeRoute(options) + ret = routeCtrl.run() + + self.readState() + + def __configure_gateway_routing(self): + if self.via_node is None: + return + + self.nodeIPv4Forwarding(1, self.via_node) + self.nodeIPv6Forwarding(1, self.via_node) + + node_type = self.getNodeType(self.via_node) + if node_type != self.node_type_ap: + return + + for interface_id in self.getNodeInterfaceIds(self.via_node): + interface_type = self.getNodeInterfaceType(interface_id, self.via_node) + if interface_type != self.network_type["wan"]: + continue + + self.setNATonInterface(interface_id, self.via_node) + + def __post_check(self): + pass + + def __update_state(self): + if not self.record: + return + + if self.add: + new_route = {} + new_route["to"] = self.to + new_route["via"] = self.via + new_route["prefix"] = self.prefix + + self.setNetworkRoute(self.network_id, self.to, new_route) + else: + self.removeNetworkRoute(self.network_id, self.to) + + def run(self): + with self.getStateLockManager(): + self.__pre_check() + + self.__configure_nodes_routes() + # For TAP device, happy will not configure address/routing + # And it will be configured by LwIP stack in whatever process LwIP is running + if not self.IsTapDevice(self.node_id): + self.__configure_gateway_routing() + + with self.getStateLockManager(): + + self.__post_check() + + self.readState() + + self.__update_state() + + self.writeState() + + return ReturnMsg(0) diff --git a/pool/shard001/Python/0013743_custom_auth.py b/pool/shard001/Python/0013743_custom_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..3a10655ba78180036045238b84e0cddd3effb99c --- /dev/null +++ b/pool/shard001/Python/0013743_custom_auth.py @@ -0,0 +1,90 @@ +# coding=utf-8 + +from django.db import models +from django.contrib.auth.models import ( + BaseUserManager, AbstractBaseUser +) + + +class UserProfileManager(BaseUserManager): + def create_user(self, email, name, password=None): + """ + Creates and saves a User with the given email, date of + birth and password. + """ + if not email: + raise ValueError('Users must have an email address') + + user = self.model( + email=self.normalize_email(email), + name=name, + ) + + user.set_password(password) + user.save(using=self._db) + return user + + def create_superuser(self, email, name, password): + """ + Creates and saves a superuser with the given email, date of + birth and password. + """ + user = self.create_user( + email, + password=password, + name=name, + ) + user.is_admin = True + user.save(using=self._db) + return user + + +class UserProfile(AbstractBaseUser): # customer user model + email = models.EmailField( + verbose_name='email address', + max_length=64, + unique=True, + ) + is_active = models.BooleanField(default=True) + is_admin = models.BooleanField(default=False) + name = models.CharField(u'名字', max_length=32) + token = models.CharField(u'token', max_length=128, default=None, blank=True, null=True) + department = models.CharField(u'部门', max_length=32, default=None, blank=True, null=True) + tel = models.CharField(u'座机', max_length=32, default=None, blank=True, null=True) + mobile = models.CharField(u'手机', max_length=32, default=None, blank=True, null=True) + memo = models.TextField(u'备注', blank=True, null=True, default=None) + date_joined = models.DateTimeField(blank=True, auto_now_add=True) + + host = models.ManyToManyField('HostInfo', blank=True) + + objects = UserProfileManager() # 实例化 + + USERNAME_FIELD = 'email' # 指定登录使用的用户名为 email字段 + REQUIRED_FIELDS = ['name'] # 规定创建用户的时候,必须的字段 + + def get_full_name(self): + # The user is identified by their email address + return self.email + + def get_short_name(self): + # The user is identified by their email address + return self.email + + def __unicode__(self): + return self.email + + def has_perm(self, perm, obj=None): # Django 的权限控制 + "Does the user have a specific permission?" + # Simplest possible answer: Yes, always + return True + + def has_module_perms(self, app_label): + "Does the user have permissions to view the app `app_label`?" + # Simplest possible answer: Yes, always + return True + + @property + def is_staff(self): + "Is the user a member of staff?" + # Simplest possible answer: All admins are staff + return self.is_admin diff --git a/pool/shard001/Python/0013748_setup.py b/pool/shard001/Python/0013748_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..995d74308e58d44f49d32fa8136250b3bb852785 --- /dev/null +++ b/pool/shard001/Python/0013748_setup.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +######################################################################## +# File name: setup.py +# This file is part of: aioxmpp +# +# LICENSE +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program. If not, see +# . +# +######################################################################## +import os.path +import runpy +import sys + +import setuptools +from setuptools import setup, find_packages + +here = os.path.abspath(os.path.dirname(__file__)) + +with open(os.path.join(here, "README.rst"), encoding="utf-8") as f: + long_description = f.read() + +version_mod = runpy.run_path("aioxmpp/_version.py") + +lxml_constraint = "lxml~=4.0" +if sys.version_info < (3, 5): + lxml_constraint += ",<4.4" + +sortedcollections_constraint = "sortedcollections~=2.1" +if sys.version_info < (3, 6): + sortedcollections_constraint = "sortedcollections~=1.0" + +install_requires = [ + 'aiosasl>=0.3', # need 0.2+ for LGPLv3 + 'aioopenssl>=0.1', + 'babel~=2.3', + 'dnspython>=1.0,<3.0', + lxml_constraint, + 'multidict<7,>=2.0', + sortedcollections_constraint, + 'pyOpenSSL', + 'pyasn1', + 'pyasn1_modules', + 'tzlocal>=1.2', +] + +if tuple(map(int, setuptools.__version__.split(".")[:3])) < (6, 0, 0): + for i, item in enumerate(install_requires): + install_requires[i] = item.replace("~=", ">=") + +if sys.version_info[:3] < (3, 5, 0): + install_requires.append("typing") + +setup( + name="aioxmpp", + version=version_mod["__version__"].replace("-", ""), + description="Pure-python XMPP library for asyncio", + long_description=long_description, + url="https://github.com/horazont/aioxmpp", + author="Jonas Schäfer", + author_email="jonas@wielicki.name", + license="LGPLv3+", + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Operating System :: POSIX", + "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Topic :: Communications :: Chat", + "Topic :: Internet :: XMPP", + ], + keywords="asyncio xmpp library", + install_requires=install_requires, + packages=find_packages(exclude=["tests*", "benchmarks*"]) +) diff --git a/pool/shard001/Python/0013755_test_dwf.py b/pool/shard001/Python/0013755_test_dwf.py new file mode 100644 index 0000000000000000000000000000000000000000..887bb1b27b63928451b571994974138df3f255f8 --- /dev/null +++ b/pool/shard001/Python/0013755_test_dwf.py @@ -0,0 +1,75 @@ +# +# This file is part of pySMT. +# +# Copyright 2015 Andrea Micheli and Marco Gario +# +# 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 pysmt.test import TestCase +from pysmt.operators import CUSTOM_NODE_TYPES, new_node_type, all_types +from pysmt.type_checker import SimpleTypeChecker +from pysmt.printers import HRPrinter +from pysmt.shortcuts import get_env, Symbol +from pysmt.exceptions import UnsupportedOperatorError + + +class TestDwf(TestCase): + # NOTE: We enforce order of execution of the tests, since in the + # other test we define a custom type. + def test_00_new_node_type(self): + self.assertEqual(len(CUSTOM_NODE_TYPES), 0, "Initially there should be no custom types") + idx = new_node_type() + self.assertIsNotNone(idx) + with self.assertRaises(AssertionError): + new_node_type(idx) + + n = new_node_type(idx+100) + self.assertEqual(n, idx+100) + + def test_01_dwf(self): + # Ad-hoc method to handle printing of the new node + def hrprinter_walk_XOR(self, formula): + self.stream.write("(") + self.walk(formula.arg(0)) + self.stream.write(" *+* ") + self.walk(formula.arg(1)) + self.stream.write(")") + return + + # Shortcuts for function in env + add_dwf = get_env().add_dynamic_walker_function + create_node = get_env().formula_manager.create_node + + # Define the new node type and register the walkers in the env + XOR = new_node_type() + add_dwf(XOR, SimpleTypeChecker, SimpleTypeChecker.walk_bool_to_bool) + add_dwf(XOR, HRPrinter, hrprinter_walk_XOR) + + # Create a test node (This implicitely calls the Type-checker) + x = Symbol("x") + f1 = create_node(node_type=XOR, args=(x,x)) + self.assertIsNotNone(f1) + + # String conversion should use the function defined above. + s_f1 = str(f1) + self.assertEqual(s_f1, "(x *+* x)") + + # We did not define an implementation for the Simplifier + with self.assertRaises(UnsupportedOperatorError): + f1.simplify() + + def test_02_all_types(self): + old_types_set = set(all_types()) + new_t = new_node_type() + new_types_set = set(all_types()) + self.assertEqual(new_types_set - old_types_set, set([new_t])) diff --git a/pool/shard001/Python/0013758_test_plugins.py b/pool/shard001/Python/0013758_test_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..98d39ec14d6063c3ddc84d6840d6d01f43e27165 --- /dev/null +++ b/pool/shard001/Python/0013758_test_plugins.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +from searx.testing import SearxTestCase +from searx import plugins +from mock import Mock + + +def get_search_mock(query, **kwargs): + return {'search': Mock(query=query, + result_container=Mock(answers=set()), + **kwargs)} + + +class PluginStoreTest(SearxTestCase): + + def test_PluginStore_init(self): + store = plugins.PluginStore() + self.assertTrue(isinstance(store.plugins, list) and len(store.plugins) == 0) + + def test_PluginStore_register(self): + store = plugins.PluginStore() + testplugin = plugins.Plugin() + store.register(testplugin) + + self.assertTrue(len(store.plugins) == 1) + + def test_PluginStore_call(self): + store = plugins.PluginStore() + testplugin = plugins.Plugin() + store.register(testplugin) + setattr(testplugin, 'asdf', Mock()) + request = Mock(user_plugins=[]) + store.call('asdf', request, Mock()) + + self.assertFalse(testplugin.asdf.called) + + request.user_plugins.append(testplugin) + store.call('asdf', request, Mock()) + + self.assertTrue(testplugin.asdf.called) + + +class SelfIPTest(SearxTestCase): + + def test_PluginStore_init(self): + store = plugins.PluginStore() + store.register(plugins.self_info) + + self.assertTrue(len(store.plugins) == 1) + + # IP test + request = Mock(user_plugins=store.plugins, + remote_addr='127.0.0.1') + request.headers.getlist.return_value = [] + ctx = get_search_mock(query='ip') + store.call('post_search', request, ctx) + self.assertTrue('127.0.0.1' in ctx['search'].result_container.answers) + + # User agent test + request = Mock(user_plugins=store.plugins, + user_agent='Mock') + request.headers.getlist.return_value = [] + + ctx = get_search_mock(query='user-agent') + store.call('post_search', request, ctx) + self.assertTrue('Mock' in ctx['search'].result_container.answers) + + ctx = get_search_mock(query='user-agent') + store.call('post_search', request, ctx) + self.assertTrue('Mock' in ctx['search'].result_container.answers) + + ctx = get_search_mock(query='What is my User-Agent?') + store.call('post_search', request, ctx) + self.assertTrue('Mock' in ctx['search'].result_container.answers) diff --git a/pool/shard001/Python/0013761_errors.py b/pool/shard001/Python/0013761_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..cc247695d7ae4f40c1cb9d049237340dbc6daccd --- /dev/null +++ b/pool/shard001/Python/0013761_errors.py @@ -0,0 +1,225 @@ +# Copyright 2010-2015 RethinkDB, all rights reserved. + +__all__ = [ + "ReqlCursorEmpty", "RqlCursorEmpty", + "ReqlError", "RqlError", + "ReqlCompileError", "RqlCompileError", + "ReqlDriverCompileError", + "ReqlServerCompileError", + "ReqlRuntimeError", "RqlRuntimeError", + "ReqlQueryLogicError", + "ReqlNonExistenceError", + "ReqlResourceLimitError", + "ReqlUserError", + "ReqlInternalError", + "ReqlTimeoutError", "RqlTimeoutError", + "ReqlAvailabilityError", + "ReqlOpFailedError", + "ReqlOpIndeterminateError", + "ReqlPermissionError", + "ReqlDriverError", "RqlDriverError", "RqlClientError", + "ReqlAuthError" +] + +import sys + +try: + unicode + + def convertForPrint(inputString): + if type(inputString) == unicode: + encoding = 'utf-8' + if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: + encoding = sys.stdout.encoding + return inputString.encode(encoding or 'utf-8', 'replace') + else: + return str(inputString) +except NameError: + def convertForPrint(inputString): + return inputString + +try: + {}.iteritems + dict_items = lambda d: d.iteritems() +except AttributeError: + dict_items = lambda d: d.items() + + +class ReqlCursorEmpty(Exception): + def __init__(self): + super(ReqlCursorEmpty, self).__init__("Cursor is empty.") + self.message = "Cursor is empty." + +RqlCursorEmpty = ReqlCursorEmpty + + +class ReqlError(Exception): + def __init__(self, message, term=None, frames=None): + super(ReqlError, self).__init__(message) + self.message = message + self.frames = frames + if term is not None and frames is not None: + self.query_printer = QueryPrinter(term, self.frames) + + def __str__(self): + if self.frames is None: + return convertForPrint(self.message) + else: + return convertForPrint("%s in:\n%s\n%s" % ( + self.message.rstrip("."), + self.query_printer.print_query(), + self.query_printer.print_carrots())) + + def __repr__(self): + return "<%s instance: %s >" % (self.__class__.__name__, str(self)) + +RqlError = ReqlError + + +class ReqlCompileError(ReqlError): + pass + +RqlCompileError = ReqlCompileError + +class ReqlDriverCompileError(ReqlCompileError): + pass + +class ReqlServerCompileError(ReqlCompileError): + pass + + +class ReqlRuntimeError(ReqlError): + pass + +RqlRuntimeError = ReqlRuntimeError + + +class ReqlQueryLogicError(ReqlRuntimeError): + pass + + +class ReqlNonExistenceError(ReqlQueryLogicError): + pass + + +class ReqlResourceLimitError(ReqlRuntimeError): + pass + + +class ReqlUserError(ReqlRuntimeError): + pass + + +class ReqlInternalError(ReqlRuntimeError): + pass + + +class ReqlAvailabilityError(ReqlRuntimeError): + pass + + +class ReqlOpFailedError(ReqlAvailabilityError): + pass + + +class ReqlOpIndeterminateError(ReqlAvailabilityError): + pass + + +class ReqlPermissionError(ReqlRuntimeError): + pass + + +class ReqlDriverError(ReqlError): + pass + +RqlClientError = ReqlDriverError +RqlDriverError = ReqlDriverError + +class ReqlAuthError(ReqlDriverError): + def __init__(self, msg, host=None, port=None): + if host is None or port is None: + super(ReqlDriverError, self).__init__(msg) + else: + super(ReqlDriverError, self).__init__( + "Could not connect to %s:%d: %s" % + (host, port, msg)) + + +try: + class ReqlTimeoutError(ReqlDriverError, TimeoutError): + def __init__(self, host=None, port=None): + if host is None or port is None: + super(ReqlDriverError, self).__init__("Operation timed out.") + else: + super(ReqlDriverError, self).__init__( + "Could not connect to %s:%d, operation timed out." % (host, port)) +except NameError: + class ReqlTimeoutError(ReqlDriverError): + def __init__(self, host=None, port=None): + if host is None or port is None: + super(ReqlDriverError, self).__init__("Operation timed out.") + else: + super(ReqlDriverError, self).__init__( + "Could not connect to %s:%d, operation timed out." % (host, port)) + +RqlTimeoutError = ReqlTimeoutError + + +class QueryPrinter(object): + def __init__(self, root, frames=[]): + self.root = root + self.frames = frames + + def print_query(self): + return ''.join(self.compose_term(self.root)) + + def print_carrots(self): + return ''.join(self.compose_carrots(self.root, self.frames)) + + def compose_term(self, term): + args = [self.compose_term(a) for a in term._args] + optargs = {} + for k, v in dict_items(term.optargs): + optargs[k] = self.compose_term(v) + return term.compose(args, optargs) + + def compose_carrots(self, term, frames): + # This term is the cause of the error + if len(frames) == 0: + return ['^' for i in self.compose_term(term)] + + cur_frame = frames[0] + args = [self.compose_carrots(arg, frames[1:]) + if cur_frame == i else self.compose_term(arg) + for i, arg in enumerate(term._args)] + + optargs = {} + for k, v in dict_items(term.optargs): + if cur_frame == k: + optargs[k] = self.compose_carrots(v, frames[1:]) + else: + optargs[k] = self.compose_term(v) + + return [' ' if i != '^' else '^' for i in term.compose(args, optargs)] + + +# This 'enhanced' tuple recursively iterates over it's elements allowing us to +# construct nested heirarchies that insert subsequences into tree. It's used +# to construct the query representation used by the pretty printer. +class T(object): + # N.B Python 2.x doesn't allow keyword default arguments after *seq + # In Python 3.x we can rewrite this as `__init__(self, *seq, intsp=''` + def __init__(self, *seq, **opts): + self.seq = seq + self.intsp = opts.pop('intsp', '') + + def __iter__(self): + itr = iter(self.seq) + for sub in next(itr): + yield sub + for token in itr: + for sub in self.intsp: + yield sub + for sub in token: + yield sub diff --git a/pool/shard001/Python/0013762_coserver.py b/pool/shard001/Python/0013762_coserver.py new file mode 100644 index 0000000000000000000000000000000000000000..07d0090730a02bb031b54d56f713d1a8f559d9d1 --- /dev/null +++ b/pool/shard001/Python/0013762_coserver.py @@ -0,0 +1,132 @@ +# This file is part of the Diamond cothread library. +# +# Copyright (C) 2014 Michael Davidsaver, Brookhaven National Laboratory +# +# The Diamond cothread library is free software; you can redistribute it +# and/or modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of the License, +# or (at your option) any later version. +# +# The Diamond cothread library is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., 51 +# Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# + +""" +cothread friendly versions of the socket servers +from the SocketServer and BaseHTTPServer modules +""" + +import sys + +if sys.version_info < (3,): + from SocketServer import BaseServer, TCPServer, UDPServer, ThreadingMixIn + from BaseHTTPServer import HTTPServer, test as _test + from SimpleHTTPServer import SimpleHTTPRequestHandler + +else: + from socketserver import BaseServer, TCPServer, UDPServer, ThreadingMixIn + from http.server import HTTPServer, SimpleHTTPRequestHandler, test as _test + +from . import cothread +from . import cosocket +from . import coselect + +__all__ = [ + 'BaseServer', + 'TCPServer', + 'UDPServer', + 'HTTPServer', + 'CoThreadingMixIn', + 'CoThreadingTCPServer', + 'CoThreadingUDPServer', + 'CoThreadingHTTPServer', +] + + +# We must patch out use of the socket, threading, and select modules +def _patch(cls): + def wrap(fun): + fun.__doc__ = getattr(cls, fun.__name__).__doc__ + return fun + + class WrappedServer(cls): + __doc__ = cls.__doc__ + + @wrap + def __init__(self, *args, **kws): + if hasattr(cls, 'address_family'): # All except BaseServer + baact = kws.get('bind_and_activate', True) + kws['bind_and_activate'] = False + + cls.__init__(self, *args, **kws) + + self.__shut = cosocket.socketpair() + + if hasattr(cls, 'address_family'): + self.socket = cosocket.cosocket(_sock = self.socket) + if baact: + self.server_bind() + self.server_activate() + + @wrap + def serve_forever(self, poll_interval=0.5): + while True: + A, B = self.fileno(), self.__shut[1].fileno() + for S, E in coselect.poll_list( + [(A, coselect.POLLIN), (B, coselect.POLLIN)]): + if S == B: + self.__shut[1].recv(100) + return + elif S == A: + self._handle_request_noblock() + + @wrap + def shutdown(self): + self.__shut[0].send(b'\0') + + @wrap + def handle_request(self): + L = coselect.poll_list( + [(self, coselect.POLLIN)], + self.timeout or self.socket.gettimeout()) + if not L: + self.handle_timeout() + else: + self._handle_request_noblock() + + @wrap + def server_close(self): + cls.server_close(self) + self.__shut[0].close() + self.__shut[1].close() + + WrappedServer.__name__ = cls.__name__ + return WrappedServer + + +BaseServer = _patch(BaseServer) +TCPServer = _patch(TCPServer) +UDPServer = _patch(UDPServer) +HTTPServer = _patch(HTTPServer) + + +class CoThreadingMixIn(ThreadingMixIn): + def process_request(self, request, client_address): + cothread.Spawn(self.process_request_thread, request, client_address) + +class CoThreadingUDPServer(CoThreadingMixIn, UDPServer): pass +class CoThreadingTCPServer(CoThreadingMixIn, TCPServer): pass +class CoThreadingHTTPServer(CoThreadingMixIn, HTTPServer): pass + +def test(HandlerClass=SimpleHTTPRequestHandler, + ServerClass=CoThreadingHTTPServer): + _test(HandlerClass, ServerClass) + +if __name__ == '__main__': + test() diff --git a/pool/shard001/Python/0013767_resnet_act.py b/pool/shard001/Python/0013767_resnet_act.py new file mode 100644 index 0000000000000000000000000000000000000000..8167ecb148fdac73a90953890d33252984ef4522 --- /dev/null +++ b/pool/shard001/Python/0013767_resnet_act.py @@ -0,0 +1,159 @@ +# Copyright 2016 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. +# ============================================================================== + +"""Function for building ResNet with adaptive computation time (ACT).""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from functools import partial + +import h5py +import tensorflow as tf + +from tensorflow.contrib import slim + +import act +import flopsometer + + +SACT_KERNEL_SIZE = 3 +INIT_BIAS = -3. + + +def get_halting_proba(outputs): + with tf.variable_scope('halting_proba'): + x = outputs + x = tf.reduce_mean(x, [1, 2], keep_dims=True) + + x = slim.batch_norm(x, scope='global_bn') + halting_proba, flops = flopsometer.conv2d( + x, + 1, + 1, + activation_fn=tf.nn.sigmoid, + normalizer_fn=None, + biases_initializer=tf.constant_initializer(INIT_BIAS), + scope='global_conv') + halting_proba = tf.squeeze(halting_proba, [1, 2]) + + return halting_proba, flops + + +def get_halting_proba_conv(outputs, residual_mask=None): + with tf.variable_scope('halting_proba'): + flops = 0 + + x = outputs + + local_feature = slim.batch_norm(x, scope='local_bn') + halting_logit, current_flops = flopsometer.conv2d( + local_feature, + 1, + SACT_KERNEL_SIZE, + activation_fn=None, + normalizer_fn=None, + biases_initializer=tf.constant_initializer(INIT_BIAS), + output_mask=residual_mask, + scope='local_conv') + flops += current_flops + + # Add global halting logit. + global_feature = tf.reduce_mean(x, [1, 2], keep_dims=True) + global_feature = slim.batch_norm(global_feature, scope='global_bn') + halting_logit_global, current_flops = flopsometer.conv2d( + global_feature, + 1, + 1, + activation_fn=None, + normalizer_fn=None, + biases_initializer=None, # biases are already present in local logits + scope='global_conv') + flops += current_flops + + # Addition with broadcasting over spatial dimensions. + halting_logit += halting_logit_global + + halting_proba = tf.sigmoid(halting_logit) + + return halting_proba, flops + + +def unit_act(block, + inputs, + unit_idx, + skip_halting_proba=False, + sact=False, + residual_mask=None): + with tf.variable_scope('unit_%d' % (unit_idx + 1), [inputs]): + outputs, flops = block.unit_fn( + inputs, *block.args[unit_idx], residual_mask=residual_mask) + + if not skip_halting_proba and unit_idx < len(block.args) - 1: + if sact: + halting_proba, current_flops = get_halting_proba_conv( + outputs, residual_mask) + flops += current_flops + else: + halting_proba, current_flops = get_halting_proba(outputs) + flops += current_flops + else: + halting_proba = None + + return outputs, halting_proba, flops + + +def stack_blocks(net, blocks, model_type, end_points=None): + """Utility function for assembling SACT models consisting of 'blocks.'""" + if end_points is None: + end_points = {} + end_points['flops'] = end_points.get('flops', 0) + end_points['block_scopes'] = [block.scope for block in blocks] + end_points['block_num_units'] = [len(block.args) for block in blocks] + + assert model_type in ('vanilla', 'act', 'act_early_stopping', 'sact') + model_type_to_func = { + 'act': act.adaptive_computation_time_wrapper, + 'act_early_stopping': act.adaptive_computation_early_stopping, + 'sact': act.spatially_adaptive_computation_time, + } + act_func = model_type_to_func.get(model_type, None) + + for block in blocks: + if act_func: + (ponder_cost, num_units, flops, halting_distribution, net) = act_func( + net, + partial(unit_act, block, sact=(model_type == 'sact')), + len(block.args), + scope=block.scope) + + end_points['{}/ponder_cost'.format(block.scope)] = ponder_cost + end_points['{}/num_units'.format(block.scope)] = num_units + end_points['{}/halting_distribution'.format( + block.scope)] = halting_distribution + else: + with tf.variable_scope(block.scope, 'block', [net]): + flops = 0 + for unit_idx in range(len(block.args)): + net, _, current_flops = unit_act( + block, net, unit_idx, skip_halting_proba=True) + flops += current_flops + + end_points['{}/flops'.format(block.scope)] = flops + end_points['flops'] += flops + end_points[block.scope] = net + + return net, end_points diff --git a/pool/shard001/Python/0013771_yaml2tfvars.py b/pool/shard001/Python/0013771_yaml2tfvars.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7e9f93bfd010920228c2ca0ad413b0a862b8f2 --- /dev/null +++ b/pool/shard001/Python/0013771_yaml2tfvars.py @@ -0,0 +1,74 @@ +import os +import sys +from os import path, system + +import yaml + +vars_map = {'COMPUTE_ENV': 'batch_compute_env_name' + , 'QUEUE_NAME': 'batch_queue_name' + , 'SOURCE_BUCKET': 'source_bucket_name' + , 'TARGET_BUCKET': 'target_bucket_name' + , 'KEY_NAME': 'ssh_key_name' + , 'AUTOSCALING_GROUP': 'batch_resources_name' + } + + +def load_config(): + cfg_file = path.join(path.dirname(__file__), 'config.yaml') + if path.exists(cfg_file): + with open(cfg_file) as f: + cfg = yaml.load(f) + return cfg + else: + raise Exception("Config file wasn't found") + + +def get_target_path(args): + file_name = 'variables.auto.tfvars' + target_path = path.join(path.abspath(path.dirname(__file__)), 'terraform/vpc-ob-pipeline/', file_name) + if len(args) == 1: + return target_path, 0 + if len(args) >= 2: + p = args[1] + if os.path.isdir(p): + return path.join(p, file_name), 0 + else: + return "", 1 + + +def create_tfvars_file(target_path, cfg): + result_list = [] + d = cfg['default'] +# for k in vars_map.keys(): +# result_list.append( +# """variable \"%s\" { +# default = \"%s\" +# }""" % (vars_map[k], d[k])) + for k in vars_map.keys(): + result_list.append("%s = \"%s\"\n" % (vars_map[k], d[k])) + result = "\n\n".join(result_list) + f = open(target_path, "w") + f.write(result) + f.close() + print("File '%s' was created or updated." % target_path) + + +def main(args): + if not os.path.isfile("./config.yaml"): + print("File `config.yaml` doesn't exist, please create it from a template") + system.exit(1) + + target_path, code = get_target_path(args) + if code > 0: + print("Directory doesn't exist") + system.exit(code) + else: + try: + create_tfvars_file(target_path, load_config()) + except Exception as e: + print("Couldn't create tfvars file due to the following error: %s" % e) + system.exit(1) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/pool/shard001/Python/0013776_main.py b/pool/shard001/Python/0013776_main.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8a35d0175e7567e6c3a93977e031fd2866e73f --- /dev/null +++ b/pool/shard001/Python/0013776_main.py @@ -0,0 +1,52 @@ +from datetime import datetime +import requests +import time +import sys +from Adafruit_7Segment import SevenSegment +from Adafruit_LEDBackpack import LEDBackpack +import logging + +segment = SevenSegment(address=0x70) +led_disp = segment.disp +CONFIG_FILE_NAME = ".raspi_clock_display_config" + +conf_file = open(CONFIG_FILE_NAME, "r") +get_time_path = conf_file.read().strip() +conf_file.close() + +logging.basicConfig(filename='log.txt',level=logging.INFO, format="%(asctime)s %(levelname)s %(module)s %(message)s", datefmt='%Y-%m-%d %H:%M:%S %Z') + +logging.info('Path to get time from: "%s"' % get_time_path) + +while True: + try: + print datetime.now() + r = requests.get(get_time_path, timeout=5) + + if r.status_code != 200: + raise Exception("Could not connect to get the time") + + alarm_datetime = datetime.fromtimestamp(int(str(r.text).split()[0])) + difference_in_days = ((alarm_datetime - datetime.now()).total_seconds()/60/60/24) + led_disp.setBlinkRate(0) + + if difference_in_days < 1 and difference_in_days > 0: + segment.writeDigit(0, alarm_datetime.hour / 10) + segment.writeDigit(1, alarm_datetime.hour % 10) + segment.writeDigit(3, alarm_datetime.minute / 10) + segment.writeDigit(4, alarm_datetime.minute % 10) + segment.setColon(SevenSegment.ColonParts.RIGHT_COLON, True) + logging.info('Next alarm: %s', alarm_datetime) + else: + for digit in [0, 1, 3, 4]: + segment.writeDigitRaw(digit, 0b1000000) + segment.setColon(SevenSegment.ColonParts.RIGHT_COLON, False) + logging.info('No alarm for the next 24 hours') + time.sleep(5) + + except Exception, e: + logging.exception(e) + # Blink 7Segment + led_disp.setBlinkRate(2) + logging.error('Error, blinking') + time.sleep(2.5) diff --git a/pool/shard001/Python/0013784_test_plugin.py b/pool/shard001/Python/0013784_test_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..c2abbdb580895b7874076daa4bca67d692a3b6b3 --- /dev/null +++ b/pool/shard001/Python/0013784_test_plugin.py @@ -0,0 +1,99 @@ +""" +Test xblock/core/plugin.py +""" + +from __future__ import absolute_import, division, print_function, unicode_literals + +from mock import patch, Mock + +from xblock.test.tools import ( + assert_is, + assert_raises_regexp, + assert_equals +) + +from xblock.core import XBlock +from xblock import plugin +from xblock.plugin import AmbiguousPluginError, PluginMissingError + + +class AmbiguousBlock1(XBlock): + """A dummy class to find as a plugin.""" + pass + + +class AmbiguousBlock2(XBlock): + """A dummy class to find as a plugin.""" + pass + + +class UnambiguousBlock(XBlock): + """A dummy class to find as a plugin.""" + pass + + +@XBlock.register_temp_plugin(AmbiguousBlock1, "bad_block") +@XBlock.register_temp_plugin(AmbiguousBlock2, "bad_block") +@XBlock.register_temp_plugin(UnambiguousBlock, "good_block") +def test_ambiguous_plugins(): + # We can load ok blocks even if there are bad blocks. + cls = XBlock.load_class("good_block") + assert_is(cls, UnambiguousBlock) + + # Trying to load bad blocks raises an exception. + expected_msg = ( + "Ambiguous entry points for bad_block: " + "xblock.test.test_plugin.AmbiguousBlock1, " + "xblock.test.test_plugin.AmbiguousBlock2" + ) + with assert_raises_regexp(AmbiguousPluginError, expected_msg): + XBlock.load_class("bad_block") + + # We can use our own function as the select function. + class MyOwnException(Exception): + """We'll raise this from `boom`.""" + pass + + def boom(identifier, entry_points): + """A select function to prove user-defined functions are called.""" + assert len(entry_points) == 2 + assert identifier == "bad_block" + raise MyOwnException("This is boom") + + with assert_raises_regexp(MyOwnException, "This is boom"): + XBlock.load_class("bad_block", select=boom) + + +def test_nosuch_plugin(): + # We can provide a default class to return for missing plugins. + cls = XBlock.load_class("nosuch_block", default=UnambiguousBlock) + assert_is(cls, UnambiguousBlock) + + # If we don't provide a default class, an exception is raised. + with assert_raises_regexp(PluginMissingError, "nosuch_block"): + XBlock.load_class("nosuch_block") + + +@patch.object(XBlock, '_load_class_entry_point', Mock(side_effect=Exception)) +def test_broken_plugin(): + plugins = XBlock.load_classes() + assert_equals(list(plugins), []) + + +def _num_plugins_cached(): + """ + Returns the number of plugins that have been cached. + """ + return len(plugin.PLUGIN_CACHE) + + +@XBlock.register_temp_plugin(AmbiguousBlock1, "thumbs") +def test_plugin_caching(): + plugin.PLUGIN_CACHE = {} + assert_equals(_num_plugins_cached(), 0) + + XBlock.load_class("thumbs") + assert_equals(_num_plugins_cached(), 1) + + XBlock.load_class("thumbs") + assert_equals(_num_plugins_cached(), 1) diff --git a/pool/shard001/Python/0013785_feature_selection.py b/pool/shard001/Python/0013785_feature_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..9e17a25ab387b21cf49a63f2d2c8b9ed8eb15464 --- /dev/null +++ b/pool/shard001/Python/0013785_feature_selection.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +from datatypes import Dataset + +from sklearn.feature_selection import SelectKBest, f_classif +from sklearn.lda import LDA +from sklearn.qda import QDA +from sklearn.decomposition import PCA + +def univariate_feature_selection(ds, n): + """ + Selects 'n' features in the dataset. Returns the Reduced Dataset + n (int), ds (Dataset) -> Dataset + """ + + selector = SelectKBest(f_classif, n) + selector.fit(ds.data, ds.target) + features = selector.get_support(indices=True) + return Dataset(selector.transform(ds.data), ds.target) + +def lda(ds, n): + ''' + Outputs the projection of the data in the best + discriminant dimension. + Maximum of 2 dimensions for our binary case (values of n greater than this will be ignored by sklearn) + ''' + selector = LDA(n_components=n) + selector.fit(ds.data, ds.target) + new_data = selector.transform(ds.data) + return Dataset(new_data, ds.target) + +def pca(ds,n): + ''' + Uses the PCA classifier to reduces the dimensionality by choosing the n lastest elements + of the transform. + ''' + selector = PCA() + selector.fit(ds.data, ds.target) + new_data = selector.transform(ds.data)[:, :-n] + return Dataset(new_data, ds.target) diff --git a/pool/shard001/Python/0013786_file_manager.py b/pool/shard001/Python/0013786_file_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..be9e5111019d2c2618c222b8d5152b31307a4b18 --- /dev/null +++ b/pool/shard001/Python/0013786_file_manager.py @@ -0,0 +1,201 @@ +# Copyright 2021 The FedLearner Authors. 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. + +# coding: utf-8 +import importlib +import logging +import os +import re +from collections import namedtuple + +from typing import List + +from tensorflow.io import gfile + +# path: absolute path of the file +# size: file size in bytes +# mtime: time of last modification, unix timestamp in seconds. +File = namedtuple('File', ['path', 'size', 'mtime']) +# Currently the supported format '/' or 'hdfs://' +# TODO(chenyikan): Add oss format when verified. +SUPPORTED_FILE_PREFIXES = r'\.+\/|^\/|^hdfs:\/\/' + + +class FileManagerBase(object): + """A base interface for file manager, please implement this interface + if you have specific logic to handle files, for example, HDFS with ACL.""" + def can_handle(self, path: str) -> bool: + """If the manager can handle such file.""" + raise NotImplementedError() + + def ls(self, path: str, recursive=False) -> List[str]: + """Lists files under a path. + Raises: + ValueError: When the path does not exist. + """ + raise NotImplementedError() + + def move(self, source: str, destination: str) -> bool: + """Moves a file from source to destination, if destination + is a folder then move into that folder. Files that already exist + will be overwritten.""" + raise NotImplementedError() + + def remove(self, path: str) -> bool: + """Removes files under a path.""" + raise NotImplementedError() + + def copy(self, source: str, destination: str) -> bool: + """Copies a file from source to destination, if destination + is a folder then move into that folder. Files that already exist + will be overwritten.""" + raise NotImplementedError() + + def mkdir(self, path: str) -> bool: + """Creates a directory. If already exists, return False""" + raise NotImplementedError() + + def read(self, path: str) -> str: + raise NotImplementedError() + + +class GFileFileManager(FileManagerBase): + """Gfile file manager for all FS supported by TF, + currently it covers all file types we have.""" + def can_handle(self, path): + if path.startswith('fake://'): + return False + return re.match(SUPPORTED_FILE_PREFIXES, path) + + def ls(self, path: str, recursive=False) -> List[File]: + def _get_file_stats(path: str): + stat = gfile.stat(path) + return File(path=path, + size=stat.length, + mtime=int(stat.mtime_nsec / 1e9)) + + if not gfile.exists(path): + raise ValueError( + f'cannot access {path}: No such file or directory') + # If it is a file + if not gfile.isdir(path): + return [_get_file_stats(path)] + + files = [] + if recursive: + for root, _, res in gfile.walk(path): + for file in res: + if not gfile.isdir(os.path.join(root, file)): + files.append(_get_file_stats(os.path.join(root, file))) + else: + for file in gfile.listdir(path): + if not gfile.isdir(os.path.join(path, file)): + files.append(_get_file_stats(os.path.join(path, file))) + # Files only + return files + + def move(self, source: str, destination: str) -> bool: + self.copy(source, destination) + self.remove(source) + return destination + + def remove(self, path: str) -> bool: + if not gfile.isdir(path): + return os.remove(path) + return gfile.rmtree(path) + + def copy(self, source: str, destination: str) -> bool: + if gfile.isdir(destination): + # gfile requires a file name for copy destination. + return gfile.copy(source, + os.path.join(destination, + os.path.basename(source)), + overwrite=True) + return gfile.copy(source, destination, overwrite=True) + + def mkdir(self, path: str) -> bool: + return gfile.makedirs(path) + + def read(self, path: str) -> str: + return gfile.GFile(path).read() + + +class FileManager(FileManagerBase): + """A centralized manager to handle files. + + Please extend `FileManagerBase` and put the class path into + `CUSTOMIZED_FILE_MANAGER`. For example, + 'fedlearner_webconsole.utils.file_manager:HdfsFileManager' + """ + def __init__(self): + self._file_managers = [] + cfm_path = os.environ.get('CUSTOMIZED_FILE_MANAGER') + if cfm_path: + module_path, class_name = cfm_path.split(':') + module = importlib.import_module(module_path) + # Dynamically construct a file manager + customized_file_manager = getattr(module, class_name) + self._file_managers.append(customized_file_manager()) + self._file_managers.append(GFileFileManager()) + + def can_handle(self, path): + for fm in self._file_managers: + if fm.can_handle(path): + return True + return False + + def ls(self, path: str, recursive=False) -> List[File]: + for fm in self._file_managers: + if fm.can_handle(path): + return fm.ls(path, recursive=recursive) + raise RuntimeError(f'ls is not supported for {path}') + + def move(self, source: str, destination: str) -> bool: + logging.info('Moving files from [%s] to [%s]', source, destination) + for fm in self._file_managers: + if fm.can_handle(source) and fm.can_handle(destination): + return fm.move(source, destination) + # TODO(chenyikan): Support cross FileManager move by using buffers. + raise RuntimeError( + f'move is not supported for {source} and {destination}') + + def remove(self, path: str) -> bool: + logging.info('Removing file [%s]', path) + for fm in self._file_managers: + if fm.can_handle(path): + return fm.remove(path) + raise RuntimeError(f'remove is not supported for {path}') + + def copy(self, source: str, destination: str) -> bool: + logging.info('Copying file from [%s] to [%s]', source, destination) + for fm in self._file_managers: + if fm.can_handle(source) and fm.can_handle(destination): + return fm.copy(source, destination) + # TODO(chenyikan): Support cross FileManager move by using buffers. + raise RuntimeError( + f'copy is not supported for {source} and {destination}') + + def mkdir(self, path: str) -> bool: + logging.info('Create directory [%s]', path) + for fm in self._file_managers: + if fm.can_handle(path): + return fm.mkdir(path) + raise RuntimeError(f'mkdir is not supported for {path}') + + def read(self, path: str) -> str: + logging.info(f'Read file from [{path}]') + for fm in self._file_managers: + if fm.can_handle(path): + return fm.read(path) + raise RuntimeError(f'read is not supported for {path}') diff --git a/pool/shard001/Python/0013787_mon_alarm.py b/pool/shard001/Python/0013787_mon_alarm.py new file mode 100644 index 0000000000000000000000000000000000000000..e78bdbaf35e69ae1e5147c3482e6381dc8658ee1 --- /dev/null +++ b/pool/shard001/Python/0013787_mon_alarm.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# -*- encoding:utf-8 -*- +import sys +reload(sys) +sys.setdefaultencoding('utf8') +__author__ = 'kairong' +import MySQLdb +import ConfigParser +from multiprocessing import Process + +def alarm(id): + """Alarm ID""" + print "ID: %d monitor is error!" %(id) + +def check_status(id): + """根据ID查询报警阈值,以及现在的状态值""" + re_dict = {"status_0":0} + sum_c = 0 + conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') + cur = conn.cursor() + sql_get_id_status = "select C.status_code,A.fail_time from status_code AS C,montior_url AS A where C.ID = A.ID and C.ID = %d;" %(id) + cur.execute(sql_get_id_status) + status_all = cur.fetchall() + print id, + for c_status, a_status in status_all: + sum_c += c_status + d_key = "status_%d" % (c_status) + re_dict[d_key] = re_dict.get(d_key,0) + 1 + if sum_c == 0: + print "ID %d is ok" % (id,) + else: + sum_v = 0 + for v in re_dict.values(): + sum_v += v + if re_dict["status_0"] / float(sum_v) < 0.5: + print "ID %d is error" % (id,) + + + # if c_status >= a_status: + # alarm(id) + # else: + # print "ID %d is ok" %(id) + +def get_args(main, name): + """获取配置""" + return cf.get(main, name) + +def main(): + '''获取所有现在的监控列表的ID,根据ID触发监控''' + conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8') + cur = conn.cursor() + sql_get_id = "select ID from montior_url;" + cur.execute(sql_get_id) + while True: + line = cur.fetchone() + if not line: + break + #check_status(line[0]) + Process(target=check_status,args=(line[0],)).start() + +cf = ConfigParser.ConfigParser() +cf.read("./local_config") +db_hostname = get_args("DB", "db_host") +db_user = get_args("DB", "username") +db_pass = get_args("DB", "passwd") +db_default = get_args("DB", "db") + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0013790_xgboost_runtime.py b/pool/shard001/Python/0013790_xgboost_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..28fc2ded952635df1f3a72cf6091d4daefa515f1 --- /dev/null +++ b/pool/shard001/Python/0013790_xgboost_runtime.py @@ -0,0 +1,32 @@ +import random, math +import operator +from collections import defaultdict +from seldon.xgb import * +import seldon.pipeline.pipelines as pl +import json + + +def init(config): + print "initialised" + global tailq + xgboost_config = config['XGBOOST'] + global pipeline + pipeline = pl.Pipeline(local_models_folder="models",models_folder=xgboost_config['featuresPath'],aws_key=xgboost_config.get("awsKey",None),aws_secret=xgboost_config.get("awsSecret",None)) + pipeline.transform_init() + global modelLocation + modelLocation = xgboost_config["modelPath"] + global xgSeldon + xgSeldon = XGBoostSeldon(**xgboost_config) + xgSeldon.load_models() + +def score(json): + print json + jsonTransformed = pipeline.transform_json(json) + print jsonTransformed + return xgSeldon.predict_json(jsonTransformed) + +def get_predictions(client,json): + return (score(json),modelLocation) + + + diff --git a/pool/shard001/Python/0013791_pipeline.py b/pool/shard001/Python/0013791_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..7928e2ae53e1b2b7868c900c00944fcd5bd89b87 --- /dev/null +++ b/pool/shard001/Python/0013791_pipeline.py @@ -0,0 +1,190 @@ +"""Provides high level routines and objects that convert user +input such as graphs into actual functioning data flow objects. + +This module takes care of setting up the scheduler and providing +an input channel from which the calling application can submit +data. + +It also provides the pooling logic which ensures that each instance +of the data flow model is run on a different CPU/core. At the same +time, it provides an abstraction making the pool appear as a single +unified entity. + +Data fed is actually load balanced in a round-robin fashion across +all instances in the workflow pool. + +Uses the L{multiprocessing} module and requires Python >= 2.6 +""" +import stackless +import traceback +from multiprocessing import Process, Pipe, Queue + +from .scheduler import sched + +def pipeline(graph): + """Initializes the main scheduling tasklet. + + @param graph: The work flow graph + @type graph: Python dict organized as a graph + @return: L{stackless.channel} + """ + ch = stackless.channel() + stackless.tasklet(sched)(ch, graph).run() + return ch + +class Instance: + """Represents a single instance of a data flow model. + """ + def __init__(self, channel): + """Class constructor + + @param channel: the L{stackless.channel} this instance will listen on + @type channel: L{stackless.channel} + """ + self.sender, self.recipient = Pipe() + self.channel = channel + + def execute(self, graph): + """This is the entry point for the process. + + This method will be forked into a separate process + from the caller using the L{multiprocessing.Process} + method. + + The actual pipeline must be created here so that it + lives inside a separate process than the caller. This + is vital to how the scheduling works in stackless Python. + + @see: L{Dataflow.add_process} + + @param graph: The data flow graph + @type graph: dict + + @return: Nothing + """ + pipe = pipeline(graph) + self._run(pipe) + + def _run(self, pipe): + """The main loop that runs inside the new process. + + This runs in an event loop waiting on data using + a L{multiprocessing.Pipe} which allows two processes + to communicate using shared memory. + + If no data is available then it blocks and waits. + + @param pipe: The communcation channel used to wake this method + @type pipe: L{multiprocessing.Pipe} + @return: Nothing + """ + while True: + data = self.recipient.recv() + if data == -1: + break + try: + pipe.send(data) + except: + print('OOPS! - Component Failure') + traceback.print_exc() + + def send(self): + """Sends data into the new process + + This runs in an event loop waiting on data using + a L{multiprocessing.Queue}. When data arrives, it is + sent immediately into the new process using a + L{multiprocessing.Pipe}. + + If no data is available then it blocks and waits. + + This method serves as a proxy that can shuttle + data from the main calling process to the newly + created process that was created using L{execute} + + @return: Nothing + """ + while True: + data = self.channel.get() + if data == -1: + self.sender.send(-1) + break + else: + self.sender.send(data) + +class Dataflow: + """Provides an abstraction of a group of L{Instance}s. + + A Dataflow represents a pool of data flow L{Instance}s. + The caller simply sends data to the Dataflow and the + Dataflow takes care of load balancing across all available + L{Instance}s. + + It uses L{multiprocessing.Queue} to send data to the + instance pool. + """ + def __init__(self, graph, n=1): + """Class constructor + + @param graph: the data model in graph notation + @type graph: dict + @param n: The number of instances to start (pool size) + This number should the number of CPUs and/or cores + available on the architecture running the code. + Defaults to 1 + @type n: int + """ + self.queue = Queue() + self.pipeline = graph + self.size = n + self.processes = [] + + for i in range(self.size): + self.add_process() + + def send(self, data): + """Sends data to the next available L{Instance} + + Uses a stackless channel to communicate with the + L{Instance} tasklet. + + @see: L{add_process} + @param data: The data being sent + @type data: Application Specific + """ + self.queue.put(data) + + def close(self): + """ Shuts down this workflow and all associated L{Instance}s + + Sends a terminate signal to all the tasklets causing them to + return which in turn causes the process running that L{Instance} + to return/exit as well. + + This should lead to a clean shutdown based on the shear nature + of stackless tasklets. Any data will be flushed (completed) before + exiting. + """ + for p in self.processes: + self.queue.put(-1) + + def add_process(self): + """Adds a new process (L{Instance} to the Dataflow pool. + + Creates a new L{Instance} and runs it inside a L{multiprocessing.Process} + """ + process = Instance(self.queue) + self.processes.append(process) + Process(target=process.send).start() + Process(target=process.execute, args=(self.pipeline,)).start() + + def remove_process(self): + """Removes an instance from the Dataflow pool. + + Shuts down one instance in the pool. + @todo: Which Instance do we stop? Right now it's the last that was added + which may be good enough. What if it's the only instance? + """ + process = self.processes.pop() + self.queue.put(-1) + diff --git a/pool/shard001/Python/0013799_base.py b/pool/shard001/Python/0013799_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd8fc18b198b959bd30b2513daae8a0ecdd57e3 --- /dev/null +++ b/pool/shard001/Python/0013799_base.py @@ -0,0 +1,84 @@ +# Since this package contains a "django" module, this is required on Python 2. +from __future__ import absolute_import + +from django.core.exceptions import ( + ImproperlyConfigured, SuspiciousFileOperation, +) +from django.template.utils import get_app_template_dirs +from django.utils._os import safe_join +from django.utils.functional import cached_property + + +class BaseEngine(object): + + # Core methods: engines have to provide their own implementation + # (except for from_string which is optional). + + def __init__(self, params): + """ + Initializes the template engine. + + Receives the configuration settings as a dict. + """ + params = params.copy() + self.name = params.pop('NAME') + self.dirs = list(params.pop('DIRS')) + self.app_dirs = bool(params.pop('APP_DIRS')) + if params: + raise ImproperlyConfigured( + "Unknown parameters: {}".format(", ".join(params))) + + @property + def app_dirname(self): + raise ImproperlyConfigured( + "{} doesn't support loading templates from installed " + "applications.".format(self.__class__.__name__)) + + def from_string(self, template_code): + """ + Creates and returns a template for the given source code. + + This method is optional. + """ + raise NotImplementedError( + "subclasses of BaseEngine should provide " + "a from_string() method") + + def get_template(self, template_name): + """ + Loads and returns a template for the given name. + + Raises TemplateDoesNotExist if no such template exists. + """ + raise NotImplementedError( + "subclasses of BaseEngine must provide " + "a get_template() method") + + # Utility methods: they are provided to minimize code duplication and + # security issues in third-party backends. + + @cached_property + def template_dirs(self): + """ + Returns a list of directories to search for templates. + """ + # Immutable return value because it's cached and shared by callers. + template_dirs = tuple(self.dirs) + if self.app_dirs: + template_dirs += get_app_template_dirs(self.app_dirname) + return template_dirs + + def iter_template_filenames(self, template_name): + """ + Iterates over candidate files for template_name. + + Ignores files that don't lie inside configured template dirs to avoid + directory traversal attacks. + """ + for template_dir in self.template_dirs: + try: + yield safe_join(template_dir, template_name) + except SuspiciousFileOperation: + # The joined path was located outside of this template_dir + # (it might be inside another one, so this isn't fatal). + pass diff --git a/pool/shard001/Python/0013803_func.py b/pool/shard001/Python/0013803_func.py new file mode 100644 index 0000000000000000000000000000000000000000..f5eb2a06bdcebb8f8f19c642928ab9e637b7f6a0 --- /dev/null +++ b/pool/shard001/Python/0013803_func.py @@ -0,0 +1,90 @@ + +def gcd(m,n): + if n == 0: + return m + else: + return gcd(n , m%n) + +print (gcd(20, 30)) +print (type(gcd)) + +gcd2 = gcd +print (gcd2(20, 30)) +print (id(gcd), id(gcd2)) + +def sum(a, b): + return a + b + +def sum(a, b, c): + return a + b + c + +print (sum(1, 2, 3)) +# TypeError +#print (sum(1, 2)) + +def sum(a, b, c = 0): + return a + b + c + +print (sum(1, 2, 3)) +print (sum(1, 2)) + +print (sum(c=3, b=2, a=1)) + + +def appendTo(i, l=[]): + l.append(i) + return l + +print (appendTo(4, [1, 2, 3])) +print (appendTo(10)) + +print (appendTo(40, [10, 20, 30])) +print (appendTo(20)) + +def sum2(*numbers): + total = 0 + for number in numbers: + total += number + return total + +print (sum2(1, 2, 3)) +print (sum2(1, 2)) +print (sum2(1, 2, 3, 4, 5, 6)) + +def sum3(a, b, c): + return a + b + c + +data = (1, 2, 3) +print (sum3(*data)) + +def do(**args): + print (args) + +do(name = "John", age=20, job='?') +args = {'a': 1, 'b': 2, 'c':3} +print (sum3(**args)) + +def some(*arg1, **arg2): + print (arg1) + print (arg2) + +some(1, 2, 3, 4, 5, a=1, b=2, c=3) + + +def selection(number): + def min(m, j): + if j == len(number): + return m + elif number[j] < number[m]: + return min(j, j + 1) + else: + return min(m, j + 1) + + for i in range(0, len(number)): + m = min(i, i + 1) + if i != m: + number[i], number[m] = number[m], number[i] + +number = [1, 5, 2, 3, 9, 7] +selection(number) +print(number) \ No newline at end of file diff --git a/pool/shard001/Python/0013804_behave_test_steps.py b/pool/shard001/Python/0013804_behave_test_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..037b74fe8a130e1dc3fd5e732d0e4e6159834cab --- /dev/null +++ b/pool/shard001/Python/0013804_behave_test_steps.py @@ -0,0 +1,28 @@ +from behave import given, when, then, step + + +@given('we have behave installed') +def step_impl(context): + pass + + +@given('we should see our custom flags in context') +def step_impl(context): + assert context.config.userdata['test_value'] == 'this value should show up in my context' + + +@when('we implement {number:d} tests') +def step_impl(context, number): + assert number > 1 or number == 0 + context.tests_count = number + + +@then('behave will test them for us!') +def step_impl(context): + assert context.failed is False + assert context.tests_count >= 0 + + +@step('behave finds {number:d} feature files') +def step_impl(context, number): + assert len(context.config.paths) == 3 diff --git a/pool/shard001/Python/0013806_dataplumbing.py b/pool/shard001/Python/0013806_dataplumbing.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2e773c8a6d201f12fa98f5f79090afb5eb9f5e --- /dev/null +++ b/pool/shard001/Python/0013806_dataplumbing.py @@ -0,0 +1,77 @@ +######################################################################################### +# Author: Jared L. Ostmeyer +# Date Started: 2016-07-26 +# Environment: Python3 +# License: See LICENSE +# Purpose: Load dataset and create interfaces for piping the data to the model. +########################################################################################## + +import csv +import numpy as np + +import lib_paths +import atchley_factors as vector_representation + + +def load_repertoires(data_dir): + repertoires = dict() + with open(data_dir+'/data/answers.csv', 'r') as keyfile_stream: + keyfile_reader = csv.DictReader(keyfile_stream, delimiter=',') + for keyfile_row in keyfile_reader: + sample_id = keyfile_row['Sample'] + diagnosis_id = keyfile_row['Diagnosis'] + sequences = dict() + path = data_dir+'/data/sample_'+keyfile_row['Sample']+'.csv' + with open(path, 'r') as sample_stream: + sample_reader = csv.DictReader(sample_stream, delimiter=',') + for sample_row in sample_reader: + sequence = sample_row['Sequence'] + count = float(sample_row['Count']) + if sequence not in sequences: + sequences[sequence] = count + else: + sequences[sequence] += count + repertoires[sample_id] = { + 'Diagnosis': diagnosis_id, + 'Sequences': sequences + } + return repertoires + +def process_repertoires(repertoires, snip_size=6): + repertoires_snip = {} + for sample, repertoire in repertoires.items(): + diagnosis = repertoire['Diagnosis'] + snips = {} + for sequence, count in repertoire['Sequences'].items(): + stop = len(sequence)-snip_size+1 + for i in range(stop): + snip = sequence[i:i+snip_size] + if snip not in snips: + snips[snip] = count + else: + snips[snip] += count + repertoires_snip[sample] = { + 'Diagnosis': diagnosis, + 'Snips': snips + } + + num_samples = len(repertoires) + max_snips = -1 + num_features = snip_size*vector_representation.length + + for sample, repertoire in repertoires_snip.items(): + num_snips = len(repertoire['Snips']) + if num_snips > max_snips: + max_snips = num_snips + + xs = np.zeros((num_samples, max_snips, num_features), dtype=np.float32) # Features + cs = np.zeros((num_samples, max_snips), dtype=np.float32) # Snippet count + ys = np.zeros((num_samples), dtype=np.float32) # Labels + + for i, (sample, repertoire) in enumerate(sorted(repertoires_snip.items(), key=lambda item: item[0])): + for j, (snip, count) in enumerate(repertoire['Snips'].items()): + xs[i,j,:] = vector_representation.features(snip) + cs[i,j] = float(count) + ys[i] = float(repertoire['Diagnosis']) + return xs, cs, ys + diff --git a/pool/shard001/Python/0013811_device.py b/pool/shard001/Python/0013811_device.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7c30579394412becf75ff8253ffd54c62cc51b --- /dev/null +++ b/pool/shard001/Python/0013811_device.py @@ -0,0 +1,198 @@ +"""Adapter to wrap the rachiopy api for home assistant.""" + +import logging +from typing import Optional + +from homeassistant.const import EVENT_HOMEASSISTANT_STOP, HTTP_OK + +from .const import ( + KEY_DEVICES, + KEY_ENABLED, + KEY_EXTERNAL_ID, + KEY_FLEX_SCHEDULES, + KEY_ID, + KEY_MAC_ADDRESS, + KEY_MODEL, + KEY_NAME, + KEY_SCHEDULES, + KEY_SERIAL_NUMBER, + KEY_STATUS, + KEY_USERNAME, + KEY_ZONES, +) +from .webhooks import LISTEN_EVENT_TYPES, WEBHOOK_CONST_ID + +_LOGGER = logging.getLogger(__name__) + + +class RachioPerson: + """Represent a Rachio user.""" + + def __init__(self, rachio, config_entry): + """Create an object from the provided API instance.""" + # Use API token to get user ID + self.rachio = rachio + self.config_entry = config_entry + self.username = None + self._id = None + self._controllers = [] + + def setup(self, hass): + """Rachio device setup.""" + response = self.rachio.person.info() + assert int(response[0][KEY_STATUS]) == HTTP_OK, "API key error" + self._id = response[1][KEY_ID] + + # Use user ID to get user data + data = self.rachio.person.get(self._id) + assert int(data[0][KEY_STATUS]) == HTTP_OK, "User ID error" + self.username = data[1][KEY_USERNAME] + devices = data[1][KEY_DEVICES] + for controller in devices: + webhooks = self.rachio.notification.get_device_webhook(controller[KEY_ID])[ + 1 + ] + # The API does not provide a way to tell if a controller is shared + # or if they are the owner. To work around this problem we fetch the webooks + # before we setup the device so we can skip it instead of failing. + # webhooks are normally a list, however if there is an error + # rachio hands us back a dict + if isinstance(webhooks, dict): + _LOGGER.error( + "Failed to add rachio controller '%s' because of an error: %s", + controller[KEY_NAME], + webhooks.get("error", "Unknown Error"), + ) + continue + + rachio_iro = RachioIro(hass, self.rachio, controller, webhooks) + rachio_iro.setup() + self._controllers.append(rachio_iro) + _LOGGER.info('Using Rachio API as user "%s"', self.username) + + @property + def user_id(self) -> str: + """Get the user ID as defined by the Rachio API.""" + return self._id + + @property + def controllers(self) -> list: + """Get a list of controllers managed by this account.""" + return self._controllers + + def start_multiple_zones(self, zones) -> None: + """Start multiple zones.""" + self.rachio.zone.start_multiple(zones) + + +class RachioIro: + """Represent a Rachio Iro.""" + + def __init__(self, hass, rachio, data, webhooks): + """Initialize a Rachio device.""" + self.hass = hass + self.rachio = rachio + self._id = data[KEY_ID] + self.name = data[KEY_NAME] + self.serial_number = data[KEY_SERIAL_NUMBER] + self.mac_address = data[KEY_MAC_ADDRESS] + self.model = data[KEY_MODEL] + self._zones = data[KEY_ZONES] + self._schedules = data[KEY_SCHEDULES] + self._flex_schedules = data[KEY_FLEX_SCHEDULES] + self._init_data = data + self._webhooks = webhooks + _LOGGER.debug('%s has ID "%s"', str(self), self.controller_id) + + def setup(self): + """Rachio Iro setup for webhooks.""" + # Listen for all updates + self._init_webhooks() + + def _init_webhooks(self) -> None: + """Start getting updates from the Rachio API.""" + current_webhook_id = None + + # First delete any old webhooks that may have stuck around + def _deinit_webhooks(_) -> None: + """Stop getting updates from the Rachio API.""" + if not self._webhooks: + # We fetched webhooks when we created the device, however if we call _init_webhooks + # again we need to fetch again + self._webhooks = self.rachio.notification.get_device_webhook( + self.controller_id + )[1] + for webhook in self._webhooks: + if ( + webhook[KEY_EXTERNAL_ID].startswith(WEBHOOK_CONST_ID) + or webhook[KEY_ID] == current_webhook_id + ): + self.rachio.notification.delete(webhook[KEY_ID]) + self._webhooks = None + + _deinit_webhooks(None) + + # Choose which events to listen for and get their IDs + event_types = [] + for event_type in self.rachio.notification.get_webhook_event_type()[1]: + if event_type[KEY_NAME] in LISTEN_EVENT_TYPES: + event_types.append({"id": event_type[KEY_ID]}) + + # Register to listen to these events from the device + url = self.rachio.webhook_url + auth = WEBHOOK_CONST_ID + self.rachio.webhook_auth + new_webhook = self.rachio.notification.add( + self.controller_id, auth, url, event_types + ) + # Save ID for deletion at shutdown + current_webhook_id = new_webhook[1][KEY_ID] + self.hass.bus.listen(EVENT_HOMEASSISTANT_STOP, _deinit_webhooks) + + def __str__(self) -> str: + """Display the controller as a string.""" + return f'Rachio controller "{self.name}"' + + @property + def controller_id(self) -> str: + """Return the Rachio API controller ID.""" + return self._id + + @property + def current_schedule(self) -> str: + """Return the schedule that the device is running right now.""" + return self.rachio.device.current_schedule(self.controller_id)[1] + + @property + def init_data(self) -> dict: + """Return the information used to set up the controller.""" + return self._init_data + + def list_zones(self, include_disabled=False) -> list: + """Return a list of the zone dicts connected to the device.""" + # All zones + if include_disabled: + return self._zones + + # Only enabled zones + return [z for z in self._zones if z[KEY_ENABLED]] + + def get_zone(self, zone_id) -> Optional[dict]: + """Return the zone with the given ID.""" + for zone in self.list_zones(include_disabled=True): + if zone[KEY_ID] == zone_id: + return zone + + return None + + def list_schedules(self) -> list: + """Return a list of fixed schedules.""" + return self._schedules + + def list_flex_schedules(self) -> list: + """Return a list of flex schedules.""" + return self._flex_schedules + + def stop_watering(self) -> None: + """Stop watering all zones connected to this controller.""" + self.rachio.device.stop_water(self.controller_id) + _LOGGER.info("Stopped watering of all zones on %s", str(self)) diff --git a/pool/shard001/Python/0013812_create.py b/pool/shard001/Python/0013812_create.py new file mode 100644 index 0000000000000000000000000000000000000000..63c8e9834779eae01e0f89670ad3997712c52ad8 --- /dev/null +++ b/pool/shard001/Python/0013812_create.py @@ -0,0 +1,131 @@ +# Copyright (c) 2011 Cosku Acay, http://www.coskuacay.com + +import app.data as data +from app.generators import * + +# THIS CREATES THE ENEMY OBJECTS + +# Globals +canvas = 0 +MyShip = {} +enemies = {} +generators = {} + + +# Initialize generators and objects +def init(gameCanvas): + global MyShip + global generators + global canvas + global polygonShapes + + canvas = gameCanvas + # Create polygon data + polygonShapes = data.createPentagons("grey", "black", 1) + + # Create generators + generators["bulletGen"] = bulletGenerator(canvas, "orange", "black", 2, 8, 25) + generators["squareGen"] = objectGenerator(canvas, data.createRegular(4), "blue", + "black", 1, {"health": 2, "scale": 55, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.15}) + generators["triangleGen"] = objectGenerator(canvas, data.rightTri, "yellow", "black", + 1, {"health": 1, "scale": 40, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.12}) + generators["pentriGen"] = objectGenerator(canvas, data.pentri, "grey", "black", + 1, {"health": 1, "scale": 55, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.12}) + generators["pentagonGen"] = objectGenerator(canvas, data.createRegular(5), "grey", "black", + 1, {"health": 3, "scale": 55, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.12}) + generators["hexegonGen"] = objectGenerator(canvas, data.createRegular(6), "pink", "black", + 1, {"health": 6, "scale": 60, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.08}) + generators["myGodGen"] = objectGenerator(canvas, data.createRegular(8), "black", "black", + 1, {"health": 20, "scale": 12, "direction": "RANDOM", + "rotation": "RANDOM", "randomScale": 0.08}) + + # Create player ship + newShape = shape(data.triangle, "CENTROID", "brown", "black", 1, "CALC") + shipObj = smartObject(newShape, canvas) + shipObj.scale = 50 + MyShip["object"] = shipObj # smartObject + + +# Creates a triangle at the given location +def createTriangle(center): + global generators + global enemies + + newTriangle = next(generators["triangleGen"]) + newTriangle.position = list(center) + newTriangle.speed = 4 + random.random() * 8 + newTriangle.angularSpeed = radians(0.01 + random.random() * 10) + enemies["triangles"].append(newTriangle) + + +# Pentagons divide when hit. This function handles that +def createPenTri(center): + global generators + global enemies + + newTriangle = next(generators["pentriGen"]) + newTriangle.position = list(center) + newTriangle.speed = 5 + random.random() * 7 + newTriangle.angularSpeed = radians(0.5 + random.random() * 10) + enemies["triangles"].append(newTriangle) + + +# Creates a square at a random position +def createRandomSquare(): + global generators + global enemies + + newSquare = next(generators["squareGen"]) + x = -random.random() * 200 + y = -random.random() * 200 + newSquare.position = [x, y] + newSquare.speed = 2.5 + random.random() * 7 + newSquare.angularSpeed = radians(0.01 + random.random() * 5) + enemies["squares"].append(newSquare) + + +# Creates a pentagon at a random position +def createRandomPentagon(): + global generators + global enemies + + newPent = next(generators["pentagonGen"]) + x = -random.random() * 200 + y = -random.random() * 200 + newPent.position = [x, y] + newPent.speed = 3 + random.random() * 5 + newPent.angularSpeed = radians(0.01 + random.random() * 4) + enemies["pentagons"].append(newPent) + + +# Creates a hexegon at a random position +def createRandomHexegon(): + global generators + global enemies + + newHexe = next(generators["hexegonGen"]) + x = -random.random() * 200 + y = -random.random() * 200 + newHexe.position = [x, y] + newHexe.speed = 2 + random.random() * 4 + newHexe.angularSpeed = radians(0.01 + random.random() * 4) + enemies["hexegons"].append(newHexe) + + +# Creates a myGod at a random position +def createRandomMyGod(): + global generators + global enemies + + newGod = next(generators["myGodGen"]) + x = -random.random() * 200 + y = -random.random() * 200 + newGod.position = [x, y] + newGod.speed = 15 + random.random() * 6 + newGod.angularSpeed = radians(6 + random.random() * 6) + enemies["myGod"].append(newGod) diff --git a/pool/shard001/Python/0013814_cmd.py b/pool/shard001/Python/0013814_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..1dabfce400abbd7ccaaa65074fab8a98b81c4cdd --- /dev/null +++ b/pool/shard001/Python/0013814_cmd.py @@ -0,0 +1,37 @@ +""" +Commands for dealing with command scripts. +""" + +import qq +import os + + +class EditCommand(qq.QQCommand): + """ + Command for editing the file containing a command. + """ + + name = 'cmd.edit' + shorttext = 'Edit a command' + + def execute(self, command_name): + try: + inst = qq.instantiate_command(command_name) + except Exception as e: + qq.output('Failed to instantiate command: ' + command_name) + qq.output(e) + return False + if inst is None: + qq.output('Command not found: ' + command_name) + return False + editor = os.environ.get('EDITOR', None) + if editor is None: + qq.output('The EDITOR environment variable is not set.') + return False + qq.shell_execute('"{}" "{}"'.format(editor, inst.fullpath)) + return True + + def help(self): + return '''Usage: qq help COMMAND +Display help information about a particular command. + ''' diff --git a/pool/shard001/Python/0013819_01-run.py b/pool/shard001/Python/0013819_01-run.py new file mode 100644 index 0000000000000000000000000000000000000000..54647e54834d832372c4c844c352cc4c6bfb92be --- /dev/null +++ b/pool/shard001/Python/0013819_01-run.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +# Copyright (C) 2017 Freie Universität Berlin +# +# This file is subject to the terms and conditions of the GNU Lesser +# General Public License v2.1. See the file LICENSE in the top level +# directory for more details. + +import os +import sys + +sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) +import testrunner + +def testfunc(child): + child.expect_exact("On-board button test") + index = child.expect([ + r"\[FAILED\] no buttons available!", + r" -- Available buttons: \d+" + ]) + + if index == 1: + child.expect_exact("[SUCCESS]") + +if __name__ == "__main__": + sys.exit(testrunner.run(testfunc)) diff --git a/pool/shard001/Python/0013824_convert_seq.py b/pool/shard001/Python/0013824_convert_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..55654c2ca2df324845f8b8a8752463ea47c110de --- /dev/null +++ b/pool/shard001/Python/0013824_convert_seq.py @@ -0,0 +1,67 @@ +#!usr/bin/python + +# Copyright 2016, Rohan Dandage +# This program is distributed under General Public License v. 3. + +""" +================================ +``convert_seq`` +================================ +""" +from Bio.Seq import Seq +from Bio.Alphabet import generic_dna +import logging +logging.basicConfig(format='[%(asctime)s] %(levelname)s\tfrom %(filename)s in %(funcName)s(..): %(message)s',level=logging.DEBUG) # filename=cfg_xls_fh+'.log' + +def cmplmt(s): + """ + Gets complement of a sequence. + + :param s: sequence string. + """ + from dms2dfe.lib.global_vars import basecomplement + + letters = list(s) + letters = [basecomplement[base] for base in letters] + return ''.join(letters) +def revers(s): + """ + Gets reverse of a sequence. + + :param s: sequence string. + """ + return s[::-1] + +def revcom(s): + """ + Gets reverse complement of a sequence. + + :param s: sequence string. + """ + return cmplmt(s[::-1]) + +def cds2aas(cds_str,host,stop_codon='X') : + """ + This translates codons to amino acids. + + :param cds_str: codon sequence string. + :param host: name of host organism for choosing codon table. [coli | yeast | sapiens]. + :returns aas: amino acid. + """ + coding_dna = Seq(cds_str, generic_dna) + #aas='' + if len(coding_dna)%3 != 0 : + # logging.error('len(coding_dna)%3 != 0') + # print coding_dna + return False + elif "coli" in host : + aas=str(coding_dna.translate(table=11)) # http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi + elif "yeast" in host : + aas=str(coding_dna.translate(table=12)) + elif "sapiens" in host : + aas=str(coding_dna.translate(table=1)) + if stop_codon!='X': + return aas + else: + return aas.replace("*", "X") + diff --git a/pool/shard001/Python/0013825_base.py b/pool/shard001/Python/0013825_base.py new file mode 100644 index 0000000000000000000000000000000000000000..c477a703099c5815eb26e19621134148e76a01b9 --- /dev/null +++ b/pool/shard001/Python/0013825_base.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +import os +from .mixins import UserGetOrCreateMixin + +from bunch import Bunch +import hashlib + +settings = {} + + +class AbridgeConnectionBase(UserGetOrCreateMixin): + """ + Base Mailout Connection + """ + ABRIDGE_API_VERSION = 'api/v1/' + + def __init__(self, ABRIDGE_PROJECT, ABRIDGE_SECRET_ACCESS_KEY, **kwargs): + super(AbridgeConnectionBase, self).__init__() + + check_user = kwargs.get('check_user', True) + + self.ABRIDGE_ENABLED = kwargs.get('ABRIDGE_ENABLED', True) + self.ABRIDGE_API_URL = kwargs.get('ABRIDGE_API_URL', 'http://localhost:8006/') + + self.ABRIDGE_PROJECT = ABRIDGE_PROJECT + self.ABRIDGE_SECRET_ACCESS_KEY = ABRIDGE_SECRET_ACCESS_KEY + + if self.ABRIDGE_API_URL[-1] != '/': + raise Exception("The settings.ABRIDGE_API_URL must end in a \"/\"") + + if self.ABRIDGE_SECRET_ACCESS_KEY is None: + raise Exception("You must specify a ABRIDGE_SECRET_ACCESS_KEY") + + if self.ABRIDGE_PROJECT is None: + raise Exception("You must specify a ABRIDGE_PROJECT") + + kwargs = self.subscriber_in_kwargs(**kwargs) # we have a new user? + # append kwargs to class + self.__dict__.update(kwargs) + + if check_user is True: + # ensure that we have the current logged in user in abridge + self.ensure_abridge_subscriber() + + @property + def headers(self): + return { + 'Authorization': 'Bearer {access_token}'.format(access_token=self.ABRIDGE_SECRET_ACCESS_KEY), + 'Content-Type': 'application/json', + 'Accept': 'application/json', + } + + def extract_subscriber(self, subscriber): + """ + Extract a useable subscriber object + """ + if subscriber is None: + return None + else: + if getattr(subscriber, 'email', None): + raise Exception('subscriber must have a .email attribute') + else: + + # main id + self._email = getattr(subscriber, 'email', subscriber.get('email')) + # create a hash from the current users email address + self._email_hash = hashlib.md5(self._email.encode('utf-8')).hexdigest() + + # less important data + self._first_name = getattr(subscriber, 'first_name', subscriber.get('first_name')) + self._last_name = getattr(subscriber, 'last_name', subscriber.get('last_name')) + + # reset the subscriber to a valid object + self._subscriber = None # reset the current subscriber + self._subscriber = Bunch({ + 'email': self._email, + 'email_hash': self._email_hash, + 'first_name': self._first_name, + 'last_name': self._last_name, + 'subscriptions': [], + }) + + return self._subscriber + + def get_url(self, path): + """ + parse url correctly + """ + dir(self) + return '{base}{api_version}{path}'.format(base=self.ABRIDGE_API_URL, + api_version=self.ABRIDGE_API_VERSION, + path=path) + diff --git a/pool/shard001/Python/0013833_init__.py b/pool/shard001/Python/0013833_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..939844143882ddcce5554a9bc1de00d1917f9d06 --- /dev/null +++ b/pool/shard001/Python/0013833_init__.py @@ -0,0 +1,170 @@ +# Author: Krzysztof Dorosz +# +# Disclaimer: +# Writing and open sourcing this backend was kindly funded by Issue Stand +# http://issuestand.com/ +# + +from decimal import Decimal +import hashlib +import logging +import time +import datetime +from django.utils import six +from six.moves.urllib.request import Request, urlopen +from six.moves.urllib.parse import urlencode + +from django.core.exceptions import ImproperlyConfigured +from django.core.urlresolvers import reverse +from django.utils.translation import ugettext_lazy as _ +from pytz import utc + +from getpaid import signals +from getpaid.backends import PaymentProcessorBase +from getpaid.backends.przelewy24.tasks import get_payment_status_task +from getpaid.utils import get_domain + +logger = logging.getLogger('getpaid.backends.przelewy24') + + +class PaymentProcessor(PaymentProcessorBase): + BACKEND = u'getpaid.backends.przelewy24' + BACKEND_NAME = _(u'Przelewy24') + BACKEND_ACCEPTED_CURRENCY = (u'PLN',) + BACKEND_LOGO_URL = u'getpaid/backends/przelewy24/przelewy24_logo.png' + + _GATEWAY_URL = u'https://secure.przelewy24.pl/index.php' + _SANDBOX_GATEWAY_URL = u'https://sandbox.przelewy24.pl/index.php' + + _GATEWAY_CONFIRM_URL = u'https://secure.przelewy24.pl/transakcja.php' + _SANDBOX_GATEWAY_CONFIRM_URL = u'https://sandbox.przelewy24.pl/transakcja.php' + + _ACCEPTED_LANGS = (u'pl', u'en', u'es', u'de', u'it') + _REQUEST_SIG_FIELDS = (u'p24_session_id', u'p24_id_sprzedawcy', u'p24_kwota', u'crc') + _SUCCESS_RETURN_SIG_FIELDS = (u'p24_session_id', u'p24_order_id', u'p24_kwota', u'crc') + _STATUS_SIG_FIELDS = (u'p24_session_id', u'p24_order_id', u'p24_kwota', u'crc') + + @staticmethod + def compute_sig(params, fields, crc): + params = params.copy() + params.update({'crc': crc}) + text = u"|".join(map(lambda field: six.text_type(params.get(field, '')), fields)) + return six.text_type(hashlib.md5(text.encode('utf-8')).hexdigest()) + + @staticmethod + def on_payment_status_change(p24_session_id, p24_order_id, p24_kwota, p24_order_id_full, p24_crc): + params = { + 'p24_session_id': p24_session_id, + 'p24_order_id': p24_order_id, + 'p24_kwota': p24_kwota, + 'p24_order_id_full': p24_order_id_full, + 'p24_crc': p24_crc, + } + crc = PaymentProcessor.get_backend_setting('crc') + if p24_crc != PaymentProcessor.compute_sig(params, PaymentProcessor._SUCCESS_RETURN_SIG_FIELDS, + crc): + logger.warning('Success return call has wrong crc %s' % str(params)) + return False + + payment_id = p24_session_id.split(':')[0] + get_payment_status_task.delay(payment_id, p24_session_id, p24_order_id, p24_kwota) + return True + + def get_payment_status(self, p24_session_id, p24_order_id, p24_kwota): + params = { + 'p24_session_id': p24_session_id, + 'p24_order_id': p24_order_id, + 'p24_id_sprzedawcy': PaymentProcessor.get_backend_setting('id'), + 'p24_kwota': p24_kwota, + } + crc = PaymentProcessor.get_backend_setting('crc') + params['p24_crc'] = PaymentProcessor.compute_sig(params, self._STATUS_SIG_FIELDS, crc) + + for key in params.keys(): + params[key] = six.text_type(params[key]).encode('utf-8') + + data = urlencode(params).encode('utf-8') + + url = self._GATEWAY_CONFIRM_URL + if PaymentProcessor.get_backend_setting('sandbox', False): + url = self._SANDBOX_GATEWAY_CONFIRM_URL + + self.payment.external_id = p24_order_id + + request = Request(url, data) + try: + response = urlopen(request).read().decode('utf8') + except Exception: + logger.exception('Error while getting payment status change %s data=%s' % (url, str(params))) + return + + response_list = list(filter(lambda ll: ll, map(lambda li: li.strip(), response.splitlines()))) + + if len(response_list) >= 2 and response_list[0] == 'RESULT' and response_list[1] == 'TRUE': + logger.info('Payment accepted %s' % str(params)) + self.payment.amount_paid = Decimal(p24_kwota) / Decimal('100') + self.payment.paid_on = datetime.datetime.utcnow().replace(tzinfo=utc) + if self.payment.amount_paid >= self.payment.amount: + self.payment.change_status('paid') + else: + self.payment.change_status('partially_paid') + else: + logger.warning('Payment rejected for data=%s: "%s"' % (str(params), response)) + self.payment.change_status('failed') + + def get_gateway_url(self, request): + """ + Routes a payment to Gateway, should return URL for redirection. + + """ + params = { + 'p24_id_sprzedawcy': PaymentProcessor.get_backend_setting('id'), + 'p24_opis': self.get_order_description(self.payment, self.payment.order), + 'p24_session_id': "%s:%s:%s" % (self.payment.pk, self.BACKEND, time.time()), + 'p24_kwota': int(self.payment.amount * 100), + 'p24_email': None, + + } + + user_data = { + 'email': None, + 'lang': None, + 'p24_klient': None, + 'p24_adres': None, + 'p24_kod': None, + 'p24_miasto': None, + 'p24_kraj': None, + } + signals.user_data_query.send(sender=None, order=self.payment.order, user_data=user_data) + + for key in ('p24_klient', 'p24_adres', 'p24_kod', 'p24_miasto', 'p24_kraj'): + if user_data[key] is not None: + params[key] = user_data[key] + + if user_data['email']: + params['p24_email'] = user_data['email'] + + if user_data['lang'] and user_data['lang'].lower() in PaymentProcessor._ACCEPTED_LANGS: + params['p24_language'] = user_data['lang'].lower() + elif PaymentProcessor.get_backend_setting('lang', False) and PaymentProcessor.get_backend_setting( + 'lang').lower() in PaymentProcessor._ACCEPTED_LANGS: + params['p24_language'] = PaymentProcessor.get_backend_setting('lang').lower() + + params['p24_crc'] = self.compute_sig(params, self._REQUEST_SIG_FIELDS, + PaymentProcessor.get_backend_setting('crc')) + + current_site = get_domain() + use_ssl = PaymentProcessor.get_backend_setting('ssl_return', False) + + params['p24_return_url_ok'] = ('https://' if use_ssl else 'http://') + current_site + reverse( + 'getpaid:przelewy24:success', kwargs={'pk': self.payment.pk}) + params['p24_return_url_error'] = ('https://' if use_ssl else 'http://') + current_site + reverse( + 'getpaid:przelewy24:failure', kwargs={'pk': self.payment.pk}) + + if params['p24_email'] is None: + raise ImproperlyConfigured( + '%s requires filling `email` field for payment ' + '(you need to handle `user_data_query` signal)' % self.BACKEND) + + return self._SANDBOX_GATEWAY_URL if PaymentProcessor.get_backend_setting( + 'sandbox', False) else self._GATEWAY_URL, 'POST', params diff --git a/pool/shard001/Python/0013834_B.py b/pool/shard001/Python/0013834_B.py new file mode 100644 index 0000000000000000000000000000000000000000..aec7e42970fecdfcc1b74ea8ec09d6871d82f1bf --- /dev/null +++ b/pool/shard001/Python/0013834_B.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Problem: Out of Gas +# Language: Python +# Author: KirarinSnow +# Usage: python thisfile.py output.out +# Comments: Uses http://mpmath.googlecode.com for arbitrary precision. + + +from mpmath import * + +# precision +mp.dps = 15 + +for case in range(int(raw_input())): + print "Case #%d:" % (case+1) + l = raw_input().split() + d = mpf(l.pop(0)) + n, a = map(int, l) + + tt, xx = zip(*[map(mpf, raw_input().split()) for i in range(n)]) + + # add final point (t, d) where t is the time that the other car gets there + t = [] + x = [] + for i in range(n): + if xx[i] <= d: + t.append(tt[i]) + x.append(xx[i]) + if len(x) > 0 and x[-1] < d: + j = len(x) + v = (xx[j]-xx[j-1])/(tt[j]-tt[j-1]) + b = xx[j]-v*tt[j] + tc = (d-b)/v + x.append(d) + t.append(tc) + + nn = len(x) + + accs = map(mpf, raw_input().split()) + + # for each point, compute the time delay necessary to reach that point + # if we wait at the top of the hill for the current delay and then + # accelerate without braking + for acc in accs: + delay = mpf(0) + for i in range(1, nn): + if x[i] < mpf('0.5')*acc*(t[i]-delay)**mpf(2): + delay = t[i]-sqrt(mpf(2)*x[i]/acc) + print sqrt(d*mpf(2)/acc)+delay diff --git a/pool/shard001/Python/0013836_conf.py b/pool/shard001/Python/0013836_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..76acba6b6dbb4a09756266b015771aece59f01c6 --- /dev/null +++ b/pool/shard001/Python/0013836_conf.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# Licensed to Cloudera, Inc. under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. Cloudera, Inc. licenses this file +# to you 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 logging +import os +import sys + +from desktop.lib.conf import Config + +if sys.version_info[0] > 2: + from django.utils.translation import gettext_lazy as _t +else: + from django.utils.translation import ugettext_lazy as _t + + +LOG = logging.getLogger(__name__) + + +HOSTNAME=Config( + key='hostname', + help=_t('Hostname or IP of server.'), + type=str, + default='localhost', +) + +PORT=Config( + key='port', + help=_t('Port the sentry service is running on.'), + type=int, + default=8038, +) + +SENTRY_CONF_DIR = Config( + key='sentry_conf_dir', + help=_t('Sentry configuration directory, where sentry-site.xml is located.'), + default=os.environ.get("SENTRY_CONF_DIR", '/etc/sentry/conf') +) + +PRIVILEGE_CHECKER_CACHING=Config( + key='privilege_checker_caching', + help=_t('Number of seconds when the privilege list of a user is cached.'), + type=int, + default=60 * 5, +) + + +def is_enabled(): + from hadoop import cluster # Avoid dependencies conflicts + cluster = cluster.get_cluster_conf_for_job_submission() + + return HOSTNAME.get() != 'localhost' and cluster.SECURITY_ENABLED.get() diff --git a/pool/shard001/Python/0013837_init__.py b/pool/shard001/Python/0013837_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f52748def64b64259d9d58c1609db1816b179d8f --- /dev/null +++ b/pool/shard001/Python/0013837_init__.py @@ -0,0 +1,142 @@ +""" +MIDI input package +provides a dock which allows to capture midi events and insert notes + +- input is static, not dynamic +- special midi events (e. g. damper pedal) can modify notes (e. g. duration) + or insert elements (e. g. slurs) + +current limitations: +- special events not implemented yet + +TODO: + dynamic input +""" + +import time +import weakref + +from PyQt4.QtCore import QObject, QSettings, QThread, SIGNAL + +import midihub +import midifile.event +import midifile.parser +import documentinfo + +from . import elements + + +class MidiIn(object): + def __init__(self, widget): + self._widget = weakref.ref(widget) + self._portmidiinput = None + self._listener = None + self._chord = None + + def __del__(self): + if isinstance(self._listener, Listener): + self.capturestop() + + def widget(self): + return self._widget() + + def open(self): + s = QSettings() + self._portname = s.value("midi/input_port", midihub.default_input(), type("")) + self._pollingtime = s.value("midi/polling_time", 10, int) + self._portmidiinput = midihub.input_by_name(self._portname) + + self._listener = Listener(self._portmidiinput, self._pollingtime) + QObject.connect(self._listener, SIGNAL("caughtevent"), self.analyzeevent) + + def close(self): + # self._portmidiinput.close() + # this will end in segfault with pyportmidi 0.0.7 in ubuntu + # see https://groups.google.com/d/msg/pygame-mirror-on-google-groups/UA16GbFsUDE/RkYxb9SzZFwJ + # so we cleanup ourself and invoke __dealloc__() by garbage collection + # so discard any reference to a pypm.Input instance + if self._portmidiinput: + self._portmidiinput._input = None + self._portmidiinput = None + self._listener = None + + def capture(self): + if not self._portmidiinput: + self.open() + if not self._portmidiinput: + return + doc = self.widget().mainwindow().currentDocument() + self._language = documentinfo.docinfo(doc).language() or 'nederlands' + self._activenotes = 0 + self._listener.start() + + def capturestop(self): + self._listener.stop() + if not self._listener.isFinished(): + self._listener.wait() + self._activenotes = 0 + self.close() + + def analyzeevent(self, event): + if isinstance(event, midifile.event.NoteEvent): + self.noteevent(event.type, event.channel, event.note, event.value) + + def noteevent(self, notetype, channel, notenumber, value): + targetchannel = self.widget().channel() + if channel == targetchannel or targetchannel == 0: # '0' captures all + if notetype == 9 and value > 0: # note on with velocity > 0 + notemapping = elements.NoteMapping(self.widget().keysignature(), self.widget().accidentals()=='sharps') + note = elements.Note(notenumber, notemapping) + if self.widget().chordmode(): + if not self._chord: # no Chord instance? + self._chord = elements.Chord() + self._chord.add(note) + self._activenotes += 1 + else: + self.printwithspace(note.output(self.widget().relativemode(), self._language)) + elif (notetype == 8 or (notetype == 9 and value == 0)) and self.widget().chordmode(): + self._activenotes -= 1 + if self._activenotes <= 0: # activenotes could get negative under strange conditions + if self._chord: + self.printwithspace(self._chord.output(self.widget().relativemode(), self._language)) + self._activenotes = 0 # reset in case it was negative + self._chord = None + + def printwithspace(self, text): + cursor = self.widget().mainwindow().textCursor() + # check if there is a space before cursor or beginning of line + posinblock = cursor.position() - cursor.block().position() + charbeforecursor = cursor.block().text()[posinblock-1:posinblock] + if charbeforecursor.isspace() or cursor.atBlockStart(): + cursor.insertText(text) + else: + cursor.insertText(' ' + text) + +class Listener(QThread): + def __init__(self, portmidiinput, pollingtime): + QThread.__init__(self) + self._portmidiinput = portmidiinput + self._pollingtime = pollingtime + + def run(self): + self._capturing = True + while self._capturing: + while not self._portmidiinput.poll(): + time.sleep(self._pollingtime/1000.) + if not self._capturing: + break + if not self._capturing: + break + data = self._portmidiinput.read(1) + + # midifile.parser.parse_midi_events is a generator which expects a long "byte string" from a file, + # so we feed it one. But since it's just one event, we only need the first "generated" element. + # First byte is time, which is unnecessary in our case, so we feed a dummy byte 77 + # and strip output by just using [1]. 77 is chosen randomly ;) + s = bytearray([77, data[0][0][0], data[0][0][1], data[0][0][2], data[0][0][3]]) + event = next(midifile.parser.parse_midi_events(s))[1] + + self.emit(SIGNAL("caughtevent"), event) + + def stop(self): + self._capturing = False diff --git a/pool/shard001/Python/0013841_wal_transfer.py b/pool/shard001/Python/0013841_wal_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..19b6b314f9b9b4de6dac4fa2c79fb9ae2da61188 --- /dev/null +++ b/pool/shard001/Python/0013841_wal_transfer.py @@ -0,0 +1,169 @@ +import gevent +import os +import re +import traceback + +from gevent import queue +from os import path +from wal_e.exception import UserCritical +from wal_e.storage import s3_storage + + +class WalSegment(object): + def __init__(self, seg_path, explicit=False): + self.path = seg_path + self.explicit = explicit + self.name = path.basename(self.path) + + def mark_done(self): + """Mark the archive status of this segment as 'done'. + + This is most useful when performing out-of-band parallel + uploads of segments, so that Postgres doesn't try to go and + upload them again. + + This amounts to messing with an internal bookkeeping mechanism + of Postgres, but that mechanism is not changing too fast over + the last five years and seems simple enough. + """ + + # Recheck that this is not an segment explicitly passed from Postgres + if self.explicit: + raise UserCritical( + msg='unexpected attempt to modify wal metadata detected', + detail=('Segments explicitly passed from postgres should not ' + 'engage in archiver metadata manipulation: {0}' + .format(self.path)), + hint='report a bug') + + # Attempt a rename of archiver metadata, wrapping unexpected + # raised exceptions into a UserCritical. + try: + status_dir = path.join(path.dirname(self.path), + 'archive_status') + + ready_metadata = path.join(status_dir, self.name + '.ready') + done_metadata = path.join(status_dir, self.name + '.done') + + os.rename(ready_metadata, done_metadata) + except StandardError: + raise UserCritical( + msg='problem moving .ready archive status to .done', + detail='Traceback is: {0}'.format(traceback.format_exc()), + hint='report a bug') + + @staticmethod + def from_ready_archive_status(xlog_dir): + status_dir = path.join(xlog_dir, 'archive_status') + statuses = os.listdir(status_dir) + + # Try to send earliest segments first. + statuses.sort() + + for status in statuses: + # Only bother with segments, not history files and such; + # it seems like special treatment of such quantities is + # more likely to change than that of the WAL segments, + # which are bulky and situated in a particular place for + # crash recovery. + match = re.match(s3_storage.SEGMENT_READY_REGEXP, status) + + if match: + seg_name = match.groupdict()['filename'] + seg_path = path.join(xlog_dir, seg_name) + + yield WalSegment(seg_path, explicit=False) + + +class WalTransferGroup(object): + """Concurrency and metadata manipulation for parallel transfers. + + It so happens that it looks like WAL segment uploads and downloads + can be neatly done with one mechanism, so do so here. + """ + + def __init__(self, transferer): + # Injected transfer mechanism + self.transferer = transferer + + # Synchronization and tasks + self.wait_change = queue.Queue(maxsize=0) + self.expect = 0 + self.closed = False + + # Maintain a list of running greenlets for gevent.killall. + # + # Abrupt termination of WAL-E (e.g. calling exit, as seen with + # a propagated error) will not result in clean-ups + # (e.g. 'finally' clauses) being run, so it's necessary to + # retain the greenlets, inject asynchronous exceptions, and + # then wait on termination. + self.greenlets = set([]) + + def join(self): + """Wait for transfer to exit, raising errors as necessary.""" + self.closed = True + + while self.expect > 0: + val = self.wait_change.get() + self.expect -= 1 + + if val is not None: + # Kill all the running greenlets, waiting for them to + # clean up and exit. + # + # As a fail-safe against indefinite blocking of + # gevent.killall, time out after a liberal amount of + # time. This is not expected to ever occur except for + # bugs and very dire situations, so do not take pains + # to convert it into a UserException or anything. + gevent.killall(self.greenlets, block=True, timeout=60) + raise val + + def start(self, segment): + """Begin transfer for an indicated wal segment.""" + + if self.closed: + raise UserCritical(msg='attempt to transfer wal after closing', + hint='report a bug') + + g = gevent.Greenlet(self.transferer, segment) + g.link(self._complete_execution) + self.greenlets.add(g) + + # Increment .expect before starting the greenlet, or else a + # very unlucky .join could be fooled as to when pool is + # complete. + self.expect += 1 + + g.start() + + def _complete_execution(self, g): + """Forward any raised exceptions across a channel.""" + + # Triggered via completion callback. + # + # Runs in its own greenlet, so take care to forward the + # exception, if any, to fail the entire transfer in event of + # trouble. + assert g.ready() + self.greenlets.remove(g) + + placed = UserCritical(msg='placeholder bogus exception', + hint='report a bug') + + if g.successful(): + try: + segment = g.get() + + if not segment.explicit: + segment.mark_done() + except StandardError, e: + # Absorb and forward exceptions across the channel. + placed = e + else: + placed = None + else: + placed = g.exception + + self.wait_change.put(placed) diff --git a/pool/shard001/Python/0013843_ParameterDialog.py b/pool/shard001/Python/0013843_ParameterDialog.py new file mode 100644 index 0000000000000000000000000000000000000000..f188956cc29de554051b7b16be09353a1c67028d --- /dev/null +++ b/pool/shard001/Python/0013843_ParameterDialog.py @@ -0,0 +1,171 @@ +import re +from PyQt4.QtCore import * +from PyQt4.QtGui import * +import PyQt4.QtCore as QtCore +import ui_parameterdlg +import sys +import os.path +# from CC3DProject.enums import * +from ParameterScanEnums import * + +MAC = "qt_mac_set_native_menubar" in dir() + + + +class TablePushButton(QPushButton): + def __init__(self,_parent=None): + super(TablePushButton,self).__init__(_parent) + self.row=-1 + self.col=-1 + + def setPosition(self,_row,_col): + self.row=_row + self.col=_col + + def getPosition(self): + return self.row,self.col + +class ParameterDialog(QDialog,ui_parameterdlg.Ui_ParameterDlg): + #signals + # gotolineSignal = QtCore.pyqtSignal( ('int',)) + + def __init__(self,parent=None): + super(ParameterDialog, self).__init__(parent) + self.fileType='XML' + + self.scannableParams={} + self.xmlString='' + self.accessPath='' + self.parameterScanXMLElements={} + self.parameterScanDataMap={} + + # self.scannedFileName='' # name of the file being scanned - can be either XML , or Python + + self.setupUi(self) + + self.updateUi() + + def setFileType(self,_type): + self.fileType=_type + + def __handleActionClicked(self): + senderBtn=self.sender() + row,col=senderBtn.getPosition() + print 'clicked row,column=',(row,col) + from ParameterScanUtils import ParameterScanData + + nameItem=self.paramTW.item(row,PARAMETER) + + valueItem=self.paramTW.item(row,VALUE) + + # value=float(valueItem.text()) + value=str(valueItem.text()) + + print 'TYPE=',TYPE + typeItem=self.paramTW.item(row,TYPE) + type=TYPE_DICT_REVERSE[str(typeItem.text())] + print 'type=',type,'\n\n\n\n' + + psd=ParameterScanData() + + psd.name=str(nameItem.text()) + psd.type=type + psd.accessPath=self.accessPath + + # show param scan values generation dialog + from ParValDlg import ParValDlg + parvaldlg=ParValDlg(self) + parvaldlg.initParameterScanData(_parValue=value,_parName=psd.name,_parType=psd.type,_parAccessPath=psd.accessPath) + # parvaldlg.setAutoMinMax(value) + + if parvaldlg.exec_(): + valueStr=str() + try: + psd.customValues=parvaldlg.getValues() + except ValueError,e: + QMessageBox.warning(self,"Error Parsing Parameter List","Please make sure that parameter list entries have correct type") + return + psd.valueType=parvaldlg.getValueType() + # VALUE_TYPE_DICT_REVERSE[parvaldlg.getValueType()] + else: + #user canceled + return + + el=psd.toXMLElem() + + from ParameterScanUtils import XMLHandler + xmlHandler=XMLHandler() + xmlHandler.writeXMLElement(el.CC3DXMLElement) # because ElementCC3D was constructed in Python we need to get C++ object (CC3DXMLElement) from it this is what writeXMLElement expects + self.parameterScanDataMap[psd.stringHash()]=psd + + # print 'xmlElem=',xmlHandler.xmlString + + + def displayXMLScannableParameters(self,_elem,_accessPath,_parameterScanFile): + + self.accessPath=_accessPath + + from ParameterScanUtils import ParameterScanUtils + + psu=ParameterScanUtils() + print 'xmlElem=',_elem + + self.xmlString='<'+_elem.name+' ' + for key in _elem.attributes.keys(): + self.xmlString+=' '+key+'="'+_elem.attributes[key]+'"' + + self.xmlString+='>' + self.elemLE.setText(self.xmlString) + + self.scannableParams=psu.extractXMLScannableParameters(_elem,_parameterScanFile) + + table=self.paramTW + + for paramName, paramProps in self.scannableParams.iteritems(): + currentRow=table.rowCount() + # if table.rowCount()>0 else 0 + print 'currentRow=',currentRow,'paramName=',paramName + table.insertRow(currentRow) + paramNameItem=QTableWidgetItem(paramName) + paramValueItem=QTableWidgetItem(paramProps[0]) + + paramTypeItem=QTableWidgetItem(TYPE_DICT[paramProps[1]]) + + btn = TablePushButton(table) + + + actionItem=None + btn.setText('Edit...') + # if paramProps[1]==0: + # btn.setText('Add To Scan...') + # # actionItem=QTableWidgetItem('Add To Scan') + # elif paramProps[1]==1: + # btn.setText('View/Edit...') + # # actionItem=QTableWidgetItem('View/Edit...') + + table.setItem (currentRow,PARAMETER, paramNameItem) + table.setItem (currentRow,VALUE, paramValueItem) + table.setItem (currentRow,TYPE, paramTypeItem) + + table.setCellWidget(currentRow, ACTION, btn) + btn.setPosition(currentRow, ACTION) + btn.clicked.connect(self.__handleActionClicked) + + def displayPythonScannableParameters(self,_pythonLine,_parameterScanFile): + print '_pythonLine=',_pythonLine + from ParameterScanUtils import ParameterScanUtils + psu=ParameterScanUtils() + foundGlobalVar=psu.checkPythonLineForGlobalVariable(_pythonLine) + print 'foundGlobalVar=',foundGlobalVar + + + def updateUi(self): + table=self.paramTW + table.verticalHeader().setDefaultSectionSize(20) + table.horizontalHeader().setDefaultSectionSize(20) + + table.horizontalHeader().setResizeMode(QHeaderView.Stretch) + + + + diff --git a/pool/shard001/Python/0013847_test.py b/pool/shard001/Python/0013847_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f644379365dbefca3edf4b41745ee6b88f0510fb --- /dev/null +++ b/pool/shard001/Python/0013847_test.py @@ -0,0 +1,139 @@ + +# Voyager distance calculations using SPICE and Voyager kernels. +# Uses Python interface - see https://github.com/AndrewAnnex/SpiceyPy + +# Instructions: +# run `pip install spicepy` +# Download +# ftp://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0012.tls +# ftp://naif.jpl.nasa.gov/pub/naif/VOYAGER/kernels/spk/Voyager_1.a54206u_V0.2_merged.bsp +# ftp://naif.jpl.nasa.gov/pub/naif/VOYAGER/kernels/spk/Voyager_2.m05016u.merged.bsp + + + +import math +import spiceypy as spice + + +# utc time range +# utcStart = '1979-03-01' +# utcStart = '1979-01-01' +# utcStop = '1979-03-10' +utcStart = '1986-01-01' +utcStop = '1986-01-30' + +# target and observer +# target = 'JUPITER BARYCENTER' +# target = 'Ganymede' +# target = 'URANUS' +target = 'URANUS BARYCENTER' +# observer = 'VOYAGER 1' +# observer = 'Voyager 1' +observer = 'VOYAGER 2' + + +def et2str(et): + "Convert an ephemeris time (seconds after J2000) to a UTC string." + # see https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html + formatStr = "ISOC" + prec = 0 + s = spice.et2utc(et, formatStr, prec, lenout=256) + return s + +def getDistance(x,y,z): + return math.sqrt(x**2+y**2+z**2) + + +# load kernels (data files) +spice.furnsh('naif0012.tls') # leap second data +spice.furnsh('Voyager_1.a54206u_V0.2_merged.bsp') +spice.furnsh('Voyager_2.m05016u.merged.bsp') +# spice.furnsh('jup100.bsp') # jupiter satellite data (20mb) + +# get ephemeris time (seconds since J2000) +etStart = spice.str2et(utcStart) +etStop = spice.str2et(utcStop) + +# get time range +nsteps = 50 +etTimes = [i*(etStop-etStart)/nsteps + etStart for i in range(nsteps)] + +# get vectors from observer to target +# see http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpos_c.html +frame = 'J2000' +abcorr = 'NONE' # abberation correction +positions, lightTimes = spice.spkpos(target, etTimes, frame, abcorr, observer) + + + + +# # spice.furnsh('kernels/naif0012.tls') # load leap second data +# # spice.furnsh('kernels/Voyager_1.a54206u_V0.2_merged.bsp') # voyager 1 data + +# # get field values +# # volume,fileid,phase,craft,target,time,instrument,filter,note +# # volume = row[config.filesColVolume] # eg 5101 +# # fileId = row[config.filesColFileId] # eg C1385455 +# # phase = row[config.filesColPhase] # eg Jupiter +# # craft = row[config.filesColCraft] # eg Voyager1 +# # target = row[config.filesColTarget] # eg Io +# target = 'Jupiter' +# # time = row[config.filesColTime] # eg 1978-12-11T01:03:29 +# time = '1978-12-11T01:03:29' +# # instrument = row[config.filesColInstrument] # eg Narrow + +# et = spice.str2et(time) +# frame = 'J2000' +# abcorr = 'NONE' # abberation correction +# target = target + ' BARYCENTER' +# observer = 'Voyager 1' +# position, lightTime = spice.spkpos(target, et, frame, abcorr, observer) +# print position +# # distance = getDistance(position) +# # fields = 'volume,imageId,target,distance(km)'.split(',') # keep in synch with row, below +# # row = [volume,fileId,target,distance] +# # print row +# # writer.writerow(row) +# # print distance + + +# end + + + + + + +# get distances +# distances = [math.sqrt(x**2+y**2+z**2) for x,y,z in positions] +distances = [getDistance(x,y,z) for x,y,z in positions] + +# Jupiter has a mean radius of 69,911 kilometers + +# Voyager 1's closest approach to Jupiter occurred March 5, 1979 +# Distance 349,000 km +# Voyager 2's closest approach to Jupiter occurred on July 9, 1979. +# It came within 570,000 km of the planet's cloud tops. + +for i, distance in enumerate(distances): + print "%s %.0f" % (et2str(etTimes[i]), distance) + +# 1979-03-04T10:04:48 1720452 +# 1979-03-04T14:24:00 1482460 +# 1979-03-04T18:43:12 1238139 +# 1979-03-04T23:02:24 987003 +# 1979-03-05T03:21:36 730901 +# 1979-03-05T07:40:48 485618 +# 1979-03-05T12:00:00 348461 +# 1979-03-05T16:19:12 477570 +# 1979-03-05T20:38:24 721531 +# 1979-03-06T00:57:36 977694 +# 1979-03-06T05:16:48 1229137 +# 1979-03-06T09:36:00 1473770 +# 1979-03-06T13:55:12 1712063 + +# Clean up the kernels +spice.kclear() + + + diff --git a/pool/shard001/Python/0013850_xml_tcp_client.py b/pool/shard001/Python/0013850_xml_tcp_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a150f4597ef01f35ed7efd6676478ce28f0f2196 --- /dev/null +++ b/pool/shard001/Python/0013850_xml_tcp_client.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# Copyright (c) Twisted Matrix Laboratories. +# See LICENSE for details. +import sys + +from twisted.internet import task +from twisted.internet.defer import Deferred +from twisted.internet.protocol import ClientFactory +from twisted.protocols.basic import LineReceiver + +BILLION_LAUGHS = None + +class EchoClient(LineReceiver): + delimiter = '\0' + + def connectionMade(self): + self.sendLine(BILLION_LAUGHS) + + + def lineReceived(self, line): + print("receive:", line) + self.transport.loseConnection() + + + +class EchoClientFactory(ClientFactory): + protocol = EchoClient + + def __init__(self): + self.done = Deferred() + + + def clientConnectionFailed(self, connector, reason): + print('connection failed:', reason.getErrorMessage()) + self.done.errback(reason) + + + def clientConnectionLost(self, connector, reason): + print('connection lost:', reason.getErrorMessage()) + self.done.callback(None) + + + +def main(reactor): + global BILLION_LAUGHS + BILLION_LAUGHS = open(sys.argv[1]).read() + factory = EchoClientFactory() + reactor.connectTCP('localhost', 8000, factory) + return factory.done + + + +if __name__ == '__main__': + task.react(main) diff --git a/pool/shard001/Python/0013852_registerable.py b/pool/shard001/Python/0013852_registerable.py new file mode 100644 index 0000000000000000000000000000000000000000..43e5f10d6f0ed36c461ca3f759c13ff0bbc66dad --- /dev/null +++ b/pool/shard001/Python/0013852_registerable.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from flask import current_app +from .confirmable import generate_confirmation_token_and_link +from .confirmable import system_requires_confirmation +from .models import User +from .signals import user_registered + +from oldhawaii_metadata.mail import send_mail + + +def register_user(**kwargs): + kwargs.pop('password_confirm', None) + user = User.create(**kwargs) + + signal_context = {'user': user} + mail_context = {'user': user} + + if system_requires_confirmation(): + confirmation_token, confirmation_link = \ + generate_confirmation_token_and_link(user) + signal_context['confirmation_token'] = confirmation_token + mail_context['confirmation_link'] = confirmation_link + + user_registered.send( + current_app._get_current_object(), + **signal_context) + + send_mail( + 'Thank you for registering!', + current_app.config['MAIL_DEFAULT_SENDER'], + user.email, + plain_template_path='users/emails/welcome.txt.html', + html_template_path='users/emails/welcome.html', + **mail_context) + + return user + +# vim: filetype=python diff --git a/pool/shard001/Python/0013853_db_handlers.py b/pool/shard001/Python/0013853_db_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..edc0a986403f5f295879c31b845720698017b77e --- /dev/null +++ b/pool/shard001/Python/0013853_db_handlers.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +from db.db_update import * +from google.appengine.api import users +import datetime +import logging +import webapp2 +from constants import admin_users + + +''' +class InsertNBAGames(webapp2.RequestHandler): + def get(self): + user = users.get_current_user() + if user: + if users.is_current_user_admin(): + self.response.write('You are an administrator.') + insert_nba_games(datetime.date(2016,10,29)) + #insert_nba_games(datetime.date.today()) + logging.info("Inserting NBA games.") + else: + self.response.write('You are not an administrator.') + else: + self.response.write('You are not logged in.') +''' + +class InsertNBAGames(webapp2.RequestHandler): + def get(self): + user_id = self.request.get('user_id', default_value = None) + if user_id: + if user_id in admin_users: + self.response.write('You are an administrator. Inserting NBA games') + insert_nba_games(datetime.date(2016,10,29)) + logging.info("Inserted NBA games.") + else: + self.response.write('You are not an administrator.') + else: + self.response.write('You are not logged in.') + +class InsertNFLGames(webapp2.RequestHandler): + def get(self): + user_id = self.request.get('user_id', default_value = None) + if user_id: + if user_id in admin_users: + self.response.write('You are an administrator. Inserting NFL games.') + insert_nfl_games() + else: + self.response.write('You are not an administrator.') + else: + self.response.write('You are not logged in.') + + +''' +class InsertNFLGames(webapp2.RequestHandler): + def get(self): + user = users.get_current_user() + if user: + if users.is_current_user_admin(): + self.response.write('You are an administrator. Inserting NFL games.') + insert_nfl_games() + else: + self.response.write('You are not an administrator.') + else: + self.response.write('You are not logged in.') +''' + + +class UpdateNBAGames(webapp2.RequestHandler): + def get(self): + date = datetime.date.today() - datetime.timedelta(days=1) + #logging.info("HELLO") + #logging.info(date) + #curr_date = datetime.date(2016,10,29) + update_nba_games(date) + logging.info("Updating NBA games for {}.".format(date)) + +class UpdateAllNBAGames(webapp2.RequestHandler): + def get(self): + start_date = datetime.date(2016,11,03) + curr_date = start_date + end_date = datetime.date.today() - datetime.timedelta(days=1) + while curr_date <= end_date: + update_nba_games(curr_date) + curr_date = curr_date + datetime.timedelta(days=1) + logging.info("Updating NBA games from {} to {}.".format(start_date, end_date)) + +class UpdateNFLGames(webapp2.RequestHandler): + def get(self): + date = datetime.date.today() - datetime.timedelta(days=1) + update_nfl_games(date) + logging.info("Updating NFL games for {}".format(date)) + +class UpdateAllNFLGames(webapp2.RequestHandler): + def get(self): + date = datetime.date.today() - datetime.timedelta(days=1) + update_all_nfl_games(date) + logging.info("Updating all NFL games up to {}".format(date)) + +class RecalculateGoatIndex(webapp2.RequestHandler): + def get(self): + recalculate_goat_index("nba") + recalculate_goat_index("nfl") + update_goat_index_rankings("nba") + update_goat_index_rankings("nfl") + +class UpdateNBATeamRecords(webapp2.RequestHandler): + def get(self): + update_nba_team_records() + logging.info("Updating NBA team records.") + +class UpdateNFLTeamRecords(webapp2.RequestHandler): + def get(self): + update_nfl_team_records() + logging.info("Updating NFL team records.") + +class TempUpdateOptionSport(webapp2.RequestHandler): + def get(self): + update_option_sport_attrib() + \ No newline at end of file diff --git a/pool/shard001/Python/0013858_sankantsu.py b/pool/shard001/Python/0013858_sankantsu.py new file mode 100644 index 0000000000000000000000000000000000000000..716997f979bde26a472fce65f4d323b24ffae587 --- /dev/null +++ b/pool/shard001/Python/0013858_sankantsu.py @@ -0,0 +1,25 @@ +from mahjong.hand_calculating.yaku import Yaku +from mahjong.meld import Meld + + +class SanKantsu(Yaku): + """ + The hand with three kan sets + """ + + def __init__(self, yaku_id=None): + super(SanKantsu, self).__init__(yaku_id) + + def set_attributes(self): + self.tenhou_id = 27 + + self.name = "San Kantsu" + + self.han_open = 2 + self.han_closed = 2 + + self.is_yakuman = False + + def is_condition_met(self, hand, melds, *args): + kan_sets = [x for x in melds if x.type == Meld.KAN or x.type == Meld.SHOUMINKAN] + return len(kan_sets) == 3 diff --git a/pool/shard001/Python/0013859_models.py b/pool/shard001/Python/0013859_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c4d8b37ada098b383bda1b15bee029a4071cf227 --- /dev/null +++ b/pool/shard001/Python/0013859_models.py @@ -0,0 +1,100 @@ +from django.db import models +from django.contrib import admin +from django import forms +import requests + + +# Create your models here. +from config.settings.common import env + + +class Solution(models.Model): + hash = models.CharField(max_length=32) + + def __str__(self): + return str(self.hash) + +class Challenge(models.Model): + """ + The Challenge model is a collection of data for each challenge the user can complete. + Challenges are simple CTF-esque problems where a user has to find a text string and evaluate it against the + stored result. + """ + + # This section defines the different categories of problems + FORENSICS = 'FR' + CRYPTOGRAPHY = 'CR' + LINUX = 'LX' + ALGORITHMS = 'AL' + WEB = 'WB' + REVERSE_ENGINEERING = 'RE' + PWNING = 'PW' + PROCOM = 'PC' + + CHALLENGE_CATEGORIES = ( + (FORENSICS, "Forensics"), + (CRYPTOGRAPHY, "Cryptography"), + (LINUX, "Linux"), + (ALGORITHMS, "Algorithms"), + (WEB, "Web"), + (REVERSE_ENGINEERING, "Reverse Engineering"), + (PWNING, "Pwning"), + (PROCOM, "ProCom") + ) + + name = models.CharField(max_length=100) + description = models.CharField(max_length=10000) + attachments = models.FileField(blank=True, null=True) + points = models.IntegerField() + category = models.CharField( + max_length=2, + choices=CHALLENGE_CATEGORIES + ) + key_hashes = models.ManyToManyField(Solution) + solves = models.IntegerField(default=0) + lesson = models.BooleanField(default=False) + will = models.BooleanField(default=False) + prereq = models.ManyToManyField('self', blank=True) + + def __str__(self): + return (str(self.name)) + +def post_save_challenge(sender, instance, created, *args, **kwargs): + if created: + from requests.auth import HTTPBasicAuth + r = requests.post( + url='https://discordapp.com/api/channels/227554629741707274/messages', + headers={ + 'Authorization': 'Bot ' + env('DISCORD_TOKEN'), + 'User-Agent': 'ctf-bot (http://ctf.tips.club, v0.1)' + }, + data={ + 'content': "<@&228329733434114048> **New Problem:** {name}\nPoints: {points}\nCategory: {cat}"\ + .format(name=instance.name, points=instance.points, cat=instance.category) + } + ) + print(r.text) + print(env('DISCORD_TOKEN')) + +models.signals.post_save.connect(post_save_challenge, sender=Challenge) + +class ChallengeAdmin(admin.ModelAdmin): + + def formfield_for_dbfield(self, db_field, **kwargs): + formfield = super(ChallengeAdmin, self).formfield_for_dbfield(db_field, **kwargs) + if db_field.name == 'description': + formfield.widget = forms.Textarea(attrs=formfield.widget.attrs) + return formfield + + filter_horizontal = ['key_hashes',] + + class Meta(): + fields = '__all__' + +class Score(models.Model): + value = models.IntegerField(default=0) + category = models.CharField( + max_length=2, + choices=Challenge.CHALLENGE_CATEGORIES + ) + diff --git a/pool/shard001/Python/0013860_bundle.py b/pool/shard001/Python/0013860_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..13b88e09081fcea134f785053ea316501c7ffc18 --- /dev/null +++ b/pool/shard001/Python/0013860_bundle.py @@ -0,0 +1,84 @@ +#----------------------------------------------------------------------------- +# Copyright (C) PyZMQ Developers +# Distributed under the terms of the Modified BSD License. +# +# This bundling code is largely adapted from pyzmq-static's get.sh by +# Brandon Craig-Rhodes, which is itself BSD licensed. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# This bundling code is largely adapted from pyzmq's code +# PyZMQ Developers, which is itself Modified BSD licensed. +#----------------------------------------------------------------------------- + +import os +import shutil +import stat +import sys +import tarfile +from glob import glob +from subprocess import Popen, PIPE + +try: + # py2 + from urllib2 import urlopen +except ImportError: + # py3 + from urllib.request import urlopen + +from . import log + + +#----------------------------------------------------------------------------- +# Constants +#----------------------------------------------------------------------------- +min_qpid_proton = (0, 10) +min_qpid_proton_str = "%i.%i" % min_qpid_proton + +bundled_version = (0, 10, 0) +bundled_version_str = "%i.%i.%i" % bundled_version +libqpid_proton = "qpid-proton-%s.tar.gz" % bundled_version_str +libqpid_proton_url = ("http://www.apache.org/dist/qpid/proton/%s/%s" % + (bundled_version_str, libqpid_proton)) + +HERE = os.path.dirname(__file__) +ROOT = os.path.dirname(HERE) + + +def fetch_archive(savedir, url, fname): + """Download an archive to a specific location + + :param savedir: Destination dir + :param url: URL where the archive should be downloaded from + :param fname: Archive's filename + """ + dest = os.path.join(savedir, fname) + + if os.path.exists(dest): + log.info("already have %s" % fname) + return dest + + log.info("fetching %s into %s" % (url, savedir)) + if not os.path.exists(savedir): + os.makedirs(savedir) + req = urlopen(url) + with open(dest, 'wb') as f: + f.write(req.read()) + return dest + + +def fetch_libqpid_proton(savedir): + """Download qpid-proton to `savedir`.""" + dest = os.path.join(savedir, 'qpid-proton') + if os.path.exists(dest): + log.info("already have %s" % dest) + return + fname = fetch_archive(savedir, libqpid_proton_url, libqpid_proton) + tf = tarfile.open(fname) + member = tf.firstmember.path + if member == '.': + member = tf.getmembers()[1].path + with_version = os.path.join(savedir, member) + tf.extractall(savedir) + tf.close() + shutil.move(with_version, dest) diff --git a/pool/shard001/Python/0013865_files.py b/pool/shard001/Python/0013865_files.py new file mode 100644 index 0000000000000000000000000000000000000000..681a825a3f5664aacf0698db5fa4111883c4cfc4 --- /dev/null +++ b/pool/shard001/Python/0013865_files.py @@ -0,0 +1,156 @@ +import json +from datetime import timedelta + +from tornado import gen +from tornado.httpclient import AsyncHTTPClient, HTTPRequest +from tornado.log import app_log +from tornado.locks import BoundedSemaphore, Condition +from tornado.queues import Queue +from vizydrop.sdk.source import StreamingDataSource, SourceSchema, SourceFilter +from vizydrop.fields import * + + +# what file extensions are we interested in +VALID_FILETYPES = ['txt', 'tsv', 'csv', 'dat', 'xls', 'xlsx'] +# how many concurrent fetches can we do? +FETCH_CONCURRENCY = 10 +# our maximum request time (in seconds) +MAXIMUM_REQ_TIME = 30 + + +class OneDriveFileFilter(SourceFilter): + def get_file_list(account, **kwargs): + queue = Queue() + sem = BoundedSemaphore(FETCH_CONCURRENCY) + done, working = set(), set() + data = [] + ids = set() + + @gen.coroutine + def fetch_url(): + current_url = yield queue.get() + try: + if current_url in working: + return + page_no = working.__len__() + app_log.info("Fetching page {}".format(page_no)) + working.add(current_url) + req = account.get_request(current_url) + client = AsyncHTTPClient() + response = yield client.fetch(req) + done.add(current_url) + app_log.info("Page {} downloaded".format(page_no)) + response_data = json.loads(response.body.decode('utf-8')) + + url = response_data.get('@odata.nextLink', None) + if url is not None: + queue.put(url) + + for file in response_data.get('value', []): + if file['name'][-4:].strip('.').lower() in VALID_FILETYPES: + if file['id'] not in ids: + ids.add(file['id']) + data.append( + {"title": file['parentReference']['path'].split(':')[1].lstrip('/') + '/' + file['name'], + "value": file['id']}) + app_log.info("Page {} completed".format(page_no)) + finally: + queue.task_done() + sem.release() + + @gen.coroutine + def worker(): + while True: + yield sem.acquire() + fetch_url() + + app_log.info("Gathering filelist for account {}".format(account._id)) + for file_type in VALID_FILETYPES: + file_type = '.'.join([file_type]) + url = "https://api.onedrive.com/v1.0/drive/root/view.search?top=1000&select=parentReference,name,id,size&q={}" \ + .format(file_type) + queue.put(url) + # start our concurrency worker + worker() + # wait until we're done + yield queue.join(timeout=timedelta(seconds=MAXIMUM_REQ_TIME)) + app_log.info("Finished list retrieval. Found {} items.".format(data.__len__())) + return sorted(data, key=lambda f: f['title']) + + file = TextField(name="Filename", description="Path to the file", optional=False, get_options=get_file_list) + + +class OneDriveFileSource(StreamingDataSource): + class Meta: + identifier = "file" + name = "File" + tags = ["File", ] + description = "Contents from a Datafile" + filter = OneDriveFileFilter + + class Schema(SourceSchema): + pass + + @classmethod + @gen.coroutine + def get_data(cls, account, source_filter, limit=100, skip=0): + source_filter = OneDriveFileFilter(source_filter) + + if source_filter.file is None: + raise ValueError('required parameter file missing') + + app_log.info("Starting to retrieve file for {}".format(account._id)) + + client = AsyncHTTPClient() + uri = "https://api.onedrive.com/v1.0/drive/items/{}/content".format(source_filter.file) + lock = Condition() + + def crawl_url(url): + # some yummy regex + location_header_regex = re.compile(r'^Location:\s?(?Phttp:/{2}\S+)') + http_status_regex = re.compile(r'^HTTP/[\d\.]+\s(?P\d+)') + receiving_file = False + + # define our callbacks + def header_callback(header): + m = http_status_regex.match(header) + if m is not None: + # process our HTTP status header + status = m.group('status') + if int(status) == 200: + # if we're 200, we're receiving the file, not just a redirect + app_log.info("Receiving file {} for account {}".format(source_filter.file, account._id)) + global receiving_file + receiving_file = True + m = location_header_regex.match(header) + if m is not None: + # process our location header + uri = m.group('uri') + # and grab _that_ url + app_log.info("Following redirect for file {}".format(source_filter.file)) + crawl_url(uri) + + def stream_callback(chunk): + # only dump out chunks that are of the file we're looking for + global receiving_file + if receiving_file: + app_log.info("Writing chunk of {}B".format(chunk.__len__())) + cls.write(chunk) + + def on_completed(resp): + if 200 <= resp.code <= 299: + lock.notify() + + oauth_client = account.get_client() + uri, headers, body = oauth_client.add_token(url) + req = HTTPRequest(uri, headers=headers, body=body, header_callback=header_callback, + streaming_callback=stream_callback) + client.fetch(req, callback=on_completed) + + crawl_url(uri) + # wait for us to complete + try: + yield lock.wait(timeout=timedelta(seconds=MAXIMUM_REQ_TIME)) + app_log.info("File {} retrieved successfully".format(source_filter.file)) + except gen.TimeoutError: + app_log.error("Request for file {} => {} timed out!".format(source_filter.file, account._id)) \ No newline at end of file diff --git a/pool/shard001/Python/0013870_views.py b/pool/shard001/Python/0013870_views.py new file mode 100644 index 0000000000000000000000000000000000000000..661d6a0129586e242ffcd5670773c9c7e18ea59a --- /dev/null +++ b/pool/shard001/Python/0013870_views.py @@ -0,0 +1,48 @@ +from django.views.generic.edit import FormView +from django.views.generic import View + +from apps.chat.models import Chats +from apps.chat.utils import ChatPage +from django.http import HttpResponsePermanentRedirect +from apps.home.forms import JoinChatForm + +import logging +logger = logging.getLogger(__name__) + + +class HomeView(FormView): + template_name = 'home.html' + form_class = JoinChatForm + + def form_valid(self, form): + """ + This method is called when valid form data has been POSTed. + :param form: JoinChatForm + :return: HttpResponse + """ + # join to chat run during validation process + chat_token = self.request.POST.get('chat_token') + self.success_url = '/chat/' + str(chat_token) + + chat_page = ChatPage(self.request) + chat_page.set_user_token(form.user_token) + # logger.info('User joined to chat: ' + str(chat_token)) + logger.info('User joined to chat: ' + chat_token) + return super(HomeView, self).form_valid(form) + + +class CreateView(View): + def post(self, request, *args, **kwargs): + """ + Create chat + :param request: + :param args: + :param kwargs: + :return: HttpResponsePermanentRedirect + """ + tokens = Chats.create_chat() + chat_page = ChatPage(self.request) + chat_page.set_user_token(tokens['user_token']) + success_url = '/chat/' + tokens['chat_token'] + logger.info('Chat created: ' + tokens['chat_token']) + return HttpResponsePermanentRedirect(success_url) diff --git a/pool/shard001/Python/0013874_get_trusted_certs.py b/pool/shard001/Python/0013874_get_trusted_certs.py new file mode 100644 index 0000000000000000000000000000000000000000..acb86051a5b9d788d4ef9a5afada017d9128b83a --- /dev/null +++ b/pool/shard001/Python/0013874_get_trusted_certs.py @@ -0,0 +1,40 @@ +from foam.sfa.util.method import Method + +from foam.sfa.trust.auth import Auth +from foam.sfa.trust.credential import Credential + +from foam.sfa.util.parameter import Parameter, Mixed + +class get_trusted_certs(Method): + """ + @param cred credential string specifying the rights of the caller + @return list of gid strings + """ + + interfaces = ['registry', 'aggregate', 'slicemgr'] + + accepts = [ + Mixed(Parameter(str, "Credential string"), + Parameter(None, "Credential not specified")) + ] + + returns = Parameter(type([str]), "List of GID strings") + + def call(self, cred = None): + # If cred is not specified just return the gid for this interface. + # This is true when when a peer is attempting to initiate federation + # with this interface + self.api.logger.debug("get_trusted_certs: %r"%cred) + if not cred: + gid_strings = [] + for gid in self.api.auth.trusted_cert_list: + if gid.get_hrn() == self.api.config.SFA_INTERFACE_HRN: + gid_strings.append(gid.save_to_string(save_parents=True)) + return gid_strings + + # authenticate the cred + self.api.auth.check(cred, 'gettrustedcerts') + gid_strings = [gid.save_to_string(save_parents=True) for \ + gid in self.api.auth.trusted_cert_list] + + return gid_strings diff --git a/pool/shard001/Python/0013878_add_from.py b/pool/shard001/Python/0013878_add_from.py new file mode 100644 index 0000000000000000000000000000000000000000..1e662e73732d3f872af5376564aad9b3f160cfcc --- /dev/null +++ b/pool/shard001/Python/0013878_add_from.py @@ -0,0 +1,118 @@ +# Copyright 2004-2010 PyTom +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +#!/usr/bin/env python + +# This program adds froms to every unqualified call found in the game +# directory. It's not perfect, but it's better than nothing. + +import os +import re + +def find_labels(fn, labels): + + f = file(fn, "r") + + for l in f: + + m = re.match(r'^\s*call\s+\w+\s+from\s+(\w+)\s*$', l) + if m: + labels[m.group(1)] = True + + m = re.match(r'^\s*call\s+expression.*from\s+(\w+)\s*$', l) + if m: + labels[m.group(1)] = True + + f.close() + +def replace_labels(fn, labels): + + f = file(fn, "r") + of = file(fn + ".new", "w") + + + def replaceit(m): + target = m.group(2) + + num = 0 + + while True: + num += 1 + label = "_call_%s_%d" % (target, num) + + if label not in labels: + break + + labels[label] = True + + return m.group(1) + "call " + target + " from " + label + m.group(3) + + for l in f: + l = re.sub(r'^(\s*)call\s+(\w+)(\s*$)', replaceit, l) + + if re.search(r'call\s+expression', l) and not re.search('from', l): + + num = 0 + + while True: + num += 1 + label = "_call_expression_%d" % num + + if label not in labels: + break + + labels[label] = label + + l = l[:-1] + " from " + label + "\n" + + of.write(l) + + f.close() + of.close() + + + try: + os.unlink(fn + ".bak") + except: + pass + + os.rename(fn, fn + ".bak") + os.rename(fn + ".new", fn) + +def add_from(gamedir, commondir): + + labels = { } + + game_files = [ gamedir + "/" + i for i in os.listdir(gamedir) if i.endswith(".rpy") ] + + if commondir: + common_files = [ commondir + "/" + i for i in os.listdir(commondir) if i.endswith(".rpy") ] + else: + common_files = [ ] + + for fn in game_files + common_files: + print "Finding labels in", fn + find_labels(fn, labels) + + for fn in game_files: + print "Replacing labels in", fn + replace_labels(fn, labels) + diff --git a/pool/shard001/Python/0013881_ReverseWords.py b/pool/shard001/Python/0013881_ReverseWords.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ffb9417759affbe28bddb341b4f40491b730f5 --- /dev/null +++ b/pool/shard001/Python/0013881_ReverseWords.py @@ -0,0 +1,11 @@ +# File Handling +with open('Inputs/B-large-practice.in', 'r') as f_reader: + with open('Outputs/B-large-practice.out' ,'w') as f_writer: + + # Number of test cases + test_cases = int(f_reader.readline()) + i = 1 + while i <= test_cases: + fline = f_reader.readline().strip() + f_writer.write("Case #%d: %s\n" % (i, ' '.join(fline.split(' ')[::-1]))) + i = i + 1 \ No newline at end of file diff --git a/pool/shard001/Python/0013884_provider.py b/pool/shard001/Python/0013884_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6ffce85532357425985013515acc7b2d89f598 --- /dev/null +++ b/pool/shard001/Python/0013884_provider.py @@ -0,0 +1,66 @@ +# Copyright FuseSoC contributors +# Licensed under the 2-Clause BSD License, see LICENSE for details. +# SPDX-License-Identifier: BSD-2-Clause + +import logging +import os +import shutil + +from fusesoc.utils import Launcher + +logger = logging.getLogger(__name__) + + +class Provider: + def __init__(self, config, core_root, files_root): + self.config = config + self.core_root = core_root + self.files_root = files_root + self.cachable = not (config.get("cachable", "") == False) + self.patches = config.get("patches", []) + + def clean_cache(self): + if os.path.exists(self.files_root): + shutil.rmtree(self.files_root) + + def fetch(self): + status = self.status() + if status == "empty": + self._checkout(self.files_root) + _fetched = True + elif status == "outofdate": + self.clean_cache() + self._checkout(self.files_root) + _fetched = True + elif status == "downloaded": + _fetched = False + else: + raise RuntimeError( + "Provider status is: '" + status + "'. This shouldn't happen" + ) + if _fetched: + self._patch() + + def _patch(self): + for f in self.patches: + patch_file = os.path.abspath(os.path.join(self.core_root, f)) + if os.path.isfile(patch_file): + logger.debug( + " applying patch file: " + + patch_file + + "\n" + + " to: " + + os.path.join(self.files_root) + ) + try: + Launcher("git", ["apply", patch_file], self.files_root).run() + except OSError: + raise RuntimeError("Failed to call 'git' for patching core") + + def status(self): + if not self.cachable: + return "outofdate" + if not os.path.isdir(self.files_root): + return "empty" + else: + return "downloaded" diff --git a/pool/shard001/Python/0013888_config.py b/pool/shard001/Python/0013888_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1ed46d1c472515e1ddb8f5d845877a962b52bc --- /dev/null +++ b/pool/shard001/Python/0013888_config.py @@ -0,0 +1,70 @@ +# +# 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 oslo_config import cfg +from oslo_db import options as db_options +from oslo_log import log +from oslo_policy import opts as policy_opts +from osprofiler import initializer as osprofiler_initializer +from osprofiler import opts as osprofiler_opts +from vitrage import keystone_client +from vitrage import messaging +from vitrage import opts + + +CONF = cfg.CONF +LOG = log.getLogger(__name__) + + +def parse_config(args, default_config_files=None): + set_defaults() + log.register_options(CONF) + policy_opts.set_defaults(CONF) + osprofiler_opts.set_defaults(CONF) + db_options.set_defaults(CONF) + + for group, options in opts.list_opts(): + CONF.register_opts(list(options), + group=None if group == 'DEFAULT' else group) + + CONF(args[1:], project='vitrage', validate_default_values=True, + default_config_files=default_config_files) + + if CONF.profiler.enabled: + osprofiler_initializer.init_from_conf( + conf=CONF, + context=None, + project='vitrage', + service='api', + host=CONF.api.host + ) + + for datasource in CONF.datasources.types: + opts.register_opts(datasource, CONF.datasources.path) + + keystone_client.register_keystoneauth_opts() + log.setup(CONF, 'vitrage') + CONF.log_opt_values(LOG, log.DEBUG) + messaging.setup() + + +def set_defaults(): + from oslo_middleware import cors + cfg.set_defaults(cors.CORS_OPTS, + allow_headers=[ + 'Authorization', + 'X-Auth-Token', + 'X-Subject-Token', + 'X-User-Id', + 'X-Domain-Id', + 'X-Project-Id', + 'X-Roles']) diff --git a/pool/shard001/Python/0013890_ocr.py b/pool/shard001/Python/0013890_ocr.py new file mode 100644 index 0000000000000000000000000000000000000000..a71c8b57c6e8a47c2d39abfc01f08475d33e1e7e --- /dev/null +++ b/pool/shard001/Python/0013890_ocr.py @@ -0,0 +1,35 @@ +import shlex +import string +import logging +import re + +import pytesseract +from PIL import ImageOps, ImageFilter, ImageEnhance + +from odoo import models + +logger = logging.getLogger(__name__) + + +class OCR(models.AbstractModel): + _name = "ocr" + _description = "Optical character recognition with Tesseract" + + _languages_tesseract = ["eng", "fra", "deu", "ita", "spa"] + _accents = "çäïüëöâîûêôáíúéóàìùèò" + _punctuation = " .,!?-()" + _char_whitelist = shlex.quote(string.ascii_letters + string.digits + _punctuation + _accents + _accents.upper()) + _config = rf"-c tessedit_char_whitelist={_char_whitelist} -l {'+'.join(_languages_tesseract)} --dpi 300" + + def image_to_string(self, image): + # use greyscale, cause some letters use color pencils + image = ImageOps.grayscale(image) + + image = ImageEnhance.Contrast(image).enhance(1.5) + + logger.debug(self._config) + text = pytesseract.image_to_string(image, config=self._config) + # remove every invisible character (line breaks, etc..) by spaces + text = re.sub(r"\s+", " ", text) + logger.debug(text) + return text, image diff --git a/pool/shard001/Python/0013891_netcdf.py b/pool/shard001/Python/0013891_netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..41a1af12379fa6eb209bb3ac348f3bdaebd94237 --- /dev/null +++ b/pool/shard001/Python/0013891_netcdf.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io` namespace for importing the functions +# included below. + +import warnings +from . import _netcdf + +__all__ = [ # noqa: F822 + 'netcdf_file', 'netcdf_variable' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name not in __all__: + raise AttributeError( + "scipy.io.netcdf is deprecated and has no attribute " + f"{name}. Try looking in scipy.io instead.") + + warnings.warn(f"Please use `{name}` from the `scipy.io` namespace, " + "the `scipy.io.netcdf` namespace is deprecated.", + category=DeprecationWarning, stacklevel=2) + + return getattr(_netcdf, name) diff --git a/pool/shard001/Python/0013899_test_datasets_update_with_calcs.py b/pool/shard001/Python/0013899_test_datasets_update_with_calcs.py new file mode 100644 index 0000000000000000000000000000000000000000..5450e26943700dfe89974df619cc26c515c1e4b7 --- /dev/null +++ b/pool/shard001/Python/0013899_test_datasets_update_with_calcs.py @@ -0,0 +1,75 @@ +import simplejson as json + +from bamboo.models.dataset import Dataset +from bamboo.tests.controllers.test_abstract_datasets_update import\ + TestAbstractDatasetsUpdate + + +class TestDatasetsUpdateWithCalcs(TestAbstractDatasetsUpdate): + + def setUp(self): + TestAbstractDatasetsUpdate.setUp(self) + self._create_original_datasets() + self._add_common_calculations() + + # create linked datasets + self.calculations.create( + self.dataset2_id, 'sum(amount)', 'sum of amount') + result = json.loads( + self.controller.aggregations(self.dataset2_id)) + self.linked_dataset1_id = result[''] + + # create merged datasets + result = json.loads(self.controller.merge(dataset_ids=json.dumps( + [self.dataset1_id, self.dataset2_id]))) + self.merged_dataset1_id = result[Dataset.ID] + + result = json.loads(self.controller.merge(dataset_ids=json.dumps( + [self.merged_dataset1_id, self.linked_dataset1_id]))) + self.merged_dataset2_id = result[Dataset.ID] + + def test_setup_datasets(self): + self._verify_dataset( + self.dataset1_id, + 'updates_with_calcs/originals/dataset1.pkl') + self._verify_dataset( + self.dataset2_id, + 'updates_with_calcs/originals/dataset2.pkl') + self._verify_dataset( + self.linked_dataset1_id, + 'updates_with_calcs/originals/linked_dataset1.pkl') + self._verify_dataset( + self.merged_dataset1_id, + 'updates_with_calcs/originals/merged_dataset1.pkl') + self._verify_dataset( + self.merged_dataset2_id, + 'updates_with_calcs/originals/merged_dataset2.pkl') + + def _add_calculations(self): + self.calculations.create(self.dataset2_id, + 'amount_plus_gps_alt > gps_precision', + 'amount plus gps_alt > gps_precision') + self.calculations.create(self.linked_dataset1_id, + 'sum_of_amount * 2', + 'amount') + self.calculations.create(self.merged_dataset1_id, + 'gps_alt * 2', + 'double gps_alt') + self.calculations.create(self.merged_dataset2_id, + 'amount * 2', + 'double amount') + self._verify_dataset( + self.dataset2_id, + 'updates_with_calcs/calcs/dataset2.pkl') + self._verify_dataset( + self.linked_dataset1_id, + 'updates_with_calcs/calcs/linked_dataset1.pkl') + self._verify_dataset( + self.merged_dataset1_id, + 'updates_with_calcs/calcs/merged_dataset1.pkl') + self._verify_dataset( + self.merged_dataset2_id, + 'updates_with_calcs/calcs/merged_dataset2.pkl') + + def test_datasets_add_calculations(self): + self._add_calculations() diff --git a/pool/shard001/Python/0013905_layout.py b/pool/shard001/Python/0013905_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..330ebb3a3a49e820de29ba3385ac90284c1c9727 --- /dev/null +++ b/pool/shard001/Python/0013905_layout.py @@ -0,0 +1,173 @@ +""" +Layout + +These functions allow for easy creation +and modifications of layouts. + +* author: William Emfinger +* website: github.com/finger563/editor +* last edited: August 2015 +""" + +from PyQt4 import QtCore, QtGui + +from anchors import convertAnchorToQt, closestAnchors + +class AnchorLayout(QtGui.QGraphicsAnchorLayout): + + min_anchoring_dist = 20 + edge_padding = 10 + item_spacing = 10 + + def __init__(self, parent): + super(AnchorLayout, self).__init__(parent) + self.setSpacing(self.item_spacing) + + def sizeHint(self, which, constraint): + geo = self.geometry() + return QtCore.QSizeF(geo.width(), geo.height) + + def updateGeometry(self): + super(AnchorLayout,self).updateGeometry() + + def getClosestAnchors(self, newItem): + minDist = -1 + anchor1 = None + anchor2 = None + closestItem = None + if newItem: + for i in range(self.count()): + item = self.itemAt(i) + if item != newItem: + dist, a1, a2 = closestAnchors(item,newItem) + if minDist == -1 or dist < minDist: + minDist = dist + anchor1, anchor2 = a1, a2 + closestItem = item + return abs(minDist), anchor1, anchor2, closestItem + + def addItem(self, item): + self.removeItem(item) + if self.count(): + d, a1_str, a2_str, ci = self.getClosestAnchors(item) + a1 = convertAnchorToQt(a1_str) + a2 = convertAnchorToQt(a2_str) + if d > 0 and d < self.min_anchoring_dist: + item.viewModel()['layout config'].value['anchor'] = (a2_str, ci, a1_str) + if isinstance(a1,QtCore.Qt.Corner) and isinstance(a2,QtCore.Qt.Corner): + self.addCornerAnchors(item, a2, + ci, a1) + elif isinstance(a1, QtCore.Qt.AnchorPoint) and isinstance(a2, QtCore.Qt.AnchorPoint): + self.addAnchor(item, a2, + ci, a1) + else: + item.viewModel()['layout config'].value['anchor'] = (a2_str, self, a1_str) + self.addCornerAnchors(item, convertAnchorToQt('top left'), + self, convertAnchorToQt('top left')) + + def updateItem(self, item): + self.removeItem(item) + self.addItem(item) + + def removeItem(self, item): + for i in range(self.count()): + if item == self.itemAt(i): + self.removeAt(i) + break + + def fromLayout(self, otherLayout): + if not otherLayout: + return + for i in range(otherLayout.count()): + item = otherLayout.itemAt(0) + otherLayout.removeAt(0) + self.addItem(item) + +class HorizontalLayout(QtGui.QGraphicsLinearLayout): + def __init__(self): + super(HorizontalLayout, self).__init__() + + def fromLayout(self, otherLayout): + if not otherLayout: + return + for i in range(otherLayout.count()): + item = otherLayout.itemAt(0) + otherLayout.removeAt(0) + self.addItem(item) + + def updateItem(self, item): + item.setPos(item._original_pos) + +class VerticalLayout(QtGui.QGraphicsLinearLayout): + def __init__(self): + super(VerticalLayout, self).__init__(QtCore.Qt.Vertical) + + def fromLayout(self, otherLayout): + if not otherLayout: + return + for i in range(otherLayout.count()): + item = otherLayout.itemAt(0) + otherLayout.removeAt(0) + self.addItem(item) + + def updateItem(self, item): + item.setPos(item._original_pos) + +class GridLayout(QtGui.QGraphicsGridLayout): + def __init__(self): + super(GridLayout,self).__init__() + + def fromLayout(self, otherLayout): + if not otherLayout: + return + for i in range(otherLayout.count()): + item = otherLayout.itemAt(0) + otherLayout.removeAt(0) + self.addItem(item) + + def addItem(self,item): + self.removeItem(item) + if 'grid' not in item.viewModel()['layout config'].value: + name = item['Name'] + gr, ok = QtGui.QInputDialog.getInteger(None, + "Item '{}' Row".format(name), + "Row:", 0, 0) + if not ok: gr = -1 + gc, ok = QtGui.QInputDialog.getInteger(None, + "Item '{}' Column".format(name), + "Column:", 0, 0) + if not ok: gc = -1 + else: + gr,gc = item.viewModel()['layout config'].value['grid'] + if gc >= 0 and gr >= 0: + super(GridLayout,self).addItem(item, gr, gc) + item.viewModel()['layout config'].value['grid'] = (gr, gc) + else: + if item._original_pos: + item.setPos(item._original_pos) + else: + item.delete(None) + + def updateItem(self, item): + self.removeItem(item) + self.addItem(item) + + def removeItem(self, item): + for i in range(self.count()): + if item == self.itemAt(i): + self.removeAt(i) + break + +valid_layouts = [HorizontalLayout, VerticalLayout, GridLayout, AnchorLayout] + +def layout_create(style): + new_layout = HorizontalLayout() + if style in ['horizontal']: + new_layout = HorizontalLayout() + elif style in ['vertical']: + new_layout = VerticalLayout() + elif style in ['grid']: + new_layout = GridLayout() + elif style in ['anchor']: + new_layout = AnchorLayout() + return new_layout diff --git a/pool/shard001/Python/0013912_jan_pump_extraction_line_apis.py b/pool/shard001/Python/0013912_jan_pump_extraction_line_apis.py new file mode 100644 index 0000000000000000000000000000000000000000..7c37639f84e4529fd11b7a038e198083773ad458 --- /dev/null +++ b/pool/shard001/Python/0013912_jan_pump_extraction_line_apis.py @@ -0,0 +1,14 @@ +def main(): + info('Pump after analysis') + + #pump out bone + open('C') + + gosub('jan:PumpMicrobone') + + v=get_resource_value(name='JanMiniboneFlag') + + info('get resource value {}'.format(v)) + + if get_resource_value(name='JanMiniboneFlag'): + gosub('jan:PumpMinibone') diff --git a/pool/shard001/Python/0013915_expand_dims_layer.py b/pool/shard001/Python/0013915_expand_dims_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..574e8ca5129bf55a4e80c576220b6d96a17fd6e6 --- /dev/null +++ b/pool/shard001/Python/0013915_expand_dims_layer.py @@ -0,0 +1,77 @@ +# coding=utf-8 +# Copyright 2020 The TF-Agents Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Keras layer performing the equivalent of tf.expand_dims.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import + + +class ExpandDims(tf.keras.layers.Layer): + """Expands dims along a particular axis. + + Args: + axis: Axis to expand. A new dim is added before this axis. + May be a negative value. Must not be a tensor. + + Input shape: + `(batch_size,) + shape` + + Output shape: + `(batch_size,) + shape + [1]`, if `axis == -1`. + + `(batch_size,) + shape[:axis + 1] + [1] + shape[axis + 1:]`, + if `axis < -1`. + + `(batch_size,) + shape[:axis] + [1] + shape[axis:]`, if `axis >= 0`. + """ + + def __init__(self, axis, **kwargs): + super(ExpandDims, self).__init__(**kwargs) + self.axis = axis + + def compute_output_shape(self, input_shape): + input_shape = tf.TensorShape(input_shape) + if input_shape.rank is None: + return input_shape + input_shape = input_shape.as_list() + if self.axis == -1: + output_shape = input_shape + [1] + elif self.axis < 0: + output_shape = ( + input_shape[:self.axis + 1] + [1] + input_shape[self.axis + 1:]) + else: + output_shape = input_shape[:self.axis] + [1] + input_shape[self.axis:] + return tf.TensorShape(output_shape) + + def call(self, inputs): + if self.axis < 0: + # Negative axis, so expand starting from the right + return tf.expand_dims(inputs, self.axis) + else: + # Perform the expansion from the left, but skip the batch dimension. + return tf.expand_dims(inputs, self.axis + 1) + + def get_config(self): + config = {'axis': self.axis} + base_config = super(ExpandDims, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +# Register with Keras so we can do type(layer).from_config(layer.get_config()) +tf.keras.utils.get_custom_objects()['ExpandDims'] = ExpandDims diff --git a/pool/shard001/Python/0013923_rpm_key.py b/pool/shard001/Python/0013923_rpm_key.py new file mode 100644 index 0000000000000000000000000000000000000000..46ef34c24668f36cf8de840319ebfbdda9f5e4cc --- /dev/null +++ b/pool/shard001/Python/0013923_rpm_key.py @@ -0,0 +1,247 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Ansible module to import third party repo keys to your rpm db +# Copyright: (c) 2013, Héctor Acosta + +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +DOCUMENTATION = ''' +--- +module: rpm_key +author: + - Hector Acosta (@hacosta) +short_description: Adds or removes a gpg key from the rpm db +description: + - Adds or removes (rpm --import) a gpg key to your rpm database. +version_added: "1.3" +options: + key: + description: + - Key that will be modified. Can be a url, a file on the managed node, or a keyid if the key + already exists in the database. + type: str + required: true + state: + description: + - If the key will be imported or removed from the rpm db. + type: str + default: present + choices: [ absent, present ] + validate_certs: + description: + - If C(no) and the C(key) is a url starting with https, SSL certificates will not be validated. + - This should only be used on personally controlled sites using self-signed certificates. + type: bool + default: 'yes' + fingerprint: + description: + - The long-form fingerprint of the key being imported. + - This will be used to verify the specified key. + type: str + version_added: 2.9 +notes: + - Supports C(check_mode). +''' + +EXAMPLES = ''' +- name: Import a key from a url + ansible.builtin.rpm_key: + state: present + key: http://apt.sw.be/RPM-GPG-KEY.dag.txt + +- name: Import a key from a file + ansible.builtin.rpm_key: + state: present + key: /path/to/key.gpg + +- name: Ensure a key is not present in the db + ansible.builtin.rpm_key: + state: absent + key: DEADB33F + +- name: Verify the key, using a fingerprint, before import + ansible.builtin.rpm_key: + key: /path/to/RPM-GPG-KEY.dag.txt + fingerprint: EBC6 E12C 62B1 C734 026B 2122 A20E 5214 6B8D 79E6 +''' + +RETURN = r'''#''' + +import re +import os.path +import tempfile + +# import module snippets +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url +from ansible.module_utils._text import to_native + + +def is_pubkey(string): + """Verifies if string is a pubkey""" + pgp_regex = ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*" + return bool(re.match(pgp_regex, to_native(string, errors='surrogate_or_strict'), re.DOTALL)) + + +class RpmKey(object): + + def __init__(self, module): + # If the key is a url, we need to check if it's present to be idempotent, + # to do that, we need to check the keyid, which we can get from the armor. + keyfile = None + should_cleanup_keyfile = False + self.module = module + self.rpm = self.module.get_bin_path('rpm', True) + state = module.params['state'] + key = module.params['key'] + fingerprint = module.params['fingerprint'] + if fingerprint: + fingerprint = fingerprint.replace(' ', '').upper() + + self.gpg = self.module.get_bin_path('gpg') + if not self.gpg: + self.gpg = self.module.get_bin_path('gpg2', required=True) + + if '://' in key: + keyfile = self.fetch_key(key) + keyid = self.getkeyid(keyfile) + should_cleanup_keyfile = True + elif self.is_keyid(key): + keyid = key + elif os.path.isfile(key): + keyfile = key + keyid = self.getkeyid(keyfile) + else: + self.module.fail_json(msg="Not a valid key %s" % key) + keyid = self.normalize_keyid(keyid) + + if state == 'present': + if self.is_key_imported(keyid): + module.exit_json(changed=False) + else: + if not keyfile: + self.module.fail_json(msg="When importing a key, a valid file must be given") + if fingerprint: + has_fingerprint = self.getfingerprint(keyfile) + if fingerprint != has_fingerprint: + self.module.fail_json( + msg="The specified fingerprint, '%s', does not match the key fingerprint '%s'" % (fingerprint, has_fingerprint) + ) + self.import_key(keyfile) + if should_cleanup_keyfile: + self.module.cleanup(keyfile) + module.exit_json(changed=True) + else: + if self.is_key_imported(keyid): + self.drop_key(keyid) + module.exit_json(changed=True) + else: + module.exit_json(changed=False) + + def fetch_key(self, url): + """Downloads a key from url, returns a valid path to a gpg key""" + rsp, info = fetch_url(self.module, url) + if info['status'] != 200: + self.module.fail_json(msg="failed to fetch key at %s , error was: %s" % (url, info['msg'])) + + key = rsp.read() + if not is_pubkey(key): + self.module.fail_json(msg="Not a public key: %s" % url) + tmpfd, tmpname = tempfile.mkstemp() + self.module.add_cleanup_file(tmpname) + tmpfile = os.fdopen(tmpfd, "w+b") + tmpfile.write(key) + tmpfile.close() + return tmpname + + def normalize_keyid(self, keyid): + """Ensure a keyid doesn't have a leading 0x, has leading or trailing whitespace, and make sure is uppercase""" + ret = keyid.strip().upper() + if ret.startswith('0x'): + return ret[2:] + elif ret.startswith('0X'): + return ret[2:] + else: + return ret + + def getkeyid(self, keyfile): + stdout, stderr = self.execute_command([self.gpg, '--no-tty', '--batch', '--with-colons', '--fixed-list-mode', keyfile]) + for line in stdout.splitlines(): + line = line.strip() + if line.startswith('pub:'): + return line.split(':')[4] + + self.module.fail_json(msg="Unexpected gpg output") + + def getfingerprint(self, keyfile): + stdout, stderr = self.execute_command([ + self.gpg, '--no-tty', '--batch', '--with-colons', + '--fixed-list-mode', '--with-fingerprint', keyfile + ]) + for line in stdout.splitlines(): + line = line.strip() + if line.startswith('fpr:'): + # As mentioned here, + # + # https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS + # + # The description of the `fpr` field says + # + # "fpr :: Fingerprint (fingerprint is in field 10)" + # + return line.split(':')[9] + + self.module.fail_json(msg="Unexpected gpg output") + + def is_keyid(self, keystr): + """Verifies if a key, as provided by the user is a keyid""" + return re.match('(0x)?[0-9a-f]{8}', keystr, flags=re.IGNORECASE) + + def execute_command(self, cmd): + rc, stdout, stderr = self.module.run_command(cmd, use_unsafe_shell=True) + if rc != 0: + self.module.fail_json(msg=stderr) + return stdout, stderr + + def is_key_imported(self, keyid): + cmd = self.rpm + ' -q gpg-pubkey' + rc, stdout, stderr = self.module.run_command(cmd) + if rc != 0: # No key is installed on system + return False + cmd += ' --qf "%{description}" | ' + self.gpg + ' --no-tty --batch --with-colons --fixed-list-mode -' + stdout, stderr = self.execute_command(cmd) + for line in stdout.splitlines(): + if keyid in line.split(':')[4]: + return True + return False + + def import_key(self, keyfile): + if not self.module.check_mode: + self.execute_command([self.rpm, '--import', keyfile]) + + def drop_key(self, keyid): + if not self.module.check_mode: + self.execute_command([self.rpm, '--erase', '--allmatches', "gpg-pubkey-%s" % keyid[-8:].lower()]) + + +def main(): + module = AnsibleModule( + argument_spec=dict( + state=dict(type='str', default='present', choices=['absent', 'present']), + key=dict(type='str', required=True), + fingerprint=dict(type='str'), + validate_certs=dict(type='bool', default=True), + ), + supports_check_mode=True, + ) + + RpmKey(module) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0013924_models.py b/pool/shard001/Python/0013924_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa39e0ac13035b877e9e2f0f5989ac6d9b35199 --- /dev/null +++ b/pool/shard001/Python/0013924_models.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- vim:fileencoding=utf-8: +# Copyright (C) 2010-2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + + +from django.db import models +from django.contrib.auth.models import User +from django.db.models.signals import post_save +from django.contrib.auth.signals import user_logged_in +from apply.models import Organization + +from datetime import datetime + + +class UserProfile(models.Model): + user = models.OneToOneField(User) + first_login = models.BooleanField(default=True) + force_logout_date = models.DateTimeField(null=True, blank=True) + organization = models.ForeignKey(Organization, blank=True, null=True) + telephone = models.CharField(max_length=13, blank=True, null=True) + + def force_logout(self): + self.force_logout_date = datetime.now() + self.save() + + def __unicode__(self): + return "%s profile" % self.user + + +# Signals +def create_user_profile(sender, instance, created, **kwargs): + if created and not kwargs.get('raw', False): + UserProfile.objects.create(user=instance) +post_save.connect(create_user_profile, sender=User, dispatch_uid='create_UserProfile') + + +def update_session_last_login(sender, user, request, **kwargs): + if request: + request.session['LAST_LOGIN_DATE'] = datetime.now() +user_logged_in.connect(update_session_last_login) diff --git a/pool/shard001/Python/0013927_stop-loggerhead.py b/pool/shard001/Python/0013927_stop-loggerhead.py new file mode 100644 index 0000000000000000000000000000000000000000..3c945091292b9c3405cc254e1a5ef2ed53cff1ea --- /dev/null +++ b/pool/shard001/Python/0013927_stop-loggerhead.py @@ -0,0 +1,38 @@ +#!/usr/bin/python -S +# +# Copyright 2009-2012 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +import _pythonpath + +from optparse import OptionParser +import os +import sys + + +parser = OptionParser(description="Stop loggerhead.") +parser.parse_args() + +home = os.path.realpath(os.path.dirname(__file__)) +pidfile = os.path.join(home, 'loggerhead.pid') + +try: + f = open(pidfile, 'r') +except IOError as e: + print 'No pid file found.' + sys.exit(1) + +pid = int(f.readline()) + +try: + os.kill(pid, 0) +except OSError as e: + print 'Stale pid file; server is not running.' + sys.exit(1) + +print +print 'Shutting down previous server @ pid %d.' % (pid,) +print + +import signal +os.kill(pid, signal.SIGTERM) diff --git a/pool/shard001/Python/0013939_watch.py b/pool/shard001/Python/0013939_watch.py new file mode 100644 index 0000000000000000000000000000000000000000..20bb124b6bdda3671e4cdfd68338f622995eeb9e --- /dev/null +++ b/pool/shard001/Python/0013939_watch.py @@ -0,0 +1,133 @@ +import matplotlib.patches as mpatches +import matplotlib.pyplot as plt +import numpy as np +import os +import skimage.io as ski +import sys + +from worlds.base_world import World as BaseWorld +import core.tools as tools +import worlds.ffmpeg_tools as ft +import worlds.world_tools as wtools + +class World(BaseWorld): + """ The watch world provides a sequence of video frames to the BECCA agent + There are no actions that the agent can take that affect the world. + + This world uses the OpenCV library. Installation instructions are here: + http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation + """ + # This package assumes that it is located directly under the BECCA package + def __init__(self, lifespan=None): + super(World, self).__init__() + if lifespan is not None: + self.LIFESPAN = lifespan + # Flag determines whether to plot all the features during display + self.print_all_features = False + self.fov_horz_span = 20 + self.fov_vert_span = 15 + self.name = 'watch_world_15x20' + print "Entering", self.name + # Generate a list of the filenames to be used + self.frames_dir_name = os.path.join('becca_world_watch', 'frames') + self.video_filenames = [] + extensions = ['.mpg', '.mp4', '.flv', '.avi', '.m4v'] + self.data_dir_name = os.path.join('becca_world_watch', 'data') + self.video_filenames = tools.get_files_with_suffix( + self.data_dir_name, extensions) + self.video_file_count = len(self.video_filenames) + print self.video_file_count, 'video files loaded.' + # Initialize the video data to be viewed + self.initialize_video_file() + self.intensity_image = np.zeros((300, 400)) + + self.num_sensors = 2 * self.fov_horz_span * self.fov_vert_span + self.num_actions = 0 + self.sensors = np.zeros(self.num_sensors) + self.frame_counter = 20000 + self.frames_per_step = 3 + self.frames_per_sec = 30. + + def initialize_video_file(self): + """ Queue up one of the video files and get it ready for processing """ + if self.video_file_count == 0: + print 'Add some video files to the data directory' + # Empty out the frames directory + for filename in os.listdir(self.frames_dir_name): + if '.jpg' in filename: + os.remove(os.path.join(self.frames_dir_name, filename)) + # Pick and load a new video file + filename = self.video_filenames[ + np.random.randint(0, self.video_file_count)] + print 'Loading', filename + # Break video into frames + ft.break_movie(filename, self.data_dir_name, self.frames_dir_name) + + # Make a list of still image filenames + self.frame_list = [] + for filename in os.listdir(self.frames_dir_name): + if '.jpg' in filename: + self.frame_list.append(filename) + + self.clip_frame = 0 + + def step(self, action): + """ Advance the video one time step and read and process the frame """ + self.previous_image = self.intensity_image.copy() + self.previous_sensors = self.sensors.copy() + try: + for _ in range(self.frames_per_step): + frame_name = self.frame_list.pop(0) + full_frame_name = os.path.join(self.frames_dir_name, frame_name) + image = ski.imread(full_frame_name) + except: + self.initialize_video_file() + frame_name = self.frame_list.pop(0) + full_frame_name = os.path.join(self.frames_dir_name, frame_name) + image = ski.imread(full_frame_name) + self.timestep += 1 + self.clip_frame += self.frames_per_step + image = image.astype('float') / 256. + # Convert the color image to grayscale + self.intensity_image = np.sum(image, axis=2) / 3. + # Crop the image to get rid of sidebars + (image_height, image_width) = self.intensity_image.shape + self.intensity_image = self.intensity_image[ + image_height / 4: 3 * image_height / 4, + image_width / 4 : 3 * image_width / 4] + # Convert the grayscale to center-surround contrast pixels + center_surround_pixels = wtools.center_surround( + self.intensity_image, self.fov_horz_span, self.fov_vert_span) + unsplit_sensors = center_surround_pixels.ravel() + self.sensors = np.concatenate((np.maximum(unsplit_sensors, 0), + np.abs(np.minimum(unsplit_sensors, 0)))) + # Boost the magnitude of the sensors + self.sensors *= 10. + self.sensors = np.minimum(1., self.sensors) + reward = 0 + return self.sensors, reward + + def visualize(self, agent): + """ + Update the display to the user of the world's internal state + """ + + # debug: this is the most convenient place to tweak the agent + agent.display_interval = 1e1 + self.print_all_features = True + + if self.timestep % agent.display_interval != 0: + return + print ' '.join([self.name, 'is', str(self.timestep), 'timesteps old.']) + (projections, feature_activities) = agent.get_index_projections() + + if self.print_all_features: + log_directory = os.path.join('becca_world_watch', 'log') + wtools.print_pixel_array_features(projections, self.num_sensors, + self.num_actions, + self.fov_horz_span, + self.fov_vert_span, + directory=log_directory, + world_name=self.name, + interp='bicubic') + return diff --git a/pool/shard001/Python/0013942_NumberInputPanel.py b/pool/shard001/Python/0013942_NumberInputPanel.py new file mode 100644 index 0000000000000000000000000000000000000000..07a0c4f5dfdf0d9c64a74f29438d16548a2f4dab --- /dev/null +++ b/pool/shard001/Python/0013942_NumberInputPanel.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + NumberInputPanel.py + --------------------- + Date : August 2012 + Copyright : (C) 2012 by Victor Olaya + Email : volayaf at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Victor Olaya' +__date__ = 'August 2012' +__copyright__ = '(C) 2012, Victor Olaya' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +import os + +from PyQt4 import uic + +from processing.gui.NumberInputDialog import NumberInputDialog + +pluginPath = os.path.split(os.path.dirname(__file__))[0] +WIDGET, BASE = uic.loadUiType( + os.path.join(pluginPath, 'ui', 'widgetNumberSelector.ui')) + + +class NumberInputPanel(BASE, WIDGET): + + def __init__(self, number, minimum, maximum, isInteger): + super(NumberInputPanel, self).__init__(None) + self.setupUi(self) + + self.isInteger = isInteger + if self.isInteger: + self.spnValue.setDecimals(0) + if maximum == 0 or maximum: + self.spnValue.setMaximum(maximum) + else: + self.spnValue.setMaximum(99999999) + if minimum == 0 or minimum: + self.spnValue.setMinimum(minimum) + else: + self.spnValue.setMinimum(-99999999) + + self.spnValue.setValue(float(number)) + + self.btnCalc.clicked.connect(self.showNumberInputDialog) + + def showNumberInputDialog(self): + dlg = NumberInputDialog(self.isInteger) + dlg.exec_() + if dlg.value is not None: + self.spnValue.setValue(dlg.value) + + def getValue(self): + return self.spnValue.value() diff --git a/pool/shard001/Python/0013944_SimpleDemo.py b/pool/shard001/Python/0013944_SimpleDemo.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8328babc997434a55212969d553ae79454a34c --- /dev/null +++ b/pool/shard001/Python/0013944_SimpleDemo.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python + +# The Python version of qwt-*/examples/simple_plot/simple.cpp + +import sys +from qt import * +from Qwt4.Qwt import * +from Qwt4.anynumpy import * + + +class SimplePlot(QwtPlot): + + def __init__(self, *args): + QwtPlot.__init__(self, *args) + # make a QwtPlot widget + self.setTitle('A Simple PyQwt Plot Demonstration') + self.setAutoLegend(True) + self.setLegendPos(Qwt.Right) + # set axis titles + self.setAxisTitle(QwtPlot.xBottom, 'x -->') + self.setAxisTitle(QwtPlot.yLeft, 'y -->') + # insert a few curves + cSin = self.insertCurve('y = sin(x)') + cCos = self.insertCurve('y = cos(x)') + # set curve styles + self.setCurvePen(cSin, QPen(Qt.red)) + self.setCurvePen(cCos, QPen(Qt.blue)) + # calculate 3 NumPy arrays + x = arange(0.0, 10.0, 0.1) + y = sin(x) + z = cos(x) + # copy the data + self.setCurveData(cSin, x, y) + self.setCurveData(cCos, x, z) + # insert a horizontal marker at y = 0 + mY = self.insertLineMarker('y = 0', QwtPlot.yLeft) + self.setMarkerYPos(mY, 0.0) + # insert a vertical marker at x = 2 pi + mX = self.insertLineMarker('x = 2 pi', QwtPlot.xBottom) + self.setMarkerXPos(mX, 2*pi) + # replot + self.replot() + + # __init__() + +# class SimpleDemo + + +def main(args): + app = QApplication(args) + demo = make() + app.setMainWidget(demo) + app.exec_loop() + +# main() + +def make(): + demo = SimplePlot() + demo.resize(500, 300) + demo.show() + return demo + +# make() + + +# Admire +if __name__ == '__main__': + main(sys.argv) + +# Local Variables: *** +# mode: python *** +# End: *** + + + + diff --git a/pool/shard001/Python/0013949_flavorextradata.py b/pool/shard001/Python/0013949_flavorextradata.py new file mode 100644 index 0000000000000000000000000000000000000000..313b83b5dcbaaee8e60c76a06e3f983fcf0f6511 --- /dev/null +++ b/pool/shard001/Python/0013949_flavorextradata.py @@ -0,0 +1,101 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2012 OpenStack Foundation +# Copyright 2011 Canonical Ltd. +# 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. + +"""The Flavor extra data extension + +OpenStack API version 1.1 lists "name", "ram", "disk", "vcpus" as flavor +attributes. This extension adds to that list: + +- OS-FLV-EXT-DATA:ephemeral +""" + +from nova.api.openstack import extensions +from nova.api.openstack import wsgi +from nova.api.openstack import xmlutil + + +authorize = extensions.soft_extension_authorizer('compute', 'flavorextradata') + + +class FlavorextradataController(wsgi.Controller): + def _extend_flavors(self, req, flavors): + for flavor in flavors: + db_flavor = req.get_db_flavor(flavor['id']) + key = "%s:ephemeral" % Flavorextradata.alias + flavor[key] = db_flavor['ephemeral_gb'] + + def _show(self, req, resp_obj): + if not authorize(req.environ['nova.context']): + return + if 'flavor' in resp_obj.obj: + resp_obj.attach(xml=FlavorextradatumTemplate()) + self._extend_flavors(req, [resp_obj.obj['flavor']]) + + @wsgi.extends + def show(self, req, resp_obj, id): + return self._show(req, resp_obj) + + @wsgi.extends(action='create') + def create(self, req, resp_obj, body): + return self._show(req, resp_obj) + + @wsgi.extends + def detail(self, req, resp_obj): + if not authorize(req.environ['nova.context']): + return + resp_obj.attach(xml=FlavorextradataTemplate()) + self._extend_flavors(req, list(resp_obj.obj['flavors'])) + + +class Flavorextradata(extensions.ExtensionDescriptor): + """Provide additional data for flavors.""" + + name = "FlavorExtraData" + alias = "OS-FLV-EXT-DATA" + namespace = ("http://docs.openstack.org/compute/ext/" + "flavor_extra_data/api/v1.1") + updated = "2011-09-14T00:00:00+00:00" + + def get_controller_extensions(self): + controller = FlavorextradataController() + extension = extensions.ControllerExtension(self, 'flavors', controller) + return [extension] + + +def make_flavor(elem): + elem.set('{%s}ephemeral' % Flavorextradata.namespace, + '%s:ephemeral' % Flavorextradata.alias) + + +class FlavorextradatumTemplate(xmlutil.TemplateBuilder): + def construct(self): + root = xmlutil.TemplateElement('flavor', selector='flavor') + make_flavor(root) + alias = Flavorextradata.alias + namespace = Flavorextradata.namespace + return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace}) + + +class FlavorextradataTemplate(xmlutil.TemplateBuilder): + def construct(self): + root = xmlutil.TemplateElement('flavors') + elem = xmlutil.SubTemplateElement(root, 'flavor', selector='flavors') + make_flavor(elem) + alias = Flavorextradata.alias + namespace = Flavorextradata.namespace + return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace}) diff --git a/pool/shard001/Python/0013953_setup.py b/pool/shard001/Python/0013953_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c263b7c4b7dcd8e73c53aa12143a0016300da494 --- /dev/null +++ b/pool/shard001/Python/0013953_setup.py @@ -0,0 +1,17 @@ +from distutils.core import setup +from distutils.extension import Extension +from Cython.Distutils import build_ext +import numpy as np + +ext = [ + Extension("dfresampling.map_coordinates", sources=["dfresampling/map_coordinates.pyx"]) +] + +setup( + name = "dfresampling", + version = "0.1", + author = "Ruben De Visscher", + cmdclass={'build_ext' : build_ext}, + include_dirs = [np.get_include()], + ext_modules=ext +) diff --git a/pool/shard001/Python/0013956_math_ops_linspace_test.py b/pool/shard001/Python/0013956_math_ops_linspace_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f56b1c9284d3253a8a070e66d44a6be6de218e22 --- /dev/null +++ b/pool/shard001/Python/0013956_math_ops_linspace_test.py @@ -0,0 +1,60 @@ +# Copyright 2020 The TensorFlow Authors. 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. +# ============================================================================== +"""Tests for tensorflow.ops.math_ops.linspace.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# Using distutils.version.LooseVersion was resulting in an error, so importing +# directly. +from distutils.version import LooseVersion # pylint: disable=g-importing-member +import itertools + +import numpy as np + +from tensorflow.python.framework import test_util +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +@test_util.run_all_in_graph_and_eager_modes +class LinspaceTest(test_util.TensorFlowTestCase): + + def testLinspaceBroadcasts(self): + if LooseVersion(np.version.version) < LooseVersion("1.16.0"): + self.skipTest("numpy doesn't support axes before version 1.16.0") + + shapes = [(), (2,), (2, 2)] + + types = [np.float64, np.int64] + + for start_shape, stop_shape in itertools.product(shapes, repeat=2): + for num in [0, 1, 2, 20]: + ndims = max(len(start_shape), len(stop_shape)) + for axis in range(-ndims, ndims): + for dtype in types: + start = np.ones(start_shape, dtype) + stop = 10 * np.ones(stop_shape, dtype) + + np_ans = np.linspace(start, stop, num, axis=axis) + tf_ans = self.evaluate( + math_ops.linspace_nd(start, stop, num, axis=axis)) + + self.assertAllClose(np_ans, tf_ans) + + +if __name__ == "__main__": + googletest.main() diff --git a/pool/shard001/Python/0013957_one_time_startup.py b/pool/shard001/Python/0013957_one_time_startup.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd8775d975cc607b1c1c1b3900b87fb45590d32 --- /dev/null +++ b/pool/shard001/Python/0013957_one_time_startup.py @@ -0,0 +1,19 @@ +from dogapi import dog_http_api, dog_stats_api +from django.conf import settings +from xmodule.modulestore.django import modulestore +from django.dispatch import Signal +from request_cache.middleware import RequestCache + +from django.core.cache import get_cache + +CACHE = get_cache('mongo_metadata_inheritance') +for store_name in settings.MODULESTORE: + store = modulestore(store_name) + store.metadata_inheritance_cache_subsystem = CACHE + store.request_cache = RequestCache.get_request_cache() + + modulestore_update_signal = Signal(providing_args=['modulestore', 'course_id', 'location']) + store.modulestore_update_signal = modulestore_update_signal +if hasattr(settings, 'DATADOG_API'): + dog_http_api.api_key = settings.DATADOG_API + dog_stats_api.start(api_key=settings.DATADOG_API, statsd=True) diff --git a/pool/shard001/Python/0013960_config.py b/pool/shard001/Python/0013960_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0ceda920d590ef70250b01874001fb701b12d6 --- /dev/null +++ b/pool/shard001/Python/0013960_config.py @@ -0,0 +1,131 @@ +## ---------------------------------------------------------------------------- +# Lollysite is a website builder and blogging platform for Google App Engine. +# +# Copyright (c) 2009, 2010 Andrew Chilton . +# +# Homepage : http://www.chilts.org/project/lollysite/ +# Ohloh : https://www.ohloh.net/p/lollysite/ +# FreshMeat : http://freshmeat.net/projects/lollysite +# Source : http://gitorious.org/lollysite/ +# +# This file is part of Lollysite. +# +# Lollysite is free software: you can redistribute it and/or modify it under +# the terms of the GNU Affero General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# Lollysite is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +# details. +# +# You should have received a copy of the GNU Affero General Public License +# along with Lollysite. If not, see . +# +## ---------------------------------------------------------------------------- + +# import standard modules +import logging + +# Google specific modules +from google.appengine.ext import db +from google.appengine.api import memcache + +# local modules +from models import Config +import webbase +import util + +## ---------------------------------------------------------------------------- + +# List +class List(webbase.WebBase): + def get(self): + config = util.get_config() + vals = { + 'config' : config, + } + self.template( 'config-list.html', vals, 'admin' ); + +# Edit +class Edit(webbase.WebBase): + def get(self): + config = util.get_config() + title = None + value = None + if self.request.get('title'): + title = self.request.get('title') + if title in config.config: + value = config.config[title] + + vals = { + 'item' : { + 'title' : title, + 'value' : value, + } + } + self.template( 'config-form.html', vals, 'admin' ); + + def post(self): + title = None + value = None + config = util.get_config() + try: + # get all the incoming values + title = self.request.get('title').strip() + value = self.request.get('value').strip() + + config.config[title] = value + + config.put() + memcache.delete(title, namespace='config') + self.redirect('.') + + except Exception, err: + vals['item'] = self.request.POST + vals['err'] = err + self.template( 'config-form.html', vals, 'admin' ); + + +# Empty Form (ie. never seen ... does something then goes back to the PropertyList) +class UnCache(webbase.WebBase): + def get(self): + title = self.request.get('title') + if title: + memcache.delete(title, namespace='config') + self.redirect('.') + +# Delete +class Del(webbase.WebBase): + def get(self): + try: + title = self.request.get('title').strip() + if title: + config = util.get_config() + vals = { + 'item' : { + 'title' : title, + 'value' : config.config[title], + } + } + self.template( 'config-del.html', vals, 'admin' ); + else: + self.redirect('.') + except: + self.redirect('.') + + def post(self): + try: + title = self.request.get('title').strip() + if title: + config = util.get_config() + del config.config[title] + config.put() + memcache.delete(title, namespace='config') + # else, just redirect to this dir + self.redirect('.') + except: + self.redirect('.') + +## ---------------------------------------------------------------------------- diff --git a/pool/shard001/Python/0013967_quickstart.py b/pool/shard001/Python/0013967_quickstart.py new file mode 100644 index 0000000000000000000000000000000000000000..6a3b6bd0bcd2ebd20365356eabf97c9947993594 --- /dev/null +++ b/pool/shard001/Python/0013967_quickstart.py @@ -0,0 +1,40 @@ +""" + http://spicerack.github.io/sage/html/quickstart.html +""" + +from sage import triggers, aliases, ansi, send +from sage.signals.gmcp import room as room_signal + +room_triggers = triggers.create_group('room', app='quickstart') + +room_aliases = aliases.create_group('room', app='quickstart') + + +# interception to False means the original command passes through +@room_aliases.exact(pattern="ql", intercept=False) +def ql(alias): + + # enable the exits trigger + room_triggers('exits').enable() + + # send to Achaea + #send('ql') + + +@room_triggers.regex("^You see (a single exit leading|exits leading) ([a-z, \(\)]+)\.$", enabled=False) +def exits(trigger): + exit_str = trigger.groups[1] + exit_str = exit_str.replace('and', '') + exits = [ansi.bold_white(e.strip()) for e in exit_str.split(',')] + new_str = ', '.join(exits) + trigger.line.output = "Exits: " + new_str + + # now disable this trigger + trigger.disable() + + +def on_room_update(**kwargs): + room_triggers('exits').enable() + + +room_signal.connect(on_room_update) # Enable the room exits trigger on room change \ No newline at end of file diff --git a/pool/shard001/Python/0013972_aqdb_migrate.py b/pool/shard001/Python/0013972_aqdb_migrate.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4c3786b4b28974695e10182b51faa59100f1df --- /dev/null +++ b/pool/shard001/Python/0013972_aqdb_migrate.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python +# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- +# ex: set expandtab softtabstop=4 shiftwidth=4: +# +# Copyright (C) 2012,2013,2014,2015,2016 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. + +# Copy AQDB to a different backend. +# +# The source backend is taken from $AQDCONF as usual, the destination backend +# is taken from command line. +# +# Warning: making a copy will cause the sequences in the source database to +# jump - there's no easy way around that. +# +# Examples: +# ./aqdb_migrate sqlite:////path/aquilon.db +# ./aqdb_migrate postgresql://@/ + +from __future__ import print_function + +import argparse +import os +import signal +import sys + +# -- begin path_setup -- +BINDIR = os.path.dirname(os.path.realpath(sys.argv[0])) +LIBDIR = os.path.join(BINDIR, "..", "lib") + +if LIBDIR not in sys.path: + sys.path.append(LIBDIR) +# -- end path_setup -- + +from aquilon.aqdb import depends # pylint: disable=W0611 + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, configure_mappers +from sqlalchemy.sql import text + +from aquilon.aqdb.db_factory import DbFactory +from aquilon.aqdb.model import Base +from aquilon.utils import chunk + +signalled = 0 + + +def signal_handler(signum, frame): # pylint: disable=W0613 + global signalled # pylint: disable=W0603 + signalled = 1 + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='copy AQDB between backends') + parser.add_argument('-v', '--verbose', + action='store_true', + dest='verbose', + help='show queries (metadata bind.echo = True)') + parser.add_argument('dsn', metavar='DSN', + help='DSN of the target backend (driver://user[:password]@host[:port]/database)') + opts = parser.parse_args() + + # Use aquilon.aqdb for connecting to the source backend + db = DbFactory(verbose=opts.verbose) + src_session = sessionmaker(bind=db.engine)() + + if db.engine.dialect.name == 'oracle' or \ + db.engine.dialect.name == 'postgresql': + src_session.execute(text('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')) + + dest_engine = create_engine(opts.dsn, convert_unicode=True, echo=opts.verbose) + dest_session = sessionmaker(bind=dest_engine)() + + if db.engine.dialect.supports_sequences and \ + dest_engine.dialect.supports_sequences: + # The only operation on sequences that all DBs support is getting the + # next value. Unfortunately that means we have to alter the state of the + # source database here. + for seq in Base.metadata._sequences.values(): + nextid = src_session.execute(seq) + # Make sure the sequence is re-created with the right start index + seq.drop(dest_engine, checkfirst=True) + seq.start = nextid + + # Avoid auto-populating tables as that would interfere with the copying + Base.populate_table_on_create = False + + # Need to call this explicitely to make the __extra_table_args__ hack work + configure_mappers() + + Base.metadata.create_all(dest_engine, checkfirst=True) + + if dest_engine.dialect.name == 'postgresql': + dest_session.execute(text('SET CONSTRAINTS ALL DEFERRED')) + elif dest_engine.dialect.name == 'oracle': + dest_session.execute(text('ALTER SESSION SET CONSTRAINTS = DEFERRED')) + elif dest_engine.dialect.name == 'sqlite': + # SQLite does not allow changing the deferred state at run-time, but + # it does allow disabling foreign keys entirely + dest_session.execute(text('PRAGMA foreign_keys = 0;')) + + signal.signal(signal.SIGALRM, signal_handler) + + # Oracle does not like EINTR + signal.siginterrupt(signal.SIGALRM, False) + + multirow_insert = db.engine.dialect.supports_multivalues_insert + + for table in Base.metadata.sorted_tables: + total = src_session.execute(table.count()).scalar() + print('Processing %s (%d rows)' % (table, total), end=' ') + sys.stdout.flush() + cnt = 0 + + signal.setitimer(signal.ITIMER_REAL, 5, 5) + for rows in chunk(src_session.execute(table.select()), 1000): + cnt = cnt + len(rows) + if signalled: + print("... %d" % cnt, end=' ') + sys.stdout.flush() + signalled = 0 + + if multirow_insert: + data = [{col.key: getattr(row, col.key) + for col in table.columns} + for row in rows] + + dest_session.execute(table.insert().values(data)) + else: + for row in rows: + data = {col.key: getattr(row, col.key) for col in table.columns} + + dest_session.execute(table.insert().values(data)) + + signal.setitimer(signal.ITIMER_REAL, 0) + dest_session.flush() + print() + + dest_session.commit() diff --git a/pool/shard001/Python/0013973_topic.py b/pool/shard001/Python/0013973_topic.py new file mode 100644 index 0000000000000000000000000000000000000000..910939907869072a697e61410d269ba2557b0f91 --- /dev/null +++ b/pool/shard001/Python/0013973_topic.py @@ -0,0 +1,155 @@ +""" +Author: Keith Bourgoin, Emmett Butler +""" +__license__ = """ +Copyright 2015 Parse.ly, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +__all__ = ["Topic"] +import logging +from collections import defaultdict + +from .balancedconsumer import BalancedConsumer +from .common import OffsetType +from .partition import Partition +from .producer import Producer +from .protocol import PartitionOffsetRequest +from .simpleconsumer import SimpleConsumer + + +log = logging.getLogger(__name__) + + +class Topic(): + """ + A Topic is an abstraction over the kafka concept of a topic. + It contains a dictionary of partitions that comprise it. + """ + def __init__(self, cluster, topic_metadata): + """Create the Topic from metadata. + + :param cluster: The Cluster to use + :type cluster: :class:`pykafka.cluster.Cluster` + :param topic_metadata: Metadata for all topics. + :type topic_metadata: :class:`pykafka.protocol.TopicMetadata` + """ + self._name = topic_metadata.name + self._cluster = cluster + self._partitions = {} + self.update(topic_metadata) + + def __repr__(self): + return "<{module}.{classname} at {id_} (name={name})>".format( + module=self.__class__.__module__, + classname=self.__class__.__name__, + id_=hex(id(self)), + name=self._name + ) + + @property + def name(self): + """The name of this topic""" + return self._name + + @property + def partitions(self): + """A dictionary containing all known partitions for this topic""" + return self._partitions + + def get_producer(self, **kwargs): + """Create a :class:`pykafka.producer.Producer` for this topic. + + For a description of all available `kwargs`, see the Producer docstring. + """ + return Producer(self._cluster, self, **kwargs) + + def fetch_offset_limits(self, offsets_before, max_offsets=1): + """Get earliest or latest offset. + + Use the Offset API to find a limit of valid offsets for each partition + in this topic. + + :param offsets_before: Return an offset from before this timestamp (in + milliseconds) + :type offsets_before: int + :param max_offsets: The maximum number of offsets to return + :type max_offsets: int + """ + requests = defaultdict(list) # one request for each broker + for part in self.partitions.itervalues(): + requests[part.leader].append(PartitionOffsetRequest( + self.name, part.id, offsets_before, max_offsets + )) + output = {} + for broker, reqs in requests.iteritems(): + res = broker.request_offset_limits(reqs) + output.update(res.topics[self.name]) + return output + + def earliest_available_offsets(self): + """Get the earliest offset for each partition of this topic.""" + return self.fetch_offset_limits(OffsetType.EARLIEST) + + def latest_available_offsets(self): + """Get the latest offset for each partition of this topic.""" + return self.fetch_offset_limits(OffsetType.LATEST) + + def update(self, metadata): + """Update the Partitions with metadata about the cluster. + + :param metadata: Metadata for all topics + :type metadata: :class:`pykafka.protocol.TopicMetadata` + """ + p_metas = metadata.partitions + + # Remove old partitions + removed = set(self._partitions.keys()) - set(p_metas.keys()) + if len(removed) > 0: + log.info('Removing %d partitons', len(removed)) + for id_ in removed: + log.debug('Removing partiton %s', self._partitons[id_]) + self._partitons.pop(id_) + + # Add/update current partitions + brokers = self._cluster.brokers + if len(p_metas) > 0: + log.info("Adding %d partitions", len(p_metas)) + for id_, meta in p_metas.iteritems(): + if meta.id not in self._partitions: + log.debug('Adding partition %s/%s', self.name, meta.id) + self._partitions[meta.id] = Partition( + self, meta.id, + brokers[meta.leader], + [brokers[b] for b in meta.replicas], + [brokers[b] for b in meta.isr], + ) + else: + self._partitions[id_].update(brokers, meta) + + def get_simple_consumer(self, consumer_group=None, **kwargs): + """Return a SimpleConsumer of this topic + + :param consumer_group: The name of the consumer group to join + :type consumer_group: str + """ + return SimpleConsumer(self, self._cluster, + consumer_group=consumer_group, **kwargs) + + def get_balanced_consumer(self, consumer_group, **kwargs): + """Return a BalancedConsumer of this topic + + :param consumer_group: The name of the consumer group to join + :type consumer_group: str + """ + return BalancedConsumer(self, self._cluster, consumer_group, **kwargs) diff --git a/pool/shard001/Python/0013977_record.py b/pool/shard001/Python/0013977_record.py new file mode 100644 index 0000000000000000000000000000000000000000..17e207e2c56402aed3862fc34d282e521c253ae2 --- /dev/null +++ b/pool/shard001/Python/0013977_record.py @@ -0,0 +1,94 @@ +import pyaudio +import wave +import os, sys +import time +from pynput.keyboard import Controller, Listener + +# Sample rate, basically how many times/sec we grab a sound value +RATE = 44100 + +# Buffer to load +CHUNK = 1024 + +recording = False + +# Makes a stream from pyaudio +# PyAudio, args -> AudioStream +def mkStream(audio, **args): + return audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK, **args) + + +# records audio from the mic +# Int -> [Frame] +def recordAudio(outName): + frames = [] + global recording + recording = True + + def callback(in_data, frame_count, time_info, status): + if recording: + frames.append(in_data) + state = pyaudio.paContinue + else: + writeWav(frames, outName) + state = pyaudio.paComplete + + return (None, state) + + audio = pyaudio.PyAudio() + stream = mkStream(audio, stream_callback=callback) # Get the audio as a stream + stream.start_stream() + + + def on_press(key): + global recording + recording = False + return False + + Listener(on_press=on_press).start() + + while stream.is_active(): + time.sleep(0.25) + + # Cleanup + stream.stop_stream() + stream.close() + audio.terminate() + +# Plays the audio out loud +# [Frame] -> () +def playAudio(frames): + play = pyaudio.PyAudio() + # Make an output stream + stream = mkStream(play, output=True) + + # Play each frame + for frame in frames: + stream.write(frame) + + # Cleanup + stream.stop_stream() + stream.close() + play.terminate() + +# Writes a wav file given frames and a name +# [Frame], name -> () +def writeWav(frames, outName): + try: + os.remove(outName) + except: + pass + + wavFile = wave.open(outName, 'wb') + + # Channels basically means instruments. We only have one (for now) + wavFile.setnchannels(1) + + wavFile.setsampwidth(2) + wavFile.setframerate(RATE) + wavFile.writeframes(b''.join(frames)) + wavFile.close() + + +if __name__ == '__main__': + recordAudio('keytest.wav') diff --git a/pool/shard001/Python/0013978_test_document_follow.py b/pool/shard001/Python/0013978_test_document_follow.py new file mode 100644 index 0000000000000000000000000000000000000000..050add65e9065183bfe049d9554f34a057fb2674 --- /dev/null +++ b/pool/shard001/Python/0013978_test_document_follow.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, Frappe Technologies and Contributors +# License: MIT. See LICENSE +import frappe +import unittest +import frappe.desk.form.document_follow as document_follow + +class TestDocumentFollow(unittest.TestCase): + def test_document_follow(self): + user = get_user() + event_doc = get_event() + + event_doc.description = "This is a test description for sending mail" + event_doc.save(ignore_version=False) + + document_follow.unfollow_document("Event", event_doc.name, user.name) + doc = document_follow.follow_document("Event", event_doc.name, user.name) + self.assertEqual(doc.user, user.name) + + document_follow.send_hourly_updates() + + email_queue_entry_name = frappe.get_all("Email Queue", limit=1)[0].name + email_queue_entry_doc = frappe.get_doc("Email Queue", email_queue_entry_name) + + self.assertEqual((email_queue_entry_doc.recipients[0].recipient), user.name) + + self.assertIn(event_doc.doctype, email_queue_entry_doc.message) + self.assertIn(event_doc.name, email_queue_entry_doc.message) + + + def tearDown(self): + frappe.db.rollback() + +def get_event(): + doc = frappe.get_doc({ + 'doctype': 'Event', + 'subject': "_Test_Doc_Follow", + 'doc.starts_on': frappe.utils.now(), + 'doc.ends_on': frappe.utils.add_days(frappe.utils.now(),5), + 'doc.description': "Hello" + }) + doc.insert() + return doc + +def get_user(): + if frappe.db.exists('User', 'test@docsub.com'): + doc = frappe.get_doc('User', 'test@docsub.com') + else: + doc = frappe.new_doc("User") + doc.email = "test@docsub.com" + doc.first_name = "Test" + doc.last_name = "User" + doc.send_welcome_email = 0 + doc.document_follow_notify = 1 + doc.document_follow_frequency = "Hourly" + doc.insert() + return doc \ No newline at end of file diff --git a/pool/shard001/Python/0013980_magfit.py b/pool/shard001/Python/0013980_magfit.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfda796b42dd37ecc5e036bce7378e3cb8c710b --- /dev/null +++ b/pool/shard001/Python/0013980_magfit.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python + +''' +fit best estimate of magnetometer offsets +''' + +import sys, time, os, math + +# allow import from the parent directory, where mavlink.py is +sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) + +from optparse import OptionParser +parser = OptionParser("magfit.py [options]") +parser.add_option("--no-timestamps",dest="notimestamps", action='store_true', help="Log doesn't have timestamps") +parser.add_option("--condition",dest="condition", default=None, help="select packets by condition") +parser.add_option("--noise", type='float', default=0, help="noise to add") +parser.add_option("--mav10", action='store_true', default=False, help="Use MAVLink protocol 1.0") + +(opts, args) = parser.parse_args() + +if opts.mav10: + os.environ['MAVLINK10'] = '1' +import mavutil +from rotmat import Vector3 + +if len(args) < 1: + print("Usage: magfit.py [options] ") + sys.exit(1) + +def noise(): + '''a noise vector''' + from random import gauss + v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1)) + v.normalize() + return v * opts.noise + +def select_data(data): + ret = [] + counts = {} + for d in data: + mag = d + key = "%u:%u:%u" % (mag.x/20,mag.y/20,mag.z/20) + if key in counts: + counts[key] += 1 + else: + counts[key] = 1 + if counts[key] < 3: + ret.append(d) + print(len(data), len(ret)) + return ret + +def radius(mag, offsets): + '''return radius give data point and offsets''' + return (mag + offsets).length() + +def radius_cmp(a, b, offsets): + '''return radius give data point and offsets''' + diff = radius(a, offsets) - radius(b, offsets) + if diff > 0: + return 1 + if diff < 0: + return -1 + return 0 + +def sphere_error(p, data): + from scipy import sqrt + x,y,z,r = p + ofs = Vector3(x,y,z) + ret = [] + for d in data: + mag = d + err = r - radius(mag, ofs) + ret.append(err) + return ret + +def fit_data(data): + import numpy, scipy + from scipy import optimize + + p0 = [0.0, 0.0, 0.0, 0.0] + p1, ier = optimize.leastsq(sphere_error, p0[:], args=(data)) + if not ier in [1, 2, 3, 4]: + raise RuntimeError("Unable to find solution") + return (Vector3(p1[0], p1[1], p1[2]), p1[3]) + +def magfit(logfile): + '''find best magnetometer offset fit to a log file''' + + print("Processing log %s" % filename) + mlog = mavutil.mavlink_connection(filename, notimestamps=opts.notimestamps) + + data = [] + + last_t = 0 + offsets = Vector3(0,0,0) + + # now gather all the data + while True: + m = mlog.recv_match(condition=opts.condition) + if m is None: + break + if m.get_type() == "SENSOR_OFFSETS": + # update current offsets + offsets = Vector3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z) + if m.get_type() == "RAW_IMU": + mag = Vector3(m.xmag, m.ymag, m.zmag) + # add data point after subtracting the current offsets + data.append(mag - offsets + noise()) + + print("Extracted %u data points" % len(data)) + print("Current offsets: %s" % offsets) + + data = select_data(data) + + # do an initial fit with all data + (offsets, field_strength) = fit_data(data) + + for count in range(3): + # sort the data by the radius + data.sort(lambda a,b : radius_cmp(a,b,offsets)) + + print("Fit %u : %s field_strength=%6.1f to %6.1f" % ( + count, offsets, + radius(data[0], offsets), radius(data[-1], offsets))) + + # discard outliers, keep the middle 3/4 + data = data[len(data)/8:-len(data)/8] + + # fit again + (offsets, field_strength) = fit_data(data) + + print("Final : %s field_strength=%6.1f to %6.1f" % ( + offsets, + radius(data[0], offsets), radius(data[-1], offsets))) + +total = 0.0 +for filename in args: + magfit(filename) diff --git a/pool/shard001/Python/0013984_test_router_availability_zone.py b/pool/shard001/Python/0013984_test_router_availability_zone.py new file mode 100644 index 0000000000000000000000000000000000000000..92a378987e0f6001b054fdb79a4d320719db7b11 --- /dev/null +++ b/pool/shard001/Python/0013984_test_router_availability_zone.py @@ -0,0 +1,111 @@ +# +# 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 six + +from neutron.db.availability_zone import router as router_az_db +from neutron.db import common_db_mixin +from neutron.db import l3_agentschedulers_db +from neutron.db import l3_db +from neutron.extensions import l3 +from neutron.extensions import router_availability_zone as router_az +from neutron.plugins.common import constants as service_constants +from neutron.tests.unit.extensions import test_availability_zone as test_az +from neutron.tests.unit.extensions import test_l3 + + +class AZL3ExtensionManager(test_az.AZExtensionManager): + + def get_resources(self): + return (super(AZL3ExtensionManager, self).get_resources() + + l3.L3.get_resources()) + + +class AZRouterTestPlugin(common_db_mixin.CommonDbMixin, + l3_db.L3_NAT_db_mixin, + router_az_db.RouterAvailabilityZoneMixin, + l3_agentschedulers_db.AZL3AgentSchedulerDbMixin): + supported_extension_aliases = ["router", "l3_agent_scheduler", + "router_availability_zone"] + + @classmethod + def get_plugin_type(cls): + return service_constants.L3_ROUTER_NAT + + def get_plugin_description(self): + return "L3 Routing Service Plugin for testing" + + def _create_router_db(self, context, router, tenant_id): + # l3-plugin using routerextraattributes must call + # _process_extra_attr_router_create. + with context.session.begin(subtransactions=True): + router_db = super(AZRouterTestPlugin, self)._create_router_db( + context, router, tenant_id) + self._process_extra_attr_router_create(context, router_db, router) + return router_db + + +class TestAZRouterCase(test_az.AZTestCommon, test_l3.L3NatTestCaseMixin): + def setUp(self): + plugin = ('neutron.tests.unit.extensions.' + 'test_availability_zone.AZTestPlugin') + l3_plugin = ('neutron.tests.unit.extensions.' + 'test_router_availability_zone.AZRouterTestPlugin') + service_plugins = {'l3_plugin_name': l3_plugin} + + self._backup() + l3.RESOURCE_ATTRIBUTE_MAP['routers'].update( + router_az.EXTENDED_ATTRIBUTES_2_0['routers']) + ext_mgr = AZL3ExtensionManager() + super(TestAZRouterCase, self).setUp(plugin=plugin, ext_mgr=ext_mgr, + service_plugins=service_plugins) + + def _backup(self): + self.contents_backup = {} + for res, attrs in six.iteritems(l3.RESOURCE_ATTRIBUTE_MAP): + self.contents_backup[res] = attrs.copy() + self.addCleanup(self._restore) + + def _restore(self): + l3.RESOURCE_ATTRIBUTE_MAP = self.contents_backup + + def test_create_router_with_az(self): + self._register_azs() + az_hints = ['nova2'] + with self.router(availability_zone_hints=az_hints) as router: + res = self._show('routers', router['router']['id']) + self.assertItemsEqual(az_hints, + res['router']['availability_zone_hints']) + + def test_create_router_with_azs(self): + self._register_azs() + az_hints = ['nova2', 'nova3'] + with self.router(availability_zone_hints=az_hints) as router: + res = self._show('routers', router['router']['id']) + self.assertItemsEqual(az_hints, + res['router']['availability_zone_hints']) + + def test_create_router_without_az(self): + with self.router() as router: + res = self._show('routers', router['router']['id']) + self.assertEqual([], res['router']['availability_zone_hints']) + + def test_create_router_with_empty_az(self): + with self.router(availability_zone_hints=[]) as router: + res = self._show('routers', router['router']['id']) + self.assertEqual([], res['router']['availability_zone_hints']) + + def test_create_router_with_none_existing_az(self): + res = self._create_router(self.fmt, 'tenant_id', + availability_zone_hints=['nova4']) + self.assertEqual(404, res.status_int) diff --git a/pool/shard001/Python/0013988_fsutil.py b/pool/shard001/Python/0013988_fsutil.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a71073d657a18db642064e114cf995b2729b8b --- /dev/null +++ b/pool/shard001/Python/0013988_fsutil.py @@ -0,0 +1,135 @@ +import glob +import os +import re +import time +import datetime +import dateutil.relativedelta +import shutil +import gzip + + +class FSUtil: + """ + Custom utility class to handle file system related operations + """ + @staticmethod + def rotate_files(_dir, file_pattern, backup_count=0, backup_period='7d', archive=False): + """ + This purpose of this method is rotate files within a directory which are older + than certain period i.e.( 7 days: 7d or 2 Months: 2m). + + This method identifies files which should be rotated based on their shell glob name + pattern passed to file_pattern parameter. + + if archive parameter is set to true then all files which have been qualified for + rotation based on their modification date will be compressed and archived but not deleted. + + If set to False (default) then all files which are older than backup_period will + be deleted. + + you can also restrict the number of rotated archived file which should be kept. + + :param _dir: (string) path to directory where files should be rotated + :param file_pattern: (glob pattern) pattern of file names which should be rotated + :param backup_count: (int) no. of rotated files which should be kept in backup. + If 0 then all the rotated files are kept. + :param backup_period: (string) how much older file should be eligible for rotation + :param archive: bool True if rotated files should be archived. + :return: None + """ + mapping = dict(y='years', m='months', w='weeks', + d='days', h='hours', i='minutes', s='seconds') + regex = '^(\d+)([ymwdhis])' + match = re.compile(regex, re.IGNORECASE).match(backup_period).groups() + if not os.path.exists(_dir): + raise ValueError("Input directory does not exists!") + if match is None or not match: + raise ValueError('''backup_period parameter is not valid! + Allowed values are: digits[ymwdhis] + WHERE {}'''.format(mapping)) + if not isinstance(archive, bool): + raise ValueError("archive parameter is not boolean") + if not isinstance(backup_count, int): + raise ValueError("backup_count parameter is not integer") + else: + digit, unit = match + m = {mapping.get(str(unit).lower()): int(digit)} + period = time.mktime((datetime.datetime.now()-dateutil.relativedelta.relativedelta(**m)) + .timetuple())*1000 + all_files = glob.glob(os.path.join(_dir, file_pattern)) + files = {file: os.path.getmtime(file)*1000 for file in all_files + if os.path.getmtime(file)*1000 >= period} + backup_count = backup_count if backup_count else len(files) + shorted_files = dict(sorted(files.items(), key=lambda x: x[1], + reverse=True)[:backup_count]) + file_list = (file if file in shorted_files else os.unlink(file) + for file in all_files) + for file in file_list: + if archive: + with open(file, 'rb') as f_in: + with gzip.open(file+".gz", 'wb') as f_out: + shutil.copyfileobj(f_in, f_out) + os.unlink(file) + + @staticmethod + def copy_file(src, dst, metadata=False): + """ + This method copies source file to a new file. + This method also handles copying of symlinks source files + + :param src: (string) source file path + :param dst: (string) dest file path + :param metadata: bool True if source file permission + attributes should also be copied to destination file + :return: None + """ + if os.path.islink(src): + symlink = os.readlink(src) + if os.path.exists(dst): + os.unlink(dst) + os.symlink(symlink, dst) + else: + shutil.copy2(src, dst) if metadata else shutil.copy(src, dst) + + @staticmethod + def copy_dir(src, dst, metadata=False): + """ + This method copies content of source directory to a destination directory. + This method also creates destination directory if it does not exist. + + :param src: (string) source dir + :param dst: (string) destination dir + :param metadata: bool True if directory permission + attributes should also be copied to destination dir + :return: None + """ + if not os.path.exists(dst): + os.mkdir(dst) + if metadata: + shutil.copystat(src, dst) + root, dirs, files = os.walk(src).__next__() + if files: + _ = all(map(lambda f: FSUtil.copy_file(os.path.join(root, f), + os.path.join(dst, f), metadata), files)) + if dirs: + _ = all(map(lambda d: FSUtil.copy_dir(os.path.join(root, d), + os.path.join(dst, d), metadata), dirs)) + + @staticmethod + def replace_text_in_file(file, search_exp, replace_exp, original_bkp=False): + """ + This method replaces any string pattern to different string within a text file. + + :param file: (string) path of file in which text to be replaced + :param search_exp: (regex pattern) of source string to be replaced + :param replace_exp: (regex pattern) of target string to be replaced with + :param original_bkp: bool True if an unmodified version of original file should + be kept as backup with '.bkp' extension + :return: None + """ + import fileinput + import re + with fileinput.input(file, inplace=original_bkp, backup='.bkp') as f: + for line in f: + line = re.sub(search_exp, replace_exp, line.rstrip()) + print(line) \ No newline at end of file diff --git a/pool/shard001/Python/0013994_conf.py b/pool/shard001/Python/0013994_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..5ebc6168e38dd9b746398765c1237369c947fa5e --- /dev/null +++ b/pool/shard001/Python/0013994_conf.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +# +# autobahn documentation build configuration file, created by +# sphinx-quickstart on Sat Apr 30 17:26:56 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex +import time + +try: + import sphinx_rtd_theme +except ImportError: + sphinx_rtd_theme = None + +try: + from sphinxcontrib import spelling +except ImportError: + spelling = None + + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('./_extensions')) +sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath('.')) + +# monkey-patch txaio so that we can "use" both twisted *and* asyncio, +# at least at import time -- this is so the autodoc stuff can +# successfully import autobahn.twisted.* as well as autobahn.asyncio.* +# (usually, you can only import one or the other in a single Python +# interpreter) +import txaio + +def use_tx(): + "monkey-patched for doc-building" + from txaio import tx + txaio._use_framework(tx) + +def use_aio(): + "monkey-patched for doc-building" + from txaio import aio + txaio._use_framework(aio) + +txaio.use_twisted = use_tx +txaio.use_asyncio = use_aio + + +# Monkey patch away WARNING like: +# "index.rst:4: WARNING: nonlocal image URI found: https://img.shields.io/pypi/v/txaio.svg" +# see: http://stackoverflow.com/a/28778969 +import sphinx.environment +from docutils.utils import get_source_line + +def _warn_node(self, msg, node, **kwargs): + if not msg.startswith('nonlocal image URI found:'): + self._warnfunc(msg, '%s:%s' % get_source_line(node)) + +sphinx.environment.BuildEnvironment.warn_node = _warn_node + +try: + from qualname import qualname +except ImportError: + qualname = None + +# http://stackoverflow.com/a/21449475/884770 +# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#event-autodoc-skip-member + +# app, what, name, obj, skip, options: +# class __module__ autobahn.asyncio.websocket True {'show-inheritance': True, 'members': , 'undoc-members': True} +# +def autodoc_skip_member(app, what, name, obj, skip, options): + # skip everything that isn't decorated with @autobahn.public or .. + if hasattr(obj, '_is_public') and obj._is_public: + if qualname: + try: + qn = qualname(obj) + except AttributeError as e: + print(e) + qn = name + print('public API: {}.{}'.format(obj.__module__, qn)) + return False + else: + return True + +# !! when enabled, only members with "@public" decorator will be rendered in the docs !! +# def setup(app): +# # wire up our custom checker to skip member +# app.connect('autodoc-skip-member', autodoc_skip_member) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +autoapi_type = 'python' +autoapi_dirs = ['../autobahn'] +autoapi_add_toctree_entry = False +autoapi_options = ['members', 'undoc-members', 'private-members', 'show-inheritance', 'special-members', 'show-module-summary'] +# autoapi_template_dir = 'docs/autoapi/templates' +autoapi_python_use_implicit_namespaces = True + + +# Check if we are building on readthedocs +RTD_BUILD = os.environ.get('READTHEDOCS', None) == 'True' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + # https://sphinx-autoapi.readthedocs.io + 'autoapi.extension', + + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', + 'sphinx.ext.intersphinx', + 'sphinx.ext.ifconfig', + 'sphinx.ext.todo', + 'sphinx.ext.doctest', + + # Usage: .. thumbnail:: picture.png + # Installation: pip install sphinxcontrib-images + # Source: https://github.com/sphinx-contrib/images + 'sphinxcontrib.images', + + #'sphinxcontrib.spelling', + 'txsphinx' +] + +# extensions not available on RTD +if spelling is not None: + extensions.append('sphinxcontrib.spelling') + +spelling_lang = 'en_US' +spelling_show_suggestions = False +spelling_word_list_filename = 'spelling_wordlist.txt' + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'contents' + +# General information about the project. +project = 'autobahn' +author = 'Crossbar.io Project' +this_year = '{0}'.format(time.strftime('%Y')) +if this_year != '2012': + copyright = '2012-{0}, Crossbar.io Technologies GmbH'.format(this_year) +else: + copyright = '2012, Crossbar.io Technologies GmbH' + +# The version info for the project yo're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) +with open(os.path.join(base_dir, "autobahn", "_version.py")) as f: + exec(f.read()) # defines __version__ + +version = release = __version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build', 'work'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +if sphinx_rtd_theme: + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +else: + html_theme = "default" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = [] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# Show full, global TOC in sidebar +# http://stackoverflow.com/a/19007358 +# http://sphinx-doc.org/config.html#confval-html_sidebars +html_sidebars = { + '**': [ + 'globaltoc.html', + 'relations.html', + 'sourcelink.html', + 'searchbox.html' + ], +} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'autobahndoc' + +# http://sphinx-doc.org/ext/intersphinx.html +intersphinx_mapping = { + 'py3': ('https://docs.python.org/3', None), + 'python': ('https://docs.python.org/3', None), + 'rtd': ('https://docs.readthedocs.io/en/latest/', None), + 'txaio': ('https://txaio.readthedocs.io/en/latest/', None), + 'autobahn': ('https://autobahn.readthedocs.io/en/latest/', None), + 'zlmdb': ('https://zlmdb.readthedocs.io/en/latest/', None), +} + +rst_epilog = """ +.. |ab| replace:: Autobahn +.. |Ab| replace:: **Autobahn** +.. |abL| replace:: Autobahn|Python +.. |AbL| replace:: **Autobahn**\|Python +.. _Autobahn: http://crossbar.io/autobahn#python +.. _AutobahnJS: http://crossbar.io/autobahn#js +.. _AutobahnPython: **Autobahn**\|Python +.. _WebSocket: http://tools.ietf.org/html/rfc6455 +.. _RFC6455: http://tools.ietf.org/html/rfc6455 +.. _WAMP: http://wamp-proto.org/ +.. _Twisted: http://twistedmatrix.com/ +.. _asyncio: http://docs.python.org/3.4/library/asyncio.html +.. _CPython: http://python.org/ +.. _PyPy: http://pypy.org/ +.. _Jython: http://jython.org/ +.. _AutobahnTestsuite: http://crossbar.io/autobahn#testsuite +.. _trollius: https://pypi.python.org/pypi/trollius/ +.. _tulip: https://pypi.python.org/pypi/asyncio/ +""" + +rst_prolog = """ +""" + +# http://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method +autoclass_content = 'both' + +# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#confval-autodoc_member_order +# autodoc_member_order = 'bysource' diff --git a/pool/shard001/Python/0013995_CommonSearchBehavior.py b/pool/shard001/Python/0013995_CommonSearchBehavior.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7697a994bc87cf42b53920ceb919056610021e --- /dev/null +++ b/pool/shard001/Python/0013995_CommonSearchBehavior.py @@ -0,0 +1,148 @@ +import math +import random + +from time import time + +import util.TimeFormatter as TimeFormatter +import util.SimTimeRange as SimTimeRange + +DELTA_TIME = 0.5 + +class CommonSearchBehavior: + """ + Defines the common behavior for periodic actions generation. + """ + + def __init__(self, entries, nodePopulator, behaviorName): + self.__different = False + + self.__simultaneous = 0 + self.__absSimultaneous = 1 + self.__different = False + self.__searchDuration = 0 + self.__invalidSearches = 0 + + for entry in entries: + value = entry.firstChild.data + key = entry.getAttribute("key") + + if key == "searchFreq": + self.__searchFreq = float(value) + + if key == "finishTime": + self.__finishTime = float(value) + + if key == "discardTime": + self.__discardTime = float(value) + + if key == "nNodes": + self.__nNodes = int(value) + + if key == 'timeRange': + self.__timeRange = eval(value) + + if key == 'different': + self.__different = eval(value) + + if key == 'simultaneous': + self.__simultaneous = float(value) + + if key == 'absSimultaneous': + self.__absSimultaneous = int(value) + + if key == 'searchDuration': + self.__searchDuration = int(value) + + if key == 'invalidSearches': + self.__invalidSearches = float(value) + + self.__nodePopulator = nodePopulator + + self.__behaviorName = behaviorName + + if self.__searchFreq == 0: + self.__searchPeriod = 0.0 + else: + self.__searchPeriod = 1 / self.__searchFreq + + self.__searchTypes = [False] * self.getInvalidSearches() + self.__searchTypes += [True] * self.getValidSearches() + + def getNNodes(self): + return self.__nNodes + + def getNodePopulator(self): + return self.__nodePopulator + + def getBehaviorName(self): + return self.__behaviorName + + def mustBeDifferent(self): + return self.__different + + def generate(self, workingDir, oFile, strBuffer): + init, end = SimTimeRange.getTimeRange(self.__timeRange, self.__finishTime, self.__discardTime) + + strBuffer.writeln('') + strBuffer.writeln('************* %s ****************' % self.__behaviorName) + strBuffer.writeln('* Frequency: %.2f searches/s' % self.__searchFreq) + strBuffer.writeln('* Generated: %d sets of searches' % self.getSearches()) + strBuffer.writeln('* Time range: [%s, %s] s' % (init, end)) + strBuffer.writeln("* Simultaneous searches: %.2f" % (self.getSimultaneous())) + strBuffer.writeln("* Total searches: %d" % int(self.getSimultaneous() * self.getSearches())) + strBuffer.writeln("* Search duration: %d s" % self.__searchDuration) + strBuffer.writeln("* Invalid searches ratio: %.2f" % self.__invalidSearches) + strBuffer.writeln("* Generating %d invalid searches" % int(self.getInvalidSearches())) + self.printInfo(strBuffer) + + startTime = time() + + if self.__searchPeriod > 0.0: + #Create search events each specified period of time during specified time range + currentTime = init + DELTA_TIME + while (currentTime < end + DELTA_TIME): + self.perform(currentTime, oFile) + + #Increment time + currentTime += self.__searchPeriod + + if self.__searchDuration > 0: + self.finishSearches(self.__searchDuration, oFile) + + strBuffer.writeln('* Behavior generation time: %s ' % TimeFormatter.formatTime(time() - startTime)) + strBuffer.writeln('**********************************************************') + + def perform(self, time, oFile): + pass + + def finishSearches(self, searchDuration, oFile): + pass + + def printInfo(self, strBuffer): + pass + + def getElements(self): + pass + + def getSimultaneous(self): + if self.__simultaneous == 0: + return self.__absSimultaneous + else: + return int(self.__simultaneous * self.getNNodes()) + + def selectSearchType(self): + random.shuffle(self.__searchTypes) + return self.__searchTypes.pop() + + def getInvalidSearches(self): + return int(self.__invalidSearches * self.getTotalSearches()) + + def getValidSearches(self): + return self.getTotalSearches() - self.getInvalidSearches() + + def getSearches(self): + init, end = SimTimeRange.getTimeRange(self.__timeRange, self.__finishTime, self.__discardTime) + return int(math.ceil(self.__searchFreq * (end - init))) + + def getTotalSearches(self): + return int(self.getSimultaneous() * self.getSearches()) diff --git a/pool/shard001/Python/0013998_test_mlnx_plugin_config.py b/pool/shard001/Python/0013998_test_mlnx_plugin_config.py new file mode 100644 index 0000000000000000000000000000000000000000..70f3d2df494686ae36873394a7eee9ea5bded629 --- /dev/null +++ b/pool/shard001/Python/0013998_test_mlnx_plugin_config.py @@ -0,0 +1,89 @@ +# Copyright (c) 2014 OpenStack Foundation +# +# 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 mock +from oslo.config import cfg + +#NOTE this import loads tests required options +from neutron.plugins.mlnx.common import config # noqa +from neutron.plugins.mlnx.common import constants +from neutron.plugins.mlnx import mlnx_plugin +from neutron.tests import base + + +class TestMlnxPluginConfig(base.BaseTestCase): + expected_vlan_mappings = {'physnet1': [(1, 1000)], + 'physnet2': [(1, 1000)]} + expected_network_types = {'physnet1': constants.TYPE_ETH, + 'physnet2': constants.TYPE_IB} + config_vlan_ranges = ['physnet1:1:1000', 'physnet2:1:1000'] + config_network_types = ['physnet1:eth', 'physnet2:ib'] + + def setUp(self): + super(TestMlnxPluginConfig, self).setUp() + cfg.CONF.set_override('rpc_backend', + 'neutron.openstack.common.rpc.impl_fake') + cfg.CONF.set_override(group='MLNX', + name='network_vlan_ranges', + override=self.config_vlan_ranges) + + def _create_mlnx_plugin(self): + with mock.patch('neutron.plugins.mlnx.db.mlnx_db_v2'): + return mlnx_plugin.MellanoxEswitchPlugin() + + def _assert_expected_config(self): + plugin = self._create_mlnx_plugin() + self.assertEqual(plugin.network_vlan_ranges, + self.expected_vlan_mappings) + self.assertEqual(plugin.phys_network_type_maps, + self.expected_network_types) + + def test_vlan_ranges_with_network_type(self): + cfg.CONF.set_override(group='MLNX', + name='physical_network_type_mappings', + override=self.config_network_types) + self._assert_expected_config() + + def test_vlan_ranges_partial_network_type(self): + cfg.CONF.set_override(group='MLNX', + name='physical_network_type_mappings', + override=self.config_network_types[:1]) + cfg.CONF.set_override(group='MLNX', + name='physical_network_type', + override=constants.TYPE_IB) + self._assert_expected_config() + + def test_vlan_ranges_no_network_type(self): + cfg.CONF.set_override(group='MLNX', + name='physical_network_type', + override=constants.TYPE_IB) + cfg.CONF.set_override(group='MLNX', + name='physical_network_type_mappings', + override=[]) + self.expected_network_types.update({'physnet1': constants.TYPE_IB}) + self._assert_expected_config() + self.expected_network_types.update({'physnet1': constants.TYPE_ETH}) + + def test_parse_physical_network_mappings_invalid_type(self): + cfg.CONF.set_override(group='MLNX', + name='physical_network_type_mappings', + override=['physnet:invalid-type']) + self.assertRaises(SystemExit, self._create_mlnx_plugin) + + def test_invalid_network_type(self): + cfg.CONF.set_override(group='MLNX', + name='physical_network_type', + override='invalid-type') + self.assertRaises(SystemExit, self._create_mlnx_plugin) diff --git a/pool/shard001/Python/0013999_minpack2.py b/pool/shard001/Python/0013999_minpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9ff11fc7d888f3ace733a32f5e5c0feed99075 --- /dev/null +++ b/pool/shard001/Python/0013999_minpack2.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +import warnings +from . import _minpack2 + + +__all__ = [ # noqa: F822 + 'dcsrch', + 'dcstep', +] + + +def __getattr__(name): + if name not in __all__: + raise AttributeError( + "scipy.optimize.minpack2 is deprecated and has no attribute " + f"{name}. Try looking in scipy.optimize instead.") + + warnings.warn(f"Please use `{name}` from the `scipy.optimize` namespace, " + "the `scipy.optimize.minpack2` namespace is deprecated.", + category=DeprecationWarning, stacklevel=2) + + return getattr(_minpack2, name) diff --git a/pool/shard001/Python/0014000_plugin_pool.py b/pool/shard001/Python/0014000_plugin_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..5af0e3e2410c2b54183283f8bf66ec11ae25b9b8 --- /dev/null +++ b/pool/shard001/Python/0014000_plugin_pool.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +from operator import attrgetter + +from django.core.exceptions import ImproperlyConfigured +from django.conf.urls import url, patterns, include +from django.contrib.formtools.wizard.views import normalize_name +from django.db.models import signals +from django.template.defaultfilters import slugify +from django.utils import six +from django.utils.translation import get_language, deactivate_all, activate +from django.template import TemplateDoesNotExist, TemplateSyntaxError + +from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered +from cms.plugin_base import CMSPluginBase +from cms.models import CMSPlugin +from cms.utils.django_load import load +from cms.utils.helpers import reversion_register +from cms.utils.placeholder import get_placeholder_conf +from cms.utils.compat.dj import force_unicode, is_installed + + +class PluginPool(object): + def __init__(self): + self.plugins = {} + self.discovered = False + self.patched = False + + def discover_plugins(self): + if self.discovered: + return + from cms.views import invalidate_cms_page_cache + invalidate_cms_page_cache() + load('cms_plugins') + self.discovered = True + + def clear(self): + self.discovered = False + self.plugins = {} + self.patched = False + + def register_plugin(self, plugin): + """ + Registers the given plugin(s). + + If a plugin is already registered, this will raise PluginAlreadyRegistered. + """ + if not issubclass(plugin, CMSPluginBase): + raise ImproperlyConfigured( + "CMS Plugins must be subclasses of CMSPluginBase, %r is not." + % plugin + ) + if (plugin.render_plugin and not type(plugin.render_plugin) == property + or hasattr(plugin.model, 'render_template') + or hasattr(plugin, 'get_render_template')): + if (plugin.render_template is None and + not hasattr(plugin.model, 'render_template') and + not hasattr(plugin, 'get_render_template')): + raise ImproperlyConfigured( + "CMS Plugins must define a render template, " + "a get_render_template method or " + "set render_plugin=False: %s" % plugin + ) + # If plugin class defines get_render_template we cannot + # statically check for valid template file as it depends + # on plugin configuration and context. + # We cannot prevent developer to shoot in the users' feet + elif not hasattr(plugin, 'get_render_template'): + from django.template import loader + + template = ((hasattr(plugin.model, 'render_template') and + plugin.model.render_template) or + plugin.render_template) + if isinstance(template, six.string_types) and template: + try: + loader.get_template(template) + except TemplateDoesNotExist as e: + # Note that the template loader will throw + # TemplateDoesNotExist if the plugin's render_template + # does in fact exist, but it includes a template that + # doesn't. + if six.text_type(e) == template: + raise ImproperlyConfigured( + "CMS Plugins must define a render template (%s) that exists: %s" + % (plugin, template) + ) + else: + pass + except TemplateSyntaxError: + pass + else: + if plugin.allow_children: + raise ImproperlyConfigured( + "CMS Plugins can not define render_plugin=False and allow_children=True: %s" + % plugin + ) + plugin_name = plugin.__name__ + if plugin_name in self.plugins: + raise PluginAlreadyRegistered( + "Cannot register %r, a plugin with this name (%r) is already " + "registered." % (plugin, plugin_name) + ) + + plugin.value = plugin_name + self.plugins[plugin_name] = plugin + from cms.signals import pre_save_plugins, post_delete_plugins, pre_delete_plugins + + signals.pre_save.connect(pre_save_plugins, sender=plugin.model, + dispatch_uid='cms_pre_save_plugin_%s' % plugin_name) + signals.post_delete.connect(post_delete_plugins, sender=CMSPlugin, + dispatch_uid='cms_post_delete_plugin_%s' % plugin_name) + signals.pre_delete.connect(pre_delete_plugins, sender=CMSPlugin, + dispatch_uid='cms_pre_delete_plugin_%s' % plugin_name) + if is_installed('reversion'): + try: + from reversion.registration import RegistrationError + except ImportError: + from reversion.revisions import RegistrationError + try: + reversion_register(plugin.model) + except RegistrationError: + pass + + return plugin + + def unregister_plugin(self, plugin): + """ + Unregisters the given plugin(s). + + If a plugin isn't already registered, this will raise PluginNotRegistered. + """ + plugin_name = plugin.__name__ + if plugin_name not in self.plugins: + raise PluginNotRegistered( + 'The plugin %r is not registered' % plugin + ) + del self.plugins[plugin_name] + + def set_plugin_meta(self): + """ + Patches a plugin model by forcing a specifc db_table whether the + 'new style' table name exists or not. The same goes for all the + ManyToMany attributes. + This method must be run whenever a plugin model is accessed + directly. + + The model is modified in place; a 'patched' attribute is added + to the model to check whether it's already been modified. + """ + if self.patched: + return + self.patched = True + + def get_all_plugins(self, placeholder=None, page=None, setting_key="plugins", include_page_only=True): + self.discover_plugins() + self.set_plugin_meta() + plugins = sorted(self.plugins.values(), key=attrgetter('name')) + final_plugins = [] + template = page and page.get_template() or None + allowed_plugins = get_placeholder_conf( + setting_key, + placeholder, + template, + ) or () + for plugin in plugins: + include_plugin = False + if placeholder and not plugin.require_parent: + include_plugin = not allowed_plugins and setting_key == "plugins" or plugin.__name__ in allowed_plugins + if plugin.page_only and not include_page_only: + include_plugin = False + if include_plugin: + final_plugins.append(plugin) + + if final_plugins or placeholder: + plugins = final_plugins + + return sorted(plugins, key=attrgetter('module')) + + def get_text_enabled_plugins(self, placeholder, page): + plugins = self.get_all_plugins(placeholder, page) + plugins += self.get_all_plugins(placeholder, page, 'text_only_plugins') + return sorted((p for p in set(plugins) if p.text_enabled), + key=attrgetter('module', 'name')) + + def get_plugin(self, name): + """ + Retrieve a plugin from the cache. + """ + self.discover_plugins() + self.set_plugin_meta() + return self.plugins[name] + + def get_patterns(self): + self.discover_plugins() + + # We want untranslated name of the plugin for its slug so we deactivate translation + lang = get_language() + deactivate_all() + + try: + url_patterns = [] + for plugin in self.get_all_plugins(): + p = plugin() + slug = slugify(force_unicode(normalize_name(p.__class__.__name__))) + url_patterns += patterns('', + url(r'^plugin/%s/' % (slug,), include(p.plugin_urls)), + ) + finally: + # Reactivate translation + activate(lang) + + return url_patterns + + +plugin_pool = PluginPool() + diff --git a/pool/shard001/Python/0014006_score.py b/pool/shard001/Python/0014006_score.py new file mode 100644 index 0000000000000000000000000000000000000000..9d74dc69a7126d25f9b8074abf44b0d80570207c --- /dev/null +++ b/pool/shard001/Python/0014006_score.py @@ -0,0 +1,53 @@ +""" pip install pippi """ + +from pippi import dsp + +def make_cycles(length): + """ Well begun, half done """ + num_harmonics = dsp.randint(1, 6) + val_harmonics = [1, 2, 3, dsp.randint(4, 7), dsp.randint(5, 9)] + + # Each collection of partials + min_length = dsp.stf(10) + max_length = dsp.stf(18) + + root = 40.0 # hz + + # Deviate + root = root + dsp.rand() + + elapsed = 0 + cycles = [] + + # Count off + while elapsed < length: + cycle_length = dsp.randint(min_length, max_length) + + harmonics = [ + dsp.tone( + length=cycle_length, + freq=root * dsp.randchoose(val_harmonics), + amp=dsp.rand(0.1, 0.4), + wavetype='impulse' + ) + for h in range(num_harmonics) ] + + harmonics = [ dsp.pan(harmonic, dsp.rand()) for harmonic in harmonics ] + harmonics = [ dsp.env(harmonic, 'gauss') for harmonic in harmonics ] + + cycles += [ dsp.mix(harmonics) ] + elapsed += cycle_length + + return ''.join(cycles) + +cycles = [ make_cycles(dsp.stf(60 * 2)) for i in range(4) ] + +out = dsp.mix(cycles) +out = dsp.pine(out, dsp.stf(60 * 8), 80.0 * 2) + +cycles = [ make_cycles(dsp.stf(60 * 8)) for i in range(4) ] +cycles = dsp.mix(cycles) + +out = dsp.mix([ out, cycles ]) + +dsp.write(out, 'newly') diff --git a/pool/shard001/Python/0014007_maximum_collinear_points.py b/pool/shard001/Python/0014007_maximum_collinear_points.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5ca840f3d5c7d45b8864fc8629c27c730ac586 --- /dev/null +++ b/pool/shard001/Python/0014007_maximum_collinear_points.py @@ -0,0 +1,35 @@ +def maxPoints(A, B): + if not A or not B: return 0 + maxLen = 1 + for fp in xrange(len(A)-1): + dup = 1 + already_seen = {} + for sp in xrange(fp+1, len(A)): + if A[fp] == A[sp] and B[fp] == B[sp] and fp != sp: + dup += 1 + elif fp != sp: + if A[fp] == A[sp]: + already_seen['v'] = already_seen.get('v', 0) + 1 + elif B[fp] == B[sp]: + already_seen['h'] = already_seen.get('h', 0) + 1 + else: + slope = (1.0*(B[sp] - B[fp])) / (A[sp] - A[fp]) + already_seen[slope] = already_seen.get(slope, 0) + 1 + if len(already_seen) > 0: + maxLen = max(maxLen, max(already_seen.values()) + dup) + else: + maxLen = max(maxLen, dup) + return maxLen + + +A = [6, 5, 18, 2, 5, 2] +B = [17, 16, 17, 4, 13, 20] +"""A = [14, 17, 2, 13, 18, 9, 15, 2, 3, 7, 10, 14, 2, 18, 7, 12, 1, 9, 16, 4, 11, 4, 16, 17, 5, 8, 16, + 8, 5, 4, 16, 14, 12, 13, 2, 14, 9, 20, 5, 19, 16, 19, 3, 3, 1, 18, 19, 11, 16, 10, 12, 5, 1, 5, + 17, 20, 18, 15, 3, 5, 17, 14, 0, 0, 3, 10, 13, 10, 15, 2, 19, 14, 17, 4, 6, 1, 12] +B = [2, 3, 3, 5, 6, 10, 5, 11, 18, 1, 13, 6, 13, 14, 1, 19, 13, 2, 6, 3, 2, 2, 11, 5, 13, 18, 15, + 12, 5, 14, 2, 8, 4, 20, 1, 1, 16, 20, 9, 2, 0, 1, 4, 1, 20, 2, 9, 2, 10, 12, 4, 12, 3, 2, 3, 4, + 1, 10, 19, 17, 14, 7, 17, 5, 9, 13, 6, 18, 1, 2, 4, 6, 6, 3, 7, 18, 18]""" +#A = [20] +#B = [13] +print maxPoints(A, B) \ No newline at end of file diff --git a/pool/shard001/Python/0014008_base.py b/pool/shard001/Python/0014008_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fac73bf9f640352d04ed00a3287bdc2a5478006e --- /dev/null +++ b/pool/shard001/Python/0014008_base.py @@ -0,0 +1,69 @@ +from __future__ import absolute_import + +from fnmatch import fnmatch + +import logging +import os + +from flask import current_app + +from changes.config import db +from changes.db.utils import try_create +from changes.models.failurereason import FailureReason +from changes.storage.artifactstore import ARTIFACTSTORE_PREFIX + + +class ArtifactParseError(Exception): + pass + + +class ArtifactHandler(object): + FILENAMES = () + logger = logging.getLogger('artifacts') + + def __init__(self, step): + self.step = step + self.max_artifact_bytes = current_app.config['MAX_ARTIFACT_BYTES'] + + @staticmethod + def _sanitize_path(artifact_path): + # artifactstore prefix shouldn't be considered part of the path + if artifact_path.startswith(ARTIFACTSTORE_PREFIX): + artifact_path = artifact_path[len(ARTIFACTSTORE_PREFIX):] + return artifact_path + + @classmethod + def can_process(cls, filepath): + """ + Returns True if this handler can process the given artifact. + """ + filepath = ArtifactHandler._sanitize_path(filepath) + for pattern in cls.FILENAMES: + # we take a simplified gitignore-like approach, where if the + # pattern has a slash in it, we match it against the file path; + # otherwise we match against the basename. + if '/' in pattern: + # ignore starting slash + if pattern.startswith('/'): + pattern = pattern[1:] + if fnmatch(filepath, pattern): + return True + elif fnmatch(os.path.basename(filepath), pattern): + return True + return False + + def process(self, fp, artifact): + """ + Process the given artifact. + """ + + def report_malformed(self): + new_fr = try_create(FailureReason, { + 'step_id': self.step.id, + 'job_id': self.step.job_id, + 'build_id': self.step.job.build_id, + 'project_id': self.step.project_id, + 'reason': 'malformed_artifact' + }) + if new_fr: + db.session.commit() diff --git a/pool/shard001/Python/0014011_rest_views.py b/pool/shard001/Python/0014011_rest_views.py new file mode 100644 index 0000000000000000000000000000000000000000..b45bb1e37a542bcdda9baeefe1141e3bdde0c443 --- /dev/null +++ b/pool/shard001/Python/0014011_rest_views.py @@ -0,0 +1,43 @@ +import ipaddr + +from .serializers import SystemWithPersonalitySerializer + +from drunken_tyrion.models import System + +from rest_framework import viewsets, filters +from rest_framework.decorators import api_view, authentication_classes, renderer_classes +from rest_framework.response import Response +from rest_framework import authentication, permissions +from rest_framework.renderers import YAMLRenderer + + +class SystemViewSet(viewsets.ModelViewSet): + + model = System + serializer_class = SystemWithPersonalitySerializer + filter_backends = (filters.DjangoFilterBackend,) + filter_fields = ('slug', 'canonical_name') + + +@api_view(['GET']) +@authentication_classes((authentication.BasicAuthentication,)) +@renderer_classes((YAMLRenderer,)) +def puppet_view(request, nodename): + + try: + sys = System.objects.get(canonical_name=nodename) + except System.DoesNotExist: + return Response() + classes = {} + params = {} + for sp in sys.system_personalities.all(): + ph = sp.prepare_personality() + ph.puppet_func(classes, params) + + config_dict = {'classes': classes, 'params': params} + return Response(config_dict) + + + + + diff --git a/pool/shard001/Python/0014012_0002_auto_20170104_1720.py b/pool/shard001/Python/0014012_0002_auto_20170104_1720.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a410ffa3bc18aa1586041f6ef9f672ae5f08af --- /dev/null +++ b/pool/shard001/Python/0014012_0002_auto_20170104_1720.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-04 23:20 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('subprocuraduria', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='direccion', + name='usuarios', + field=models.ManyToManyField(to=settings.AUTH_USER_MODEL), + ), + migrations.AddField( + model_name='subprocuraduria', + name='usuarios', + field=models.ManyToManyField(to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/pool/shard001/Python/0014013_been_called_with.py b/pool/shard001/Python/0014013_been_called_with.py new file mode 100644 index 0000000000000000000000000000000000000000..6de0903c4028315bec862583c89b5a15f5952347 --- /dev/null +++ b/pool/shard001/Python/0014013_been_called_with.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +from ..decorators import mock_implementation_validator +from ..operator import Operator + + +class BeenCalledWithOperator(Operator): + """ + Asserts if a given mock subject have been called at least once + with specified arguments. + + Warning:: + + Piping style assertions is not yet supported. + + Example:: + + # Should style + should(mock).have.been_called_with('foo') + + # Should style - negation form + should(mock).have_not.been_called_with('foo', 10) + + # Expect style + expect(mock).to.have.been_called_with('foo') + + # Expect style - negation form + expect(mock).to.have_not.been_called_with('foo', True, 150) + expect(mock).to_not.have.been_called_with('foo') + """ + + # Is the operator a keyword + kind = Operator.Type.MATCHER + + # Disable diff report + show_diff = False + + # Operator keywords + operators = ('been_called_with',) + + # Error message templates + expected_message = Operator.Dsl.Message( + 'a mock that has been called at least once with arguments', + 'a mock that has not been called with arguments', + ) + + # Subject message template + subject_message = Operator.Dsl.Message( + 'a mock that has not been called with arguments', + 'a mock that has been called at least once with arguments', + ) + + @mock_implementation_validator + def match(self, subject, *args, **kwargs): + try: + subject.assert_called_with(*args, **kwargs) + return True + except AssertionError as error: + return False, error.args[0].splitlines() + + +class BeenCalledOnceWithOperator(Operator): + """ + Asserts if a given mock subject have been called once + with specified arguments. + + Warning:: + + Piping style assertions is not yet supported. + + Example:: + + # Should style + should(mock).have.been_called_once_with('foo') + + # Should style - negation form + should(mock).have_not.been_called_once_with('foo', 10) + + # Expect style + expect(mock).to.have.been_called_once_with('foo') + + # Expect style - negation form + expect(mock).to.have_not.been_called_once_with('foo', True, 150) + expect(mock).to_not.have.been_called_once_with('foo') + """ + + # Is the operator a keyword + kind = Operator.Type.MATCHER + + # Disable diff report + show_diff = False + + # Operator keywords + operators = ('been_called_once_with',) + + # Error message templates + expected_message = Operator.Dsl.Message( + 'a mock that has been called once with arguments', + 'a mock that has not been called once with arguments', + ) + + # Subject message template + subject_message = Operator.Dsl.Message( + 'a mock that has been called {call_count} time(s) with arguments', + 'a mock that has been called once with arguments', + ) + + @mock_implementation_validator + def match(self, subject, *args, **kwargs): + try: + subject.assert_called_once_with(*args, **kwargs) + return True + except AssertionError as error: + return False, error.args[0].splitlines() diff --git a/pool/shard001/Python/0014014_test_dockerhub.py b/pool/shard001/Python/0014014_test_dockerhub.py new file mode 100644 index 0000000000000000000000000000000000000000..78df7a3847421226449887c68955e2299acdfe61 --- /dev/null +++ b/pool/shard001/Python/0014014_test_dockerhub.py @@ -0,0 +1,217 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2015-2019 Bitergia +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA. +# +# Authors: +# Santiago Dueñas +# + +import datetime +import os +import shutil +import unittest +import unittest.mock + +import dateutil +import httpretty +import pkg_resources + +from grimoirelab_toolkit.uris import urijoin + +pkg_resources.declare_namespace('perceval.backends') + +from perceval.backend import BackendCommandArgumentParser +from perceval.backends.core.dockerhub import (DockerHub, + DockerHubClient, + DockerHubCommand) +from base import TestCaseBackendArchive + +DOCKERHUB_URL = "https://hub.docker.com/" +DOCKERHUB_API_URL = DOCKERHUB_URL + 'v2' +DOCKERHUB_RESPOSITORY_URL = DOCKERHUB_API_URL + '/repositories/grimoirelab/perceval' + + +def read_file(filename, mode='r'): + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename), mode) as f: + content = f.read() + return content + + +def setup_http_server(): + """Setup a mock HTTP server""" + + body = read_file('data/dockerhub/dockerhub_repository_1.json', 'rb') + + httpretty.register_uri(httpretty.GET, + DOCKERHUB_RESPOSITORY_URL, + body=body, status=200) + + +class TestDockerHubBackend(unittest.TestCase): + """DockerHub backend tests""" + + def test_initialization(self): + """Test whether attributes are initializated""" + + dockerhub = DockerHub('grimoirelab', 'perceval', tag='test') + + expected_origin = urijoin(DOCKERHUB_URL, 'grimoirelab', 'perceval') + + self.assertEqual(dockerhub.owner, 'grimoirelab') + self.assertEqual(dockerhub.repository, 'perceval') + self.assertEqual(dockerhub.origin, expected_origin) + self.assertEqual(dockerhub.tag, 'test') + self.assertIsNone(dockerhub.client) + + # When tag is empty or None it will be set to + # the value in + dockerhub = DockerHub('grimoirelab', 'perceval') + self.assertEqual(dockerhub.origin, expected_origin) + self.assertEqual(dockerhub.tag, expected_origin) + + dockerhub = DockerHub('grimoirelab', 'perceval', tag='') + self.assertEqual(dockerhub.origin, expected_origin) + self.assertEqual(dockerhub.tag, expected_origin) + + def test_shortcut_official_owner(self): + """Test if the shortcut owner is replaced when it is given on init""" + + # Value '_' should be replaced by 'library' + dockerhub = DockerHub('_', 'redis', tag='test') + + expected_origin = urijoin(DOCKERHUB_URL, 'library', 'redis') + + self.assertEqual(dockerhub.owner, 'library') + self.assertEqual(dockerhub.repository, 'redis') + self.assertEqual(dockerhub.origin, expected_origin) + + def test_has_archiving(self): + """Test if it returns True when has_archiving is called""" + + self.assertEqual(DockerHub.has_archiving(), True) + + def test_has_resuming(self): + """Test if it returns True when has_resuming is called""" + + self.assertEqual(DockerHub.has_resuming(), True) + + @httpretty.activate + @unittest.mock.patch('perceval.backends.core.dockerhub.datetime_utcnow') + def test_fetch(self, mock_utcnow): + """Test whether it fetches data from a repository""" + + mock_utcnow.return_value = datetime.datetime(2017, 1, 1, + tzinfo=dateutil.tz.tzutc()) + setup_http_server() + + dockerhub = DockerHub('grimoirelab', 'perceval') + items = [item for item in dockerhub.fetch()] + + self.assertEqual(len(items), 1) + item = items[0] + self.assertEqual(item['data']['fetched_on'], 1483228800.0) + self.assertEqual(item['uuid'], '0fa16dc4edab9130a14914a8d797f634d13b4ff4') + self.assertEqual(item['origin'], 'https://hub.docker.com/grimoirelab/perceval') + self.assertEqual(item['updated_on'], 1483228800.0) + self.assertEqual(item['category'], 'dockerhub-data') + self.assertEqual(item['tag'], 'https://hub.docker.com/grimoirelab/perceval') + + # Check requests + self.assertEqual(len(httpretty.httpretty.latest_requests), 1) + + def test_parse_json(self): + """Test if it parses a JSON stream""" + + raw_json = read_file('data/dockerhub/dockerhub_repository_1.json') + + item = DockerHub.parse_json(raw_json) + self.assertEqual(item['user'], 'grimoirelab') + self.assertEqual(item['name'], 'perceval') + + +class TestDockerHubBackendArchive(TestCaseBackendArchive): + """DockerHub backend tests using an archive""" + + def setUp(self): + super().setUp() + self.backend_write_archive = DockerHub('grimoirelab', 'perceval', archive=self.archive) + self.backend_read_archive = DockerHub('grimoirelab', 'perceval', archive=self.archive) + + def tearDown(self): + shutil.rmtree(self.test_path) + + @httpretty.activate + @unittest.mock.patch('perceval.backends.core.dockerhub.datetime_utcnow') + def test_fetch_from_archive(self, mock_utcnow): + """Test whether it fetches data from a repository""" + + mock_utcnow.return_value = datetime.datetime(2017, 1, 1, + tzinfo=dateutil.tz.tzutc()) + setup_http_server() + self._test_fetch_from_archive() + + +class TestDockerHubClient(unittest.TestCase): + """DockerHub API client tests. + + These tests do not check the body of the response, only if the call + was well formed and if a response was obtained. Due to this, take + into account that the body returned on each request might not + match with the parameters from the request. + """ + @httpretty.activate + def test_repository(self): + """Test repository API call""" + + # Set up a mock HTTP server + setup_http_server() + + # Call API + client = DockerHubClient() + response = client.repository('grimoirelab', 'perceval') + + req = httpretty.last_request() + + self.assertEqual(req.method, 'GET') + self.assertRegex(req.path, '/v2/repositories/grimoirelab/perceval') + self.assertDictEqual(req.querystring, {}) + + +class TestDockerHubCommand(unittest.TestCase): + """Tests for DockerHubCommand class""" + + def test_backend_class(self): + """Test if the backend class is DockerHub""" + + self.assertIs(DockerHubCommand.BACKEND, DockerHub) + + def test_setup_cmd_parser(self): + """Test if it parser object is correctly initialized""" + + parser = DockerHubCommand.setup_cmd_parser() + self.assertIsInstance(parser, BackendCommandArgumentParser) + + args = ['grimoirelab', 'perceval', '--no-archive'] + + parsed_args = parser.parse(*args) + self.assertEqual(parsed_args.no_archive, True) + self.assertEqual(parsed_args.owner, 'grimoirelab') + self.assertEqual(parsed_args.repository, 'perceval') + + +if __name__ == "__main__": + unittest.main(warnings='ignore') diff --git a/pool/shard001/Python/0014016_text.py b/pool/shard001/Python/0014016_text.py new file mode 100644 index 0000000000000000000000000000000000000000..ddd687933ef3b32136c4b59ff9d38794294d15e2 --- /dev/null +++ b/pool/shard001/Python/0014016_text.py @@ -0,0 +1,77 @@ +# -*- coding: UTF-8 -*- +# Copyright (C) 2003-2007 J. David Ibáñez +# Copyright (C) 2008-2009 Henry Obein +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# Import from itools +from file import File +from registry import register_handler_class + + +def guess_encoding(data): + """Tries to guess the encoding by brute force. It is likely to get + the wrong encoding, for example many utf8 files will be identified + as latin1. + """ + for encoding in ('ascii', 'utf8', 'iso8859'): + try: + unicode(data, encoding) + except UnicodeError: + pass + else: + return encoding + + # Default to UTF-8 + return 'utf8' + + +class TextFile(File): + + class_mimetypes = ['text'] + class_extension = 'txt' + + + def new(self, data=u''): + self.data = data + self.encoding = 'utf-8' + + + def _load_state_from_file(self, file): + data = file.read() + self.encoding = guess_encoding(data) + self.data = unicode(data, self.encoding) + + + ######################################################################### + # API + ######################################################################### + def get_encoding(self): + return self.encoding + + + def to_str(self, encoding='utf-8'): + return self.data.encode(encoding) + + + def to_text(self): + return unicode(self.to_str(), 'utf-8') + + + def is_empty(self): + return self.to_text().strip() == u"" + + + +register_handler_class(TextFile) diff --git a/pool/shard001/Python/0014017_package.py b/pool/shard001/Python/0014017_package.py new file mode 100644 index 0000000000000000000000000000000000000000..37bfd87a31072564f6b49785992503f31851a127 --- /dev/null +++ b/pool/shard001/Python/0014017_package.py @@ -0,0 +1,53 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License (as +# published by the Free Software Foundation) version 2.1, February 1999. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class Findutils(AutotoolsPackage): + """The GNU Find Utilities are the basic directory searching + utilities of the GNU operating system.""" + + homepage = "https://www.gnu.org/software/findutils/" + url = "http://ftpmirror.gnu.org/findutils/findutils-4.6.0.tar.gz" + + version('4.6.0', '9936aa8009438ce185bea2694a997fc1') + version('4.4.2', '351cc4adb07d54877fa15f75fb77d39f') + version('4.4.1', '5883f569dc021eee765f330bb7a3782d') + version('4.4.0', '49e769ac4382fae6f104f99d54d0a112') + version('4.2.33', 'b7e35aa175778c84942b1fee4144988b') + version('4.2.32', 'aaa6beeb41a6f04963dff58f24a55b96') + version('4.2.31', 'a0e31a0f18a49709bf5a449867c8049a') + version('4.2.30', 'c35ff6502e0b3514c99089cb5d333c25') + version('4.2.29', '24e76434ca74ba3c2c6ad621eb64e1ff') + version('4.2.28', 'f5fb3349354ee3d94fceb81dab5c71fd') + version('4.2.27', 'f1e0ddf09f28f8102ff3b90f3b5bc920') + version('4.2.26', '9ac4e62937b1fdc4eb643d1d4bf117d3') + version('4.2.25', 'e92fef6714ffa9972f28a1a423066921') + version('4.2.23', 'ecaff8b060e8d69c10eb2391a8032e26') + version('4.2.20', '7c8e12165b221dd67a19c00d780437a4') + version('4.2.18', '8aac2498435f3f1882678fb9ebda5c34') + version('4.2.15', 'a881b15aa7170aea045bf35cc92d48e7') + version('4.1.20', 'e90ce7222daadeb8616b8db461e17cbc') + version('4.1', '3ea8fe58ef5386da75f6c707713aa059') diff --git a/pool/shard001/Python/0014031_run_queries.py b/pool/shard001/Python/0014031_run_queries.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d0dc0d436e8a967775dce2346a36c64a6749b8 --- /dev/null +++ b/pool/shard001/Python/0014031_run_queries.py @@ -0,0 +1,13 @@ +import random +from energy_app.models import * + +def run_queries(): + print "Running queries" + queries = Query.objects.all() + chunks = PowerChunk.objects.all() + for query in queries: + print query + for pc in PowerChunk.objects.filter(amount__lte=query.needed_power).order_by('-amount','total_cost'): + print pc + +run_queries() \ No newline at end of file diff --git a/pool/shard001/Python/0014035_server.py b/pool/shard001/Python/0014035_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b29a3c1be90190baa5ff04900bbff95da16c69fa --- /dev/null +++ b/pool/shard001/Python/0014035_server.py @@ -0,0 +1,52 @@ +"""A device based server.""" + +# +# Copyright (c) 2010 Brian E. Granger and Eugene Chernyshov +# +# This file is part of pyzmq. +# +# pyzmq is free software; you can redistribute it and/or modify it under +# the terms of the Lesser GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# pyzmq is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# Lesser GNU General Public License for more details. +# +# You should have received a copy of the Lesser GNU General Public License +# along with this program. If not, see . + +import zmq +import os +import threading +import time + +print 'Server', os.getpid() + +def routine(context): + socket = context.socket(zmq.REP) + + socket.connect("inproc://workers") + + while True: + message = socket.recv() + time.sleep(1) + socket.send(message) + +context = zmq.Context(1) + +workers = context.socket(zmq.DEALER) +workers.bind("inproc://workers"); + +clients = context.socket(zmq.DEALER) +clients.bind('tcp://127.0.0.1:5555') + +for i in range(10): + thread = threading.Thread(target=routine, args=(context, )) + thread.start() + +zmq.device(zmq.QUEUE, clients, workers) + +print "Finished" diff --git a/pool/shard001/Python/0014039_restore.py b/pool/shard001/Python/0014039_restore.py new file mode 100644 index 0000000000000000000000000000000000000000..7c715b680b119a763ba10af583d1027b6a48d0b6 --- /dev/null +++ b/pool/shard001/Python/0014039_restore.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +# This is a Python dump created using dump2py. +# DJANGO_SETTINGS_MODULE was 'lino_book.projects.dumps.settings.b', TIME_ZONE was 'Europe/Tallinn'. + + +from __future__ import unicode_literals + +import logging +logger = logging.getLogger('lino.management.commands.dump2py') + +SOURCE_VERSION = 'None' + +import os +import six +from decimal import Decimal +from datetime import datetime +from datetime import time, date +from django.conf import settings +from django.utils.timezone import make_aware, utc +from django.core.management import call_command +# from django.contrib.contenttypes.models import ContentType +from lino.utils.dpy import create_mti_child +from lino.utils.dpy import DpyLoader +from lino.core.utils import resolve_model + +if settings.USE_TZ: + def dt(*args): + return make_aware(datetime(*args), timezone=utc) +else: + def dt(*args): + return datetime(*args) + +def new_content_type_id(m): + if m is None: return m + ct = settings.SITE.models.contenttypes.ContentType.objects.get_for_model(m) + if ct is None: return None + return ct.pk + +def pmem(): + # Thanks to https://stackoverflow.com/questions/938733/total-memory-used-by-python-process + process = psutil.Process(os.getpid()) + print(process.memory_info().rss) + +def execfile(fn, *args): + logger.info("Execute file %s ...", fn) + six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args) + # pmem() # requires pip install psutil + + +def bv2kw(fieldname, values): + """ + Needed if `Site.languages` changed between dumpdata and loaddata + """ + return settings.SITE.babelkw(fieldname, en=values[0],de=values[1],fr=values[2]) + +dumps_Foo = resolve_model("dumps.Foo") + + +def create_dumps_foo(id, designation, last_visit, bar): +# if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar) + kw = dict() + kw.update(id=id) + if designation is not None: kw.update(bv2kw('designation',designation)) + kw.update(last_visit=last_visit) + kw.update(bar=bar) + return dumps_Foo(**kw) + + + + +def main(args): + loader = DpyLoader(globals()) + from django.core.management import call_command + call_command('initdb', interactive=args.interactive) + os.chdir(os.path.dirname(__file__)) + loader.initialize() + args = (globals(), locals()) + + execfile("dumps_foo_1.py", *args) + execfile("dumps_foo_2.py", *args) + loader.finalize() + logger.info("Loaded %d objects", loader.count_objects) + call_command('resetsequences') + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description='Restore the data.') + parser.add_argument('--noinput', dest='interactive', + action='store_false', default=True, + help="Don't ask for confirmation before flushing the database.") + + args = parser.parse_args() + main(args) diff --git a/pool/shard001/Python/0014041_flashNRF51.py b/pool/shard001/Python/0014041_flashNRF51.py new file mode 100644 index 0000000000000000000000000000000000000000..67f3272487c0551c43141f5ec2f5689f75756483 --- /dev/null +++ b/pool/shard001/Python/0014041_flashNRF51.py @@ -0,0 +1,60 @@ +#!/usr/bin/python + +import time +import sys +import array + +from PirateSWD import * +from SWDCommon import * +from RpiGPIO import * + +def loadFile(path): + arr = array.array('I') + try: + arr.fromfile(open(sys.argv[1], 'rb'), 1024*1024) + except EOFError: + pass + return arr.tolist() + +def main(): + busPirate = RpiSWD("", vreg = True) + debugPort = DebugPort(busPirate) + efm32 = EFM32(debugPort) + + part_info = efm32.ahb.readWord(0x0FE081FC) # PART_NUMBER, PART_FAMILY, PROD_REV + mem_info = efm32.ahb.readWord(0x0FE081F8) # MEM_INFO_FLASH, MEM_INFO_RAM + rev = (efm32.ahb.readWord(0xE00FFFE8) & 0xF0) | ((efm32.ahb.readWord(0xE00FFFEC) & 0xF0) >> 4) # PID2 and PID3 - see section 7.3.4 in reference manual + rev = chr(rev + ord('A')) + flash_size = mem_info & 0xFFFF + if (part_info >> 16 & 0xFF) == 71: + print "Connected." + print "Part number: EFM32G%dF%d (rev %c, production ID %dd)" % (part_info & 0xFF, + flash_size, rev, part_info >> 24 & 0xFF) + else: + print "Warning: unknown part" + sys.exit() + print "Loading '%s'..." % sys.argv[1], + vals = loadFile(sys.argv[1]) + size = len(vals) * 4 + print "%d bytes." % size + if size / 1024.0 > flash_size: + print "Firmware will not fit into flash!" + sys.exit(1) + + efm32.halt() + efm32.flashUnlock() + print "Erasing Flash...", + efm32.flashErase(flash_size) + start_time = time.time() + print "Programming Flash...", + efm32.flashProgram(vals) + time_passed = time.time() - start_time + print "Programmed %d bytes in %.2f seconds (%.2f kB/sec)." % (size, + time_passed, (size / 1024.0) / time_passed) + + print "Resetting" + efm32.sysReset() + busPirate.tristatePins() + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0014043_push.py b/pool/shard001/Python/0014043_push.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1d4dadb4dedd9ad4da1882f678c33130daed16 --- /dev/null +++ b/pool/shard001/Python/0014043_push.py @@ -0,0 +1,132 @@ +import argparse +import os +import base64 +import tempfile +import requests + +from cnrclient.pack import pack_kub +from cnrclient.utils import package_filename +from cnrclient.commands.command_base import CommandBase, PackageSplit +from cnrclient.formats.helm.manifest_chart import ManifestChart +from cnrclient.formats import detect_format + + +class PushCmd(CommandBase): + name = 'push' + help_message = "push a package to the registry" + default_media_type = None + + def __init__(self, options): + super(PushCmd, self).__init__(options) + self.registry_host = options.registry_host + self.force = options.force + self.manifest = None + self.media_type = options.media_type + self.channel = options.channel + self.version = options.version + self.filter_files = True + self.metadata = None + self.prefix = None + self.manifest_name = None + self.package_name = options.package + self.package_parts = options.package_parts + self.pname = self.package_parts.get('package', None) + self.namespace = self.package_parts.get('namespace', None) + if self.namespace is None: + self.namespace = options.ns + self.version_parts = options.version_parts + if self.version == "default": + self.version = None + self.status = '' + + @classmethod + def _add_arguments(cls, parser): + cls._add_registryhost_option(parser) + cls._add_mediatype_option(parser, cls.default_media_type, required=False) + cls._add_packageversion_option(parser) + parser.add_argument("--ns", "--namespace", default=None, help=argparse.SUPPRESS) + parser.add_argument("-f", "--force", action='store_true', default=False, help="force push") + parser.add_argument("-c", "--channel", default=None, help="Set a channel") + parser.add_argument("--version-parts", default={}, help=argparse.SUPPRESS) + parser.add_argument("--package-parts", default={}, help=argparse.SUPPRESS) + + parser.add_argument('package', nargs='?', default=None, action=PackageSplit, + help="repository dest") + + def _push(self): + client = self.RegistryClient(self.registry_host) + filename = package_filename(self.package_name, self.version, self.media_type) + kubepath = os.path.join(tempfile.gettempdir(), filename + ".tar.gz") + pack_kub(kubepath, filter_files=self.filter_files, prefix=self.prefix) + kubefile = open(kubepath, 'rb') + body = { + "manifest_name": self.manifest_name, + "name": self.package_name, + "release": self.version, + "metadata": self.metadata, + "media_type": self.media_type, + "blob": base64.b64encode(kubefile.read()) + } + try: + client.push(self.package_name, body, self.force) + self.status = "package: %s (%s | %s) pushed\n" % (self.package_name, self.version, + self.media_type) + except requests.exceptions.RequestException as exc: + if not (self.channel and exc.response.status_code in [409, 400]): + raise + kubefile.close() + os.remove(kubepath) + if self.channel: + client.create_channel_release(self.package_name, self.channel, self.version) + self.status += ">>> Release '%s' added to '%s'" % (self.version, self.channel) + + def _chart(self): + self.manifest = ManifestChart() + self.manifest_name = self.manifest.name + if self.pname is None: + self.pname = self.manifest.name + self.prefix = self.pname + self.filter_files = False + if self.namespace is None: + raise argparse.ArgumentTypeError("Missing option: --namespace") + self.package_name = "%s/%s" % (self.namespace, self.pname) + if self.version is None: + self.version = self.manifest.version + self.metadata = self.manifest.metadata() + + def _all_formats(self): + self.filter_files = False + if self.version is None or self.version == "default": + raise argparse.ArgumentTypeError("Missing option: --version") + if self.package_name is None: + raise argparse.ArgumentTypeError("Missing option: --name") + self.namespace, self.pname = self.package_name.split("/") + + def _kpm(self): + raise NotImplementedError + + def _init(self): + if self.media_type is None: + self.media_type = detect_format(".").media_type + if self.media_type in ["kpm", "kpm-compose"]: + self._kpm() + elif self.media_type in ['helm', 'chart']: + self._chart() + else: + self._all_formats() + + def _call(self): + self._init() + self._push() + + def _render_dict(self): + return { + "manifest_name": self.manifest_name, + "package": self.package_name, + "version": self.version, + "media_type": self.media_type, + "channel": self.channel + } + + def _render_console(self): + return self.status diff --git a/pool/shard001/Python/0014044_test_flatpages.py b/pool/shard001/Python/0014044_test_flatpages.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6f58e77e0f125d379e3d097f63bbd8f3309d0c --- /dev/null +++ b/pool/shard001/Python/0014044_test_flatpages.py @@ -0,0 +1,62 @@ +from __future__ import unicode_literals + +from unittest import skipUnless +import warnings + +from django.apps import apps +from django.conf import settings +from django.contrib.sitemaps import FlatPageSitemap +from django.test import SimpleTestCase + +from .base import SitemapTestsBase + + +class FlatpagesSitemapTests(SitemapTestsBase): + + @skipUnless(apps.is_installed('django.contrib.flatpages'), + "django.contrib.flatpages app not installed.") + def test_flatpage_sitemap(self): + "Basic FlatPage sitemap test" + + # Import FlatPage inside the test so that when django.contrib.flatpages + # is not installed we don't get problems trying to delete Site + # objects (FlatPage has an M2M to Site, Site.delete() tries to + # delete related objects, but the M2M table doesn't exist. + from django.contrib.flatpages.models import FlatPage + + public = FlatPage.objects.create( + url='/public/', + title='Public Page', + enable_comments=True, + registration_required=False, + ) + public.sites.add(settings.SITE_ID) + private = FlatPage.objects.create( + url='/private/', + title='Private Page', + enable_comments=True, + registration_required=True + ) + private.sites.add(settings.SITE_ID) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + response = self.client.get('/flatpages/sitemap.xml') + # Public flatpage should be in the sitemap + self.assertContains(response, '%s%s' % (self.base_url, public.url)) + # Private flatpage should not be in the sitemap + self.assertNotContains(response, '%s%s' % (self.base_url, private.url)) + + +class FlatpagesSitemapDeprecationTests(SimpleTestCase): + + def test_deprecation(self): + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter('always') + FlatPageSitemap() + + self.assertEqual(len(warns), 1) + self.assertEqual( + str(warns[0].message), + "'django.contrib.sitemaps.FlatPageSitemap' is deprecated. " + "Use 'django.contrib.flatpages.sitemaps.FlatPageSitemap' instead.", + ) diff --git a/pool/shard001/Python/0014045_tuple.py b/pool/shard001/Python/0014045_tuple.py new file mode 100644 index 0000000000000000000000000000000000000000..85b3a2a612506b660db0fcd4c506d38c2711a762 --- /dev/null +++ b/pool/shard001/Python/0014045_tuple.py @@ -0,0 +1,94 @@ +# Copyright 2016 Twitter. 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. +'''tuple.py: heron's default data type''' + +import time +import random + +from collections import namedtuple + +StreamParseTuple = namedtuple('Tuple', 'id component stream task values') +"""Storm's primitive data type passed around via streams. + +:ivar id: the ID of the Tuple +:type id: str +:ivar component: component that the Tuple was generated from. +:type component: str +:ivar stream: the stream that the Tuple was emitted into. +:type stream: str +:ivar task: the task the Tuple was generated from. +:type task: int +:ivar values: the payload of the Tuple where data is stored. +:type values: tuple +""" + +HeronTuple = namedtuple('Tuple', StreamParseTuple._fields + ('creation_time', 'roots')) +"""StreamParse compatible Heron Tuple + +:ivar id: the ID of the Tuple +:type id: str +:ivar component: component that the Tuple was generated from. +:type component: str +:ivar stream: the stream that the Tuple was emitted into. +:type stream: str +:ivar task: the task the Tuple was generated from. +:type task: int +:ivar values: the payload of the Tuple where data is stored. +:type values: tuple or list +:ivar creation_time: the time the Tuple was created +:type creation_time: float +:ivar roots: a list of RootId (protobuf) +:type roots: list +""" + +class RootTupleInfo(namedtuple('RootTupleInfo', 'stream_id tuple_id insertion_time key')): + __slots__ = () + def is_expired(self, current_time, timeout_sec): + return self.insertion_time + timeout_sec - current_time <= 0 + +class TupleHelper(object): + """Tuple generator, returns StreamParse compatible tuple""" + TICK_TUPLE_ID = "__tick" + TICK_SOURCE_COMPONENT = "__system" + + #last three bits are used for type + MAX_SFIXED64_RAND_BITS = 61 + + @staticmethod + def make_tuple(stream, tuple_key, values, roots=None): + """Creates a HeronTuple + + :param stream: protobuf message ``StreamId`` + :param tuple_key: tuple id + :param values: a list of values + :param roots: a list of protobuf message ``RootId`` + """ + component_name = stream.component_name + stream_id = stream.id + gen_task = roots[0].taskid if roots is not None and len(roots) > 0 else None + return HeronTuple(id=str(tuple_key), component=component_name, stream=stream_id, + task=gen_task, values=values, creation_time=time.time(), roots=roots) + @staticmethod + def make_tick_tuple(): + """Creates a TickTuple""" + return HeronTuple(id=TupleHelper.TICK_TUPLE_ID, component=TupleHelper.TICK_SOURCE_COMPONENT, + stream=TupleHelper.TICK_TUPLE_ID, task=None, values=None, + creation_time=time.time(), roots=None) + + @staticmethod + def make_root_tuple_info(stream_id, tuple_id): + """Creates a RootTupleInfo""" + key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS) + return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id, + insertion_time=time.time(), key=key) diff --git a/pool/shard001/Python/0014046_sensor.py b/pool/shard001/Python/0014046_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..094fa8aadbb2b1d9670b4eb087ae7a013ba2230a --- /dev/null +++ b/pool/shard001/Python/0014046_sensor.py @@ -0,0 +1,84 @@ +"""Support for Blink system camera sensors.""" +from __future__ import annotations + +import logging + +from homeassistant.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorEntityDescription, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import SIGNAL_STRENGTH_DECIBELS_MILLIWATT, TEMP_FAHRENHEIT +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity import DeviceInfo, EntityCategory +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .const import DEFAULT_BRAND, DOMAIN, TYPE_TEMPERATURE, TYPE_WIFI_STRENGTH + +_LOGGER = logging.getLogger(__name__) + +SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( + SensorEntityDescription( + key=TYPE_TEMPERATURE, + name="Temperature", + native_unit_of_measurement=TEMP_FAHRENHEIT, + device_class=SensorDeviceClass.TEMPERATURE, + entity_category=EntityCategory.DIAGNOSTIC, + ), + SensorEntityDescription( + key=TYPE_WIFI_STRENGTH, + name="Wifi Signal", + native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + entity_category=EntityCategory.DIAGNOSTIC, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddEntitiesCallback +) -> None: + """Initialize a Blink sensor.""" + data = hass.data[DOMAIN][config.entry_id] + entities = [ + BlinkSensor(data, camera, description) + for camera in data.cameras + for description in SENSOR_TYPES + ] + + async_add_entities(entities) + + +class BlinkSensor(SensorEntity): + """A Blink camera sensor.""" + + def __init__(self, data, camera, description: SensorEntityDescription): + """Initialize sensors from Blink camera.""" + self.entity_description = description + self._attr_name = f"{DOMAIN} {camera} {description.name}" + self.data = data + self._camera = data.cameras[camera] + self._attr_unique_id = f"{self._camera.serial}-{description.key}" + self._sensor_key = ( + "temperature_calibrated" + if description.key == "temperature" + else description.key + ) + self._attr_device_info = DeviceInfo( + identifiers={(DOMAIN, self._camera.serial)}, + name=camera, + manufacturer=DEFAULT_BRAND, + model=self._camera.camera_type, + ) + + def update(self): + """Retrieve sensor data from the camera.""" + self.data.refresh() + try: + self._attr_native_value = self._camera.attributes[self._sensor_key] + except KeyError: + self._attr_native_value = None + _LOGGER.error( + "%s not a valid camera attribute. Did the API change?", self._sensor_key + ) diff --git a/pool/shard001/Python/0014048_config.py b/pool/shard001/Python/0014048_config.py new file mode 100644 index 0000000000000000000000000000000000000000..896b924479f29294199a5518e1df44a7f0381ca4 --- /dev/null +++ b/pool/shard001/Python/0014048_config.py @@ -0,0 +1,192 @@ +# Copyright 2004-2008 Roman Yakovenko. +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +"""This module contains the implementation of the L{config_t} class. +""" + +import os +import sys +import copy + +class parser_configuration_t(object): + """Configuration object to collect parameters for invoking C++ parser + + This class serves as a base class for the parameters that can be used + to customize the call to C++ parser. This class also allows users to work with + relative files paths. In this case files are searched in the following order: + + 1. current directory + + 2. working directory + + 3. additional include paths specified by the user + + """ + def __init__( self + , working_directory='.' + , include_paths=None + , define_symbols=None + , undefine_symbols=None + , cflags="" + , compiler=None): + """Constructor. + """ + object.__init__( self ) + self.__working_directory = working_directory + + if not include_paths: + include_paths = [] + self.__include_paths = include_paths + + if not define_symbols: + define_symbols = [] + self.__define_symbols = define_symbols + + if not undefine_symbols: + undefine_symbols = [] + self.__undefine_symbols = undefine_symbols + + self.__cflags = cflags + + self.__compiler = compiler + + def clone(self): + raise NotImplementedError( self.__class__.__name__ ) + + def __get_working_directory(self): + return self.__working_directory + def __set_working_directory(self, working_dir): + self.__working_directory=working_dir + working_directory = property( __get_working_directory, __set_working_directory ) + + @property + def include_paths(self): + """list of include paths to look for header files""" + return self.__include_paths + + @property + def define_symbols(self): + """list of "define" directives """ + return self.__define_symbols + + @property + def undefine_symbols(self): + """list of "undefine" directives """ + return self.__undefine_symbols + + @property + def compiler(self): + """compiler name to simulate""" + return self.__compiler + + def __get_cflags(self): + return self.__cflags + def __set_cflags(self, val): + self.__cflags = val + cflags = property( __get_cflags, __set_cflags + , doc="additional flags to pass to compiler" ) + + def __ensure_dir_exists( self, dir_path, meaning ): + if os.path.isdir( dir_path ): + return + msg = None + if os.path.exists( self.working_directory ): + raise RuntimeError( '%s("%s") does not exist!' % ( meaning, dir_path ) ) + else: + raise RuntimeError( '%s("%s") should be "directory", not a file.' % ( meaning, dir_path ) ) + + + def raise_on_wrong_settings( self ): + """validates the configuration settings and raises RuntimeError on error""" + self.__ensure_dir_exists( self.working_directory, 'working directory' ) + map( lambda idir: self.__ensure_dir_exists( idir, 'include directory' ) + , self.include_paths ) + + +class gccxml_configuration_t(parser_configuration_t): + """Configuration object to collect parameters for invoking gccxml. + + This class serves as a container for the parameters that can be used + to customize the call to gccxml. + """ + def __init__( self + , gccxml_path='' + , working_directory='.' + , include_paths=None + , define_symbols=None + , undefine_symbols=None + , start_with_declarations=None + , ignore_gccxml_output=False + , cflags="" + , compiler=None): + """Constructor. + """ + parser_configuration_t.__init__( self + , working_directory=working_directory + , include_paths=include_paths + , define_symbols=define_symbols + , undefine_symbols=undefine_symbols + , cflags=cflags + , compiler=compiler) + + self.__gccxml_path = gccxml_path + + if not start_with_declarations: + start_with_declarations = [] + self.__start_with_declarations = start_with_declarations + + self.__ignore_gccxml_output = ignore_gccxml_output + + def clone(self): + return copy.deepcopy( self ) + + def __get_gccxml_path(self): + return self.__gccxml_path + def __set_gccxml_path(self, new_path ): + self.__gccxml_path = new_path + gccxml_path = property( __get_gccxml_path, __set_gccxml_path + , doc="gccxml binary location" ) + + @property + def start_with_declarations(self): + """list of declarations gccxml should start with, when it dumps declaration tree""" + return self.__start_with_declarations + + def __get_ignore_gccxml_output(self): + return self.__ignore_gccxml_output + def __set_ignore_gccxml_output(self, val=True): + self.__ignore_gccxml_output = val + ignore_gccxml_output = property( __get_ignore_gccxml_output, __set_ignore_gccxml_output + , doc="set this property to True, if you want pygccxml to ignore any error\\warning that comes from gccxml" ) + + + def raise_on_wrong_settings( self ): + return + super( gccxml_configuration_t, self ).raise_on_wrong_settings() + if os.path.isfile( self.gccxml_path ): + return + if sys.platform == 'win32': + gccxml_name = 'gccxml' + '.exe' + environment_var_delimiter = ';' + elif sys.platform == 'linux2' or sys.platform == 'darwin': + gccxml_name = 'gccxml' + environment_var_delimiter = ':' + else: + raise RuntimeError( 'unable to find out location of gccxml' ) + may_be_gccxml = os.path.join( self.gccxml_path, gccxml_name ) + if os.path.isfile( may_be_gccxml ): + self.gccxml_path = may_be_gccxml + else: + for path in os.environ['PATH'].split( environment_var_delimiter ): + gccxml_path = os.path.join( path, gccxml_name ) + if os.path.isfile( gccxml_path ): + self.gccxml_path = gccxml_path + break + else: + msg = 'gccxml_path("%s") should exists or to be a valid file name.' \ + % self.gccxml_path + raise RuntimeError( msg ) + +config_t = gccxml_configuration_t #backward computability diff --git a/pool/shard001/Python/0014050_pmenv.py b/pool/shard001/Python/0014050_pmenv.py new file mode 100644 index 0000000000000000000000000000000000000000..5e554e87a7be48beb1fcf20248ca72afefd14141 --- /dev/null +++ b/pool/shard001/Python/0014050_pmenv.py @@ -0,0 +1,79 @@ +# Copyright (c) 2006 by Aurelien Foret +# Copyright (c) 2006-2022 Pacman Development Team +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +import os + +import pmtest +import tap + + +class pmenv(object): + """Environment object + """ + testcases = [] + + def __init__(self, root = "root"): + self.root = os.path.abspath(root) + self.pacman = { + "bin": None, + "bindir": ["/usr/bin/"], + "debug": 0, + "gdb": 0, + "valgrind": 0, + "nolog": 0 + } + self.config = { + "gpg": True, + "nls": True, + "curl": True + } + + def __str__(self): + return "root = %s\n" \ + "pacman = %s" \ + % (self.root, self.pacman) + + def addtest(self, testcase): + """ + """ + if not os.path.isfile(testcase): + raise IOError("test file %s not found" % testcase) + self.testcases.append(testcase) + + def run(self): + """ + """ + for testcase in self.testcases: + t = pmtest.pmtest(testcase, self.root, self.config) + t.load() + if t.skipall: + tap.skip_all("skipping %s (%s)" % (t.description, t.skipall)) + else: + tap.plan(1) + tap.diag("Running '%s'" % t.testname) + + t.generate(self.pacman) + t.run(self.pacman) + + tap.diag("==> Checking rules") + # When running under meson, we don't emit 'todo' in the plan and instead + # handle expected failures in the test() objects. This really should be + # fixed in meson: + # https://github.com/mesonbuild/meson/issues/2923#issuecomment-614647076 + tap.todo = (t.expectfailure and + not 'RUNNING_UNDER_MESON' in os.environ) + tap.subtest(lambda: t.check(), t.description) diff --git a/pool/shard001/Python/0014054_test_support.py b/pool/shard001/Python/0014054_test_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4c99cf1e57736fdd42e35a79b292c4482120045d --- /dev/null +++ b/pool/shard001/Python/0014054_test_support.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +'''Tests for natto.support.''' +import codecs +import os +import re +import sys +import yaml +import unittest +import natto.environment as env +import natto.support as support +from tests import TestStringSupport +from yaml import CLoader as Loader + +class TestSupport(unittest.TestCase, TestStringSupport): + '''Tests the behavior of the natto.mecab.Support module. ''' + + def setUp(self): + self.env = env.MeCabEnv() + enc = self.env.charset + + self.bytes2str, self.str2bytes = support.string_support(enc) + self.split_pattern, self.split_features = support.splitter_support() + + cwd = os.getcwd() + yamlfile = os.path.join(cwd, 'tests', 'test_utf8.yml') + + with codecs.open(yamlfile, 'r', encoding='utf-8') as f: + self.yaml = yaml.load(f, Loader=Loader) + + def tearDown(self): + self.yaml = None + self.env = None + self.bytes2str = None + self.str2bytes = None + self.splitter_support = None + + # ------------------------------------------------------------------------ + + def test_bytes2str(self): + '''Test behavior of string support for MeCab output: + bytes.decode(enc) to Unicode + ''' + yml = self.yaml.get('text1') + txt = self._mecab_input(yml.get('text')) + self.assertEqual(self._mecab_output(txt), self.bytes2str(txt)) + + def test_str2bytes(self): + '''Test behavior of string support for MeCab input: + str.encode(enc) to bytes + ''' + yml = self.yaml.get('text1') + txt = self._u2str(yml.get('text')) + self.assertEqual(self._mecab_input(txt), self.str2bytes(txt)) + + def test_splitter_str(self): + '''Test behavior of splitter support for MeCab boundary constraint + parsing. + ''' + yml = self.yaml.get('text7') + text = self._u2str(yml.get('text')) + pat1 = self._u2str(yml.get('pattern')) + + tokens = [self._u2str(e) for e in yml.get('tokens')] + matches = [e for e in yml.get('matches')] + expected = list(zip(tokens, matches)) + actual = list(self.split_pattern(text, pat1)) + + self.assertEqual(expected, actual) + + def test_splitter_re(self): + '''Test behavior of splitter support for MeCab boundary constraint + parsing. + ''' + yml = self.yaml.get('text7') + text = self._u2str(yml.get('text')) + pat1 = re.compile(yml.get('pattern')) + + tokens = [self._u2str(e) for e in yml.get('tokens')] + matches = [e for e in yml.get('matches')] + expected = list(zip(tokens, matches)) + actual = list(self.split_pattern(text, pat1)) + + self.assertEqual(expected, actual) + + def test_splitter_reU(self): + '''Test behavior of splitter support for MeCab boundary constraint + parsing. + ''' + yml = self.yaml.get('text8') + text = self._u2str(yml.get('text')) + pat1 = re.compile(yml.get('pattern'), re.U) + + tokens = [self._u2str(e) for e in yml.get('tokens')] + matches = [e for e in yml.get('matches')] + expected = list(zip(tokens, matches)) + actual = list(self.split_pattern(text, pat1)) + + self.assertEqual(expected, actual) + +''' +Copyright (c) 2021, Brooke M. Fujita. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' diff --git a/pool/shard001/Python/0014056_test_urlfetch.py b/pool/shard001/Python/0014056_test_urlfetch.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5e1e8a13573353382150f759b114f767e6234d --- /dev/null +++ b/pool/shard001/Python/0014056_test_urlfetch.py @@ -0,0 +1,116 @@ +# 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 mock +from requests import exceptions +from six import moves + +from solum.common import urlfetch +from solum.tests import base + + +FETCH_SIZE_OK = 500 + + +class Response: + def __init__(self, buf=''): + self.buf = buf + + def iter_content(self, chunk_size=1): + while self.buf: + yield self.buf[:chunk_size] + self.buf = self.buf[chunk_size:] + + def raise_for_status(self): + pass + + +class TestUrlFetch(base.BaseTestCase): + def setUp(self): + super(TestUrlFetch, self).setUp() + + @mock.patch('solum.common.urlfetch.requests.get') + def test_max_size_zero_byte(self, mock_get): + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + url = 'http://example.com/plan' + self.assertRaises(IOError, urlfetch.get, url, 0) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_chunk_size_zero_byte(self, mock_get): + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + url = 'http://example.com/plan' + self.assertRaises(IOError, urlfetch.get, url, FETCH_SIZE_OK, 0) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_http_scheme(self, mock_get): + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + url = 'http://example.com/plan' + self.assertEqual(data, urlfetch.get(url, FETCH_SIZE_OK)) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_https_scheme(self, mock_get): + url = 'https://example.com/plan' + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + self.assertEqual(data, urlfetch.get(url, FETCH_SIZE_OK)) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_http_error(self, mock_get): + url = 'http://example.com/plan' + mock_get.side_effect = IOError + self.assertRaises(IOError, urlfetch.get, url, FETCH_SIZE_OK) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_non_exist_url(self, mock_get): + url = 'http://non-exist.com/plan' + mock_get.side_effect = exceptions.Timeout + self.assertRaises(IOError, urlfetch.get, url, FETCH_SIZE_OK) + + def test_invalid_url(self): + self.assertRaises(IOError, urlfetch.get, 'invalid_url', FETCH_SIZE_OK) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_max_fetch_size_okay(self, mock_get): + url = 'http://example.com/plan' + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + urlfetch.get(url, FETCH_SIZE_OK) + + @mock.patch('solum.common.urlfetch.requests.get') + def test_max_fetch_size_error(self, mock_get): + url = 'http://example.com/plan' + data = '{ "foo": "bar" }' + mock_get.return_value = Response(data) + exception = self.assertRaises(IOError, urlfetch.get, url, 5) + self.assertIn("File exceeds", str(exception)) + + def test_file_scheme_default_behaviour(self): + self.assertRaises(IOError, urlfetch.get, 'file:///etc/profile', + FETCH_SIZE_OK) + + @mock.patch('six.moves.urllib.request.urlopen') + def test_file_scheme_supported(self, mock_urlopen): + data = '{ "foo": "bar" }' + url = 'file:///etc/profile' + mock_urlopen.return_value = moves.cStringIO(data) + self.assertEqual(data, urlfetch.get(url, FETCH_SIZE_OK, + allowed_schemes=['file'])) + + @mock.patch('six.moves.urllib.request.urlopen') + def test_file_scheme_failure(self, mock_urlopen): + url = 'file:///etc/profile' + mock_urlopen.side_effect = moves.urllib.error.URLError('oops') + self.assertRaises(IOError, urlfetch.get, url, FETCH_SIZE_OK, + allowed_schemes=['file']) diff --git a/pool/shard001/Python/0014075_test_translation.py b/pool/shard001/Python/0014075_test_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9987c295d84c8d32a33d73453c797c9a7ff36e --- /dev/null +++ b/pool/shard001/Python/0014075_test_translation.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 + +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division +from __future__ import absolute_import +from builtins import open +from builtins import bytes +from builtins import hex +from future import standard_library +standard_library.install_aliases() +from binary_translator import instrument_memory_access + +memory_accesses = [] + +def read_code_memory(address, size): + memory_accesses.append((address, size)) +# print("Reading code memory 0x%08x[%d]" % (address, size)) + if address >= 0x1146 and address < 0x1218: + address -= 0x1146 + return bytes([160, 137, 114, 73, 8, 67, 160, 129, 96, 139, 255, 34, + 65, 50, 16, 67, 96, 131, 32, 139, 240, 33, 8, 64, 110, 73, + 64, 24, 32, 131, 160, 139, 192, 11, 192, 3, 125, 48, 160, + 131, 96, 139, 48, 67, 96, 131, 96, 139, 176, 67, 96, 131, + 160, 139, 1, 33, 201, 3, 8, 67, 160, 131, 160, 139, 64, 4, + 64, 12, 160, 131, 0, 32, 99, 73, 64, 28, 136, 66, 252, 211, + 224, 137, 97, 73, 128, 11, 128, 3, 64, 24, 224, 129, 160, + 136, 95, 73, 192, 11, 192, 3, 64, 24, 160, 128, 224, 136, + 93, 73, 8, 64, 255, 48, 192, 28, 224, 128, 32, 137, 91, 73, + 192, 11, 192, 3, 64, 24, 32, 129, 96, 137, 89, 73, 192, 11, + 192, 3, 64, 24, 96, 129, 32, 143, 87, 73, 192, 11, 192, 3, + 64, 24, 32, 135, 96, 139, 144, 67, 96, 131, 160, 137, 64, + 10, 64, 2, 32, 48, 160, 129, 82, 72, 1, 104, 73, 8, 73, 0, + 1, 96, 0, 34, 66, 96, 79, 73, 129, 96, 79, 73, 1, 98, 79, + 73, 65, 98, 79, 73, 1, 98, 1, 104, 57, 67, 1, 96, 1, 104, + 201, 7, 252, 208][address : address + size]) + elif address >= 0x128c and address < 0x1372: + address -= 0x128c + return bytes([0, 0, 13, 64, 0, 8, 10, 64, 64, 144, 1, 64, 0, + 16, 13, 64, 200, 39, 0, 4, 128, 3, 10, 64, 204, 38, 0, 0, + 132, 156, 5, 6, 0, 0, 0, 0, 0, 47, 4, 6, 128, 39, 1, 64, + 0, 42, 1, 64, 192, 112, 3, 6, 192, 29, 0, 0, 156, 3, 0, + 4, 80, 195, 5, 6, 172, 191, 5, 6, 0, 48, 13, 64, 64, 0, + 16, 0, 176, 28, 0, 0, 188, 192, 5, 6, 7, 5, 0, 0, 150, + 250, 255, 255, 148, 0, 0, 4, 136, 3, 0, 4, 13, 10, 82, + 115, 116, 32, 48, 120, 0, 0, 0, 0, 77, 0, 0, 0, 0, 43, + 1, 64, 0, 144, 1, 64, 13, 240, 173, 222, 237, 254, 173, + 222, 200, 3, 0, 4, 255, 1, 0, 0, 5, 57, 0, 0, 160, 134, 1, + 0, 110, 46, 0, 0, 198, 122, 0, 0, 1, 248, 255, 255, 22, 13, + 0, 0, 66, 9, 0, 0, 10, 25, 0, 0, 0, 160, 13, 64, 0, 0, + 254, 3, 255, 255, 255, 127, 112, 71, 112, 71, 204, 8, 0, + 128, 0, 71, 1, 64, 160, 0, 7, 64, 10, 43, 0, 0, 11, 51, + 0, 0, 12, 45, 0, 0, 54, 53, 0, 0, 170, 114, 0, 0, 69, 77, + 0, 0, 109, 113, 0, 0, 112, 71][address : address + size]) + else: + print("Invalid address requested: 0x%x" % address) + +data = instrument_memory_access( + architecture = "thumb", + entry_point = 0x1146, + valid_pc_ranges = [(0x1146, 0x1218)] , + generated_code_address = 0x2000, + get_code_callback = read_code_memory, + opts = {"print_ir": "true", "debug": "true", "instrument_memory_access": "true"}) +f = open("code.bin", "wb") +f.write(data["generated_code"]) +f.close() + +def merge_ranges(ranges): + regions = [] + + for r in ranges: + range_done = False + for region in regions: + if r[0] >= region[0] and r[0] <= region[1]: + if r[1] > region[1]: + region[1] = r[1] + range_done = True + break + elif r[1] >= region[0] and r[1] <= region[1]: + if r[0] < region[0]: + region[0] = r[0] + range_done = True + break + + if not range_done: + regions.append(r) + + if regions == ranges: + return regions + else: + return merge_ranges(regions) + +bla = [[x, x + y] for (x, y) in memory_accesses] +print([(hex(x), hex(y)) for [x, y] in merge_ranges(bla)]) + +#print(data) +#print("Size: %d" % len(data['generated_code'])) +#print(memory_accesses) diff --git a/pool/shard001/Python/0014078_TestSingleSlice.py b/pool/shard001/Python/0014078_TestSingleSlice.py new file mode 100644 index 0000000000000000000000000000000000000000..c7c1304a8bb7790484c5a9c1e7e01b57079187ba --- /dev/null +++ b/pool/shard001/Python/0014078_TestSingleSlice.py @@ -0,0 +1,18 @@ +#!/bin/env python +import numpy +#import pylab +import CalcStatistics +from PIMCHelp import * +import random +import numpy +from PIMC import * + + +tau=0.5 +lam=0.5 +numTimeSlices=5 +numParticles=2 +Path=PathClass(numpy.zeros((numTimeSlices,numParticles,3),float),tau,lam) +Path.SetPotential(ZeroFunction) +Path.SetCouplingConstant(0.0) +print PIMC(5000,Path,SingleSliceMove) diff --git a/pool/shard001/Python/0014092_sync.py b/pool/shard001/Python/0014092_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..39aee61528cb5c36db6a75fdf04c8bfcc8d72c3d --- /dev/null +++ b/pool/shard001/Python/0014092_sync.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +"""This module contains Trakt.tv sync endpoint support functions""" +from datetime import datetime + +from trakt.core import get, post +from trakt.utils import slugify, extract_ids, timestamp + +__author__ = 'Jon Nappi' +__all__ = ['Scrobbler', 'comment', 'rate', 'add_to_history', + 'add_to_watchlist', 'remove_from_history', 'remove_from_watchlist', + 'add_to_collection', 'remove_from_collection', 'search', + 'search_by_id'] + + +@post +def comment(media, comment_body, spoiler=False, review=False): + """Add a new comment to a :class:`Movie`, :class:`TVShow`, or + :class:`TVEpisode`. If you add a review, it needs to + be at least 200 words + + :param media: The media object to post the comment to + :param comment_body: The content of comment + :param spoiler: Boolean flag to indicate whether this comment contains + spoilers + :param review: Boolean flag to determine if this comment is a review (>200 + characters. Note, if *comment_body* is longer than 200 characters, the + review flag will automatically be set to `True` + """ + if not review and len(comment_body) > 200: + review = True + data = dict(comment=comment_body, spoiler=spoiler, review=review) + data.update(media.to_json()) + yield 'comments', data + + +@post +def rate(media, rating, rated_at=None): + """Add a rating from 1 to 10 to a :class:`Movie`, :class:`TVShow`, or + :class:`TVEpisode` + + :param media: The media object to post a rating to + :param rating: A rating from 1 to 10 for the media item + :param rated_at: A `datetime.datetime` object indicating the time at which + this rating was created + """ + if rated_at is None: + rated_at = datetime.now() + + data = dict(rating=rating, rated_at=timestamp(rated_at)) + data.update(media.ids) + yield 'sync/ratings', {media.media_type: [data]} + + +@post +def add_to_history(media, watched_at=None): + """Add a :class:`Movie`, :class:`TVShow`, or :class:`TVEpisode` to your + watched history + + :param media: The media object to add to your history + :param watched_at: A `datetime.datetime` object indicating the time at + which this media item was viewed + """ + if watched_at is None: + watched_at = datetime.now() + + data = dict(watched_at=timestamp(watched_at)) + data.update(media.ids) + yield 'sync/history', {media.media_type: [data]} + + +@post +def add_to_watchlist(media): + """Add a :class:`TVShow` to your watchlist + + :param media: The :class:`TVShow` object to add to your watchlist + """ + yield 'sync/watchlist', media.to_json() + + +@post +def remove_from_history(media): + """Remove the specified media object from your history + + :param media: The media object to remove from your history + """ + yield 'sync/history/remove', media.to_json() + + +@post +def remove_from_watchlist(media): + """Remove a :class:`TVShow` from your watchlist + + :param media: The :clas:`TVShow` to remove from your watchlist + """ + yield 'sync/watchlist/remove', media.to_json() + + +@post +def add_to_collection(media): + """Add a :class:`Movie`, :class:`TVShow`, or :class:`TVEpisode` to your + collection + + :param media: The media object to collect + """ + yield 'sync/collection', media.to_json() + + +@post +def remove_from_collection(media): + """Remove a media item from your collection + + :param media: The media object to remove from your collection + """ + yield 'sync/collection/remove', media.to_json() + + +@get +def search(query, search_type='movie', year=None): + """Perform a search query against all of trakt's media types + + :param query: Your search string + :param search_type: The type of object you're looking for. Must be one of + 'movie', 'show', 'episode', or 'person' + """ + valids = ('movie', 'show', 'episode', 'person') + if search_type not in valids: + raise ValueError('search_type must be one of {}'.format(valids)) + uri = 'search?query={query}&type={type}'.format( + query=slugify(query), type=search_type) + + if year is not None: + uri += '&year={}'.format(year) + + data = yield uri + + for media_item in data: + extract_ids(media_item) + + # Need to do imports here to prevent circular imports with modules that + # need to import Scrobblers + if search_type == 'movie': + from trakt.movies import Movie + yield [Movie(**d.pop('movie')) for d in data] + elif search_type == 'show': + from trakt.tv import TVShow + yield [TVShow(**d.pop('show')) for d in data] + elif search_type == 'episode': + from trakt.tv import TVEpisode + episodes = [] + for episode in data: + show = episode.pop('show') + extract_ids(episode['episode']) + episodes.append(TVEpisode(show.get('title', None), + **episode['episode'])) + yield episodes + elif search_type == 'person': + from trakt.people import Person + yield [Person(**d.pop('person')) for d in data] + + +@get +def search_by_id(query, id_type='imdb'): + """Perform a search query by using a Trakt.tv ID or other external ID + + :param query: Your search string + :param id_type: The type of object you're looking for. Must be one of + 'trakt-movie', 'trakt-show', 'trakt-episode', 'imdb', 'tmdb', 'tvdb' or + 'tvrage' + """ + valids = ('trakt-movie', 'trakt-show', 'trakt-episode', 'imdb', 'tmdb', + 'tvdb', 'tvrage') + if id_type not in valids: + raise ValueError('search_type must be one of {}'.format(valids)) + data = yield 'search?id={query}&id_type={id_type}'.format( + query=slugify(query), id_type=id_type) + + for media_item in data: + extract_ids(media_item) + + results = [] + for d in data: + if 'episode' in d: + from trakt.tv import TVEpisode + show = d.pop('show') + extract_ids(d['episode']) + results.append(TVEpisode(show['title'], **d['episode'])) + elif 'movie' in d: + from trakt.movies import Movie + results.append(Movie(**d.pop('movie'))) + elif 'show' in d: + from trakt.tv import TVShow + results.append(TVShow(**d.pop('show'))) + elif 'person' in d: + from trakt.people import Person + results.append(Person(**d.pop('person'))) + yield results + + +class Scrobbler(object): + """Scrobbling is a seemless and automated way to track what you're watching + in a media center. This class allows the media center to easily send events + that correspond to starting, pausing, stopping or finishing a movie or + episode. + """ + + def __init__(self, media, progress, app_version, app_date): + """Create a new :class:`Scrobbler` instance + + :param media: The media object you're scrobbling. Must be either a + :class:`Movie` or :class:`TVEpisode` type + :param progress: The progress made through *media* at the time of + creation + :param app_version: The media center application version + :param app_date: The date that *app_version* was released + """ + super(Scrobbler, self).__init__() + self.progress, self.version = progress, app_version + self.media, self.date = media, app_date + if self.progress > 0: + self.start() + + def start(self): + """Start scrobbling this :class:`Scrobbler`'s *media* object""" + self._post('scrobble/start') + + def pause(self): + """Pause the scrobbling of this :class:`Scrobbler`'s *media* object""" + self._post('scrobble/pause') + + def stop(self): + """Stop the scrobbling of this :class:`Scrobbler`'s *media* object""" + self._post('scrobble/stop') + + def finish(self): + """Complete the scrobbling this :class:`Scrobbler`'s *media* object""" + if self.progress < 80.0: + self.progress = 100.0 + self.stop() + + def update(self, progress): + """Update the scobbling progress of this :class:`Scrobbler`'s *media* + object + """ + self.progress = progress + self.start() + + @post + def _post(self, uri): + """Handle actually posting the scrobbling data to trakt + + :param uri: The uri to post to + :param args: Any additional data to post to trakt alond with the + generic scrobbling data + """ + payload = dict(progress=self.progress, app_version=self.version, + date=self.date) + payload.update(self.media.to_json()) + yield uri, payload + + def __enter__(self): + """Context manager support for `with Scrobbler` syntax. Begins + scrobbling the :class:`Scrobller`'s *media* object + """ + self.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Context manager support for `with Scrobbler` syntax. Completes + scrobbling the :class:`Scrobller`'s *media* object + """ + self.finish() diff --git a/pool/shard001/Python/0014097_middleware.py b/pool/shard001/Python/0014097_middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..0486258946d497f1807ff4b32ee0927549f4fb54 --- /dev/null +++ b/pool/shard001/Python/0014097_middleware.py @@ -0,0 +1,151 @@ +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from idbase.util import localized_datetime_string_now, datetime_diff_seconds +from idbase.util import get_class +import logging +from idbase.exceptions import InvalidSessionError, LoginNotPerson, ServiceError +from idbase.decorators import POSTLOGIN_KEY + +logger = logging.getLogger(__name__) + + +UW_SAML_ENTITY = getattr(settings, 'SAML_ENTITIES', {}).get( + 'uw', 'urn:mace:incommon:washington.edu') + + +def get_authenticated_uwnetid(remote_user='', saml_idp=''): + """ + Given a remote_user and saml_idp, return a personal UWNetID or raise + an Exception. + """ + if not remote_user: + raise ServiceError('No REMOTE_USER variable set') + if (not remote_user.endswith('@washington.edu') or + saml_idp != UW_SAML_ENTITY): + raise InvalidSessionError( + 'unauthenticated user id={id}, idp={idp}'.format( + id=remote_user, idp=saml_idp)) + netid = remote_user.rsplit('@washington.edu', 1)[0] + if not is_personal_netid(netid=netid): + raise LoginNotPerson( + 'non-person logging in to site, REMOTE_USER={}'.format( + remote_user), + netid=netid) + return netid + + +def is_personal_netid(netid=None): + """ + Check in IRWS that a given netid belongs to a person. Non-persons + don't get to log in. + """ + irws = get_class(settings.IDBASE_IRWS_CLASS)() + regid = irws.get_regid(netid=netid) + return regid and regid.entity_name == 'Person' + + +class LoginUrlMiddleware(object): + """ + Middleware to check the REMOTE_USER variable only when on LOGIN_URL, + storing the user in the session. This should negate the need for + AuthenticationMiddleware, RemoteUserMiddleware, and the associated + AUTHENTICATION_BACKENDS. + + In this scenario, we have a login page that is protected by SSO, + and multiple other SSO-protected pages that check federation status. + Authenticate only the REMOTE_USER variable when on the configured + LOGIN_URL. + + We store only authenticated personal UWNetIDs as request.uwnetid, or + None if not authenticated. All errors are stored in request.login_url_error + for handling in views.login. + """ + UWNETID_KEY = '_login_url_uwnetid' + + def process_request(self, request): + """ + Create a new login if on LOGIN_URL. Otherwise use an existing user if + stored in the session. + """ + if request.path == settings.LOGIN_URL: + self.flush_session(request) + try: + uwnetid = get_authenticated_uwnetid( + remote_user=request.META.get('REMOTE_USER', ''), + saml_idp=request.META.get('Shib-Identity-Provider', '')) + request.session[self.UWNETID_KEY] = uwnetid + except (LoginNotPerson, InvalidSessionError) as e: + logger.info(e) + request.login_url_error = e + except Exception as e: + logger.exception(e) + request.login_url_error = e + request.uwnetid = request.session.get(self.UWNETID_KEY, None) + + @staticmethod + def flush_session(request): + postlogin_url = request.session.pop(POSTLOGIN_KEY, default=None) + request.session.flush() + if postlogin_url: + request.session[POSTLOGIN_KEY] = postlogin_url + + +class SessionTimeoutMiddleware(object): + """ + Middleware to supplement built-in session expiration with an + independently-managed timeout. This allows us to set + SESSION_EXPIRE_AT_BROWSER_CLOSE to True while also having an expiration, + something the default session management doesn't allow for. Allows for + setting SESSION_TIMEOUT_DEFAULT_SECONDS, the absence of which will set a + timeout of 20 minutes. + """ + def __init__(self): + if not settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: + raise ImproperlyConfigured( + 'SessionTimeoutMiddleware expects ' + 'SESSION_EXPIRE_AT_BROWSER_CLOSE to be True.') + + def process_request(self, request): + """ + Invalidate a session if expiration is beyond the last session update. + """ + last_update = request.session.get('_session_timeout_last_update', + localized_datetime_string_now()) + + expiry = getattr(settings, 'SESSION_TIMEOUT_DEFAULT_SECONDS', 20*60) + + diff = datetime_diff_seconds(last_update) + if diff > expiry: + logger.info( + 'Clearing session on inactivity (diff={}, expiry={})'.format( + diff, expiry)) + request.session.flush() + + def process_response(self, request, response): + """ + Reset the timeout if the session has been modified. + """ + if request.session.modified: + request.session['_session_timeout_last_update'] = \ + localized_datetime_string_now() + return response + + +class MockLoginMiddleware(object): + """ + Middleware to fake a shib-protected LOGIN_URL. + """ + def __init__(self): + if not settings.DEBUG: + logger.error('MockLoginMiddleware shouldn\'t be set in a ' + 'production environment') + if not hasattr(settings, 'MOCK_LOGIN_USER'): + raise ImproperlyConfigured('MOCK_LOGIN_USER required.') + + def process_request(self, request): + """ + Set a remote_user if on LOGIN_URL. + """ + if request.path == settings.LOGIN_URL: + request.META.setdefault('REMOTE_USER', settings.MOCK_LOGIN_USER) + request.META.setdefault('Shib-Identity-Provider', UW_SAML_ENTITY) diff --git a/pool/shard001/Python/0014098_account_analytic_account.py b/pool/shard001/Python/0014098_account_analytic_account.py new file mode 100644 index 0000000000000000000000000000000000000000..e99ffeb9a0932bc3ab280cbc8935ce388de56ee8 --- /dev/null +++ b/pool/shard001/Python/0014098_account_analytic_account.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# © 2016 Ainara Galdona - AvanzOSC +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html + +from openerp import models, api + + +class AccountAnalyticAccount(models.Model): + + _inherit = 'account.analytic.account' + + @api.model + def _prepare_invoice_data(self, contract): + res = super(AccountAnalyticAccount, + self)._prepare_invoice_data(contract) + partner = self.env['res.partner'].browse(res.get('partner_id', False)) + payment = partner.customer_payment_mode + res['payment_mode_id'] = payment.id + res['partner_bank_id'] = payment.bank_id.id + return res diff --git a/pool/shard001/Python/0014102_main.py b/pool/shard001/Python/0014102_main.py new file mode 100644 index 0000000000000000000000000000000000000000..b3209b3737e6941dceb78ddbc21956f6acac4037 --- /dev/null +++ b/pool/shard001/Python/0014102_main.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +import time +import math +__author__ = 'Andre Christoga' + +def main(): + ''' + Area of the shape + ''' + input = raw_input("What's the shape? ") + + if input == 'triangle': + triangle() + elif input == 'circle': + circle() + elif input == 'square': + square() + elif input == 'rectangle': + square() + elif input == 'trapezoid': + trapezoid() + else: + print 'Shape is not available' + +def init(self): + pass + +def triangle(): + ''' + Area of the triangle + ''' + pedestal = input("Pedestal: ") + height = input("Height: ") + + result = pedestal * height / 2 + print "Result:", result + exit() + +def circle(): + ''' + Area of the circle + ''' + radiant = input("Radiant: ") + + ceil = radiant * 2 / math.pi + result = math.ceil(ceil) + print "Result:", result + exit() + +def square(): + ''' + Area of the square + ''' + pedestal = input("Pedestal: ") + height = input("Height: ") + + result = pedestal * height + print "Result:", result + exit() + +def trapezoid(): + ''' + Area of the trapezoid + ''' + width_1 = input("First width: ") + width_2 = input("Second width: ") + width = width_1 + width_2 + height = input("Vertical width: ") + + result = width / 0.5 * height + print "Result: ", result + exit() + +def exit(): + ''' + Exit program + ''' + exit = raw_input("Again? [y]Yes or [n]No: ") + if exit == 'y': + main() + if exit == 'n': + print 'Goodbye! ' + time.sleep(0.1) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014106_webana.py b/pool/shard001/Python/0014106_webana.py new file mode 100644 index 0000000000000000000000000000000000000000..504a01dc412a5f76b73c837af65c05264dcd9323 --- /dev/null +++ b/pool/shard001/Python/0014106_webana.py @@ -0,0 +1,61 @@ +# -*- coding: UTF-8 -*- +# !/usr/bin/env python +import os +import sys +import time +import xlwt + +reload(sys) +sys.setdefaultencoding('utf-8') +# print sys.getdefaultencoding() +os.system('./webana.sh') + +wbk_1 = xlwt.Workbook() # 建一个excel文件 + + +##计算每个文件的行数 +def countf(filepath): + # print(filepath) + countfile = open(filepath, 'r') + # countfile = open (filepath,'r',encoding= 'utf_8') + count = -1 + for count, line in enumerate(countfile): + count += 1 + countfile.close(); + return count; + + +fndict = {} +fndict["default"] = "未知渠道" +fndict["new"] = "深圳渠道" +fndict["jtyjrrd"] = "今日热点" +fndict["jtyjrtt"] = "今日头条" +fndict["jtyszxqd"] = "深圳新渠道" +fndict["jtytxcj"] = "腾讯财经" +fndict["jtytxgp"] = "腾讯股票" +fndict["jtywx"] = "微信" +fndict["jtywxdt"] = "微信头条" +fndict["jtyzxg"] = "自选股" +fndict["jtycj"] = "财经" +fndict["jtyuc"] = "uc" +fndict["jtyyyy"] = "摇一摇" + +for sname in fndict.values(): + aaf = "web_data/" + sname + ".xls" + count = countf(aaf) # 计算文件行数 + if os.path.getsize(aaf): # 判断文件大小是否为零 + sheet_1 = wbk_1.add_sheet(sname, cell_overwrite_ok=True) # 创建工作表,表名为sname。 + fo = open(aaf, 'r') + for i in range(0, count): + line = fo.readline() + c = line.split("\t") + for j in range(0, 10): + sheet_1.write(i, j, c[j]) + fo.close() + else: + pass + +workbookname = "web_data/" + time.strftime("%m%d", time.localtime()) + "抓取资源.xls" +wbk_1.save(workbookname) # 这样就在原excel里新建是XXX1和XXX2两个sheet! +os.system(' sz web_data/`date "+%m%d"`抓取资源.xls ') +os.system('cd web_data; wc [^0-9a-tv-z]*.xls; wc aa*') diff --git a/pool/shard001/Python/0014108_auth.py b/pool/shard001/Python/0014108_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..59d6a358a79c6ca45ccd8a3584cb5d4f3a992741 --- /dev/null +++ b/pool/shard001/Python/0014108_auth.py @@ -0,0 +1,201 @@ +"""Flask extension of Flask-Principal for handling +authentication/authorization. +""" + +from flask import session, current_app +from flask_principal import ( + Principal, + identity_loaded, + identity_changed, + Identity, + AnonymousIdentity, + Permission, + RoleNeed, + TypeNeed +) + + +# pylint: disable=invalid-name +login_need = TypeNeed('login') +# pylint: enable=invalid-name + + +class SQLAlchemyAuthProvider(object): + """SQLAlchemy backed UserProvider class which provides identity information + for logged in user. + """ + + # SQLAlchemy model used to query the database for identity information + __model__ = None + + __id_key__ = 'id' + __roles_key__ = 'roles' + + def __init__(self, db_session): + self.session = db_session + + def identify(self, identity): + """Identify a user via _id to provide information for role based + authentication. + """ + ident = {} + + user = self.get_user(identity.id) + if user: + ident.update({ + self.__id_key__: identity.id, + self.__roles_key__: self.get_roles(user) + }) + + return ident + + ## + # Override these methods if they don't return user data correctly based on + # your models. + ## + + def get_user(self, _id): + """Return user object from database.""" + if _id is None: + return None + return self.session.query(self.__model__).get(_id) + + def get_roles(self, user): + """Return a list of `roles` as strings.""" + return getattr(user, self.__roles_key__, []) + + +class Auth(object): + """Auth extension.""" + _extension_name = 'carafe.auth' + + def __init__(self, app=None, provider=None): + self.principal = Principal(use_sessions=False) + self.require = PermissionFactory() + + self.app = app + if self.app: # pragma: no cover + self.init_app(app, provider) + + def init_app(self, app, provider=None): + """Initialize app.""" + app.config.setdefault('CARAFE_AUTH_ENABLED', True) + app.config.setdefault('CARAFE_AUTH_SESSION_ID_KEY', 'user_id') + app.config.setdefault('CARAFE_AUTH_IDENTITY_ID_KEY', 'id') + app.config.setdefault('CARAFE_AUTH_IDENTITY_ROLES_KEY', 'roles') + + if not app.config['CARAFE_AUTH_ENABLED']: # pragma: no cover + return + + if not hasattr(app, 'extensions'): # pragma: no cover + app.extensions = {} + + app.extensions[self._extension_name] = {'provider': provider} + + # NOTE: Instead of having principal use it's session loader, we'll use + # ours. + self.principal.init_app(app) + self.principal.identity_loader(self.session_identity_loader) + identity_loaded.connect_via(app)(self.on_identity_loaded) + + @property + def session_id_key(self): + """Property access to config's CARAFE_AUTH_SESSION_ID_KEY.""" + return current_app.config['CARAFE_AUTH_SESSION_ID_KEY'] + + @property + def identity_id_key(self): + """Property access to config's CARAFE_AUTH_IDENTITY_ID_KEY.""" + return current_app.config['CARAFE_AUTH_IDENTITY_ID_KEY'] + + @property + def identity_roles_key(self): + """Property access to config's CARAFE_AUTH_IDENTITY_ROLES_KEY.""" + return current_app.config['CARAFE_AUTH_IDENTITY_ROLES_KEY'] + + @property + def user_id(self): + """Property access to logged in user id.""" + return session.get(self.session_id_key) + + @property + def provider(self): + """Property access to auth provider instance.""" + return current_app.extensions[self._extension_name]['provider'] + + def session_identity_loader(self): + """Fetch user id from session using config's auth id key""" + if self.session_id_key in session: + identity = Identity(session[self.session_id_key]) + else: + identity = None + + return identity + + def on_identity_loaded(self, app, identity): # pylint: disable=unused-argument + """Called if session_identity_loader() returns an identity (i.e. not + None). + """ + # Whatever is returned is used for our identity. Potentially, provider + # may return a different user than original identity (e.g. app provides + # way for admin users to access site using a different user account) + + if self.provider: + ident = self.provider.identify(identity) + else: + ident = {self.identity_id_key: None} + + if self.user_id and not ident: + # session has an user_id but the ident return is empty + # user possibly deleted or inactivated in another process + self.logout() + + # provide auth (whether user is not anonymous) + if ident.get(self.identity_id_key): + identity.provides.add(login_need) + + # provide roles + for role in ident.get(self.identity_roles_key, []): + identity.provides.add(RoleNeed(role)) + + def send_identity_changed(self, user_id): + """Send identity changed event.""" + if user_id is None: + identity = AnonymousIdentity() + else: + identity = Identity(user_id) + + identity_changed.send( + current_app._get_current_object(), identity=identity) + + def login(self, user_id, propagate=True): + """Call after user has been authenticated for login.""" + if session.get(self.session_id_key) != user_id: + session[self.session_id_key] = user_id + if propagate: + self.send_identity_changed(user_id) + + def logout(self, propagate=True): + """Call to log user out.""" + if session.get(self.session_id_key): + del session[self.session_id_key] + if propagate: + self.send_identity_changed(None) + + +class PermissionFactory(object): + """General purpose permissions factory which creates RoleNeed permissions + from attribute access. + """ + def __init__(self): + self._permissions = { + 'login': Permission(login_need) + } + + def __getattr__(self, role): + """Return role permission's require method. If it doesn't exist yet, + create it.""" + if role not in self._permissions: + self._permissions[role] = Permission(RoleNeed(role)) + + return self._permissions[role].require diff --git a/pool/shard001/Python/0014109_Tunnel.py b/pool/shard001/Python/0014109_Tunnel.py new file mode 100644 index 0000000000000000000000000000000000000000..91a4ec3dad13855c556af46c60cf28738f49397a --- /dev/null +++ b/pool/shard001/Python/0014109_Tunnel.py @@ -0,0 +1,58 @@ +"""PRMS LED Tunnel core functions""" +from libs import opc + +# FadeCandy Server Settings +FADECANDY_SERVER_HOST = 'localhost' +FADECANDY_SERVER_PORT = 7890 + +# Tunnel Definition +CHANNEL_COUNT = 48 +LEDS_PER_CHANNEL = 64 +LED_COUNT = CHANNEL_COUNT * LEDS_PER_CHANNEL + +# Settings when working with sides (aka "walls") +LEFT_SIDE = 0 +RIGHT_SIDE = 1 + +SIDE_MATRIX_SIZE = (int(LEDS_PER_CHANNEL), int(CHANNEL_COUNT/2)) + +# initialize the OPC Client +Client = opc.Client(FADECANDY_SERVER_HOST+":"+str(FADECANDY_SERVER_PORT)) + +def get_pixel_index(channel, index, invert=False, wrap=True): + # validate index is within bounds or is wrappable + if (not wrap and (index < 0 or index >= LEDS_PER_CHANNEL)): + return -1 + + # wrap the index + # careful with index wrapping when translating to other languages + # python's modulo works here, some languages calculate it differently + # More info: https://stackoverflow.com/questions/3883004/negative-numbers-modulo-in-python + index = index % LEDS_PER_CHANNEL + + # calculate channel bounds + channelFirst = channel * LEDS_PER_CHANNEL + channelLast = channelFirst + LEDS_PER_CHANNEL - 1 + + # calculate the index in the full pixel list + if (invert): + result = channelLast - index + else: + result = channelFirst + index + + return result + +def get_pixel_index_by_side(side, depth, height, invert=False): + if side == LEFT_SIDE: + #left side + base = height + elif side == RIGHT_SIDE: + #right side + base = (2 * SIDE_MATRIX_SIZE[1] - height - 1) + + if base != None: + if invert: + return (base + 1) * SIDE_MATRIX_SIZE[0] - 1 - depth + return base * SIDE_MATRIX_SIZE[0] + depth + + return -1 \ No newline at end of file diff --git a/pool/shard001/Python/0014111_local_directory_corpus_driver.py b/pool/shard001/Python/0014111_local_directory_corpus_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca2998a0fb25f97d3dca7cd2559905f745d527b --- /dev/null +++ b/pool/shard001/Python/0014111_local_directory_corpus_driver.py @@ -0,0 +1,71 @@ +# Copyright (c) 2015 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. +import os + +from perf_insights import corpus_driver +from perf_insights import local_file_trace_handle +from perf_insights.value import run_info as run_info_module + + +def _GetFilesIn(basedir): + data_files = [] + for dirpath, dirnames, filenames in os.walk(basedir, followlinks=True): + new_dirnames = [d for d in dirnames if not d.startswith('.')] + del dirnames[:] + dirnames += new_dirnames + for f in filenames: + if f.startswith('.'): + continue + if f == 'README.md': + continue + full_f = os.path.join(dirpath, f) + rel_f = os.path.relpath(full_f, basedir) + data_files.append(rel_f) + + data_files.sort() + return data_files + +def _GetTagsForRelPath(relpath): + # Tags. + sub_dir = os.path.dirname(relpath) + if len(sub_dir) == 0: + return [] + parts = sub_dir.split(os.sep) + return [p for p in parts if len(p) > 0] + +def _GetMetadataForFilename(base_directory, filename): + relpath = os.path.relpath(filename, base_directory) + tags = _GetTagsForRelPath(relpath) + + metadata = {'tags': tags} + + # TODO(nduca): Add modification time to metadata. + return metadata + + +class LocalDirectoryCorpusDriver(corpus_driver.CorpusDriver): + def __init__(self, directory): + self.directory = directory + + def GetTraceHandlesMatchingQuery(self, query): + trace_handles = [] + + files = _GetFilesIn(self.directory) + for rel_filename in files: + filename = os.path.join(self.directory, rel_filename) + metadata = _GetMetadataForFilename(self.directory, filename) + + if not query.Eval(metadata, len(trace_handles)): + continue + + run_info = run_info_module.RunInfo( + url="file://%s" % filename, + display_name=rel_filename, + metadata=metadata) + + th = local_file_trace_handle.LocalFileTraceHandle(run_info, filename) + trace_handles.append(th) + + return trace_handles + diff --git a/pool/shard001/Python/0014112_configuration.py b/pool/shard001/Python/0014112_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..878c33bf91f31083f671aea7b2fcc61b2d890125 --- /dev/null +++ b/pool/shard001/Python/0014112_configuration.py @@ -0,0 +1,27 @@ +''' +Created on Oct 10, 2014 + +@author: chris +''' +from ..constants import * + + +def read_config(): + ''' + Reads the toto.vpn configuration file as a dict. + ''' + config = {} + with open(BASE_CONF) as f: + for line in f: + line = line.strip() + if line and not line.startswith('#'): + k, v = line.split('=', 1) + config[k.strip()] = v.strip().strip('"') + return config + + +if __name__ == '__main__': + try: + config = read_config() + except Exception as e: + print 'Failed to read configuration: %s' % e diff --git a/pool/shard001/Python/0014132_observable_dictionary.py b/pool/shard001/Python/0014132_observable_dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b507a940646bc63e55415351fcc8605edde9bb --- /dev/null +++ b/pool/shard001/Python/0014132_observable_dictionary.py @@ -0,0 +1,63 @@ +from observables.observable import Observable +from observables.observed_event import ObservedEvent + + +class ObservableDict(Observable): + + elements = {} + + def __init__(self): + Observable.__init__(self, events=['append', 'update', 'delete']) + self.elements = {} + + ''' + Subscriber methods: + ''' + + def define_append_observer(self, observer): + self.define_observer(observer, 'append') + + def define_update_observer(self, observer): + self.define_observer(observer, 'update') + + def define_delete_observer(self, observer): + self.define_observer(observer, 'delete') + + def define_change_observer(self, observer): + self.define_observer(observer, 'append') + self.define_observer(observer, 'update') + self.define_observer(observer, 'delete') + + ''' + Event helpers: + ''' + + def handle_element_event(self, element, event_type): + event = ObservedEvent(event_type) + event.element = element + self.notify_observers(event) + + ''' + Class methods: + ''' + + def append(self, element): + self.elements[element.get_unique_identifier()] = element + self.handle_element_event(element, 'append') + + def update(self, element): + self.elements[element.get_unique_identifier()] = element + self.handle_element_event(element, 'update') + + def delete(self, element): + del self.elements[element.get_unique_identifier()] + self.handle_element_event(element, 'delete') + + def as_list(self): + return list(self.elements.items()) + + def get(self, identifier): + if identifier in self.elements: + return self.elements[identifier] + else: + return None \ No newline at end of file diff --git a/pool/shard001/Python/0014143_queues.py b/pool/shard001/Python/0014143_queues.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5e7ed6284e3d4b54a8d5b3f120d8e31d309c3d --- /dev/null +++ b/pool/shard001/Python/0014143_queues.py @@ -0,0 +1,111 @@ +# Copyright (C) 2010 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import re + +from model.activeworkitems import ActiveWorkItems +from model.workitems import WorkItems + + +class Queue(object): + + # Eventually the list of queues may be stored in the data store. + _all_queue_names = [ + "commit-queue", + "style-queue", + "chromium-ews", + "qt-ews", + "gtk-ews", + "mac-ews", + "win-ews", + "efl-ews", + "cr-mac-ews", + ] + + def __init__(self, name): + assert(name in self._all_queue_names) + self._name = name + + @classmethod + def queue_with_name(cls, queue_name): + if queue_name not in cls._all_queue_names: + return None + return Queue(queue_name) + + @classmethod + def all(cls): + return [Queue(name) for name in cls._all_queue_names] + + @classmethod + def all_ews(cls): + return [queue for queue in cls.all() if queue.is_ews()] + + def name(self): + return self._name + + def work_items(self): + return WorkItems.lookup_by_queue(self._name) + + # FIXME: active_work_items is a bad name for this lock-table. + def active_work_items(self): + return ActiveWorkItems.lookup_by_queue(self._name) + + def _caplitalize_after_dash(self, string): + return "-".join([word[0].upper() + word[1:] for word in string.split("-")]) + + # For use in status bubbles or table headers + def short_name(self): + # HACK: chromium-ews is incorrectly named. + short_name = self._name.replace("chromium-ews", "Cr-Linux-ews") + short_name = short_name.replace("-ews", "") + short_name = short_name.replace("-queue", "") + return self._caplitalize_after_dash(short_name.capitalize()) + + def display_name(self): + # HACK: chromium-ews is incorrectly named. + display_name = self._name.replace("chromium-ews", "cr-linux-ews") + + display_name = display_name.replace("-", " ") + display_name = display_name.replace("cr", "chromium") + display_name = display_name.title() + display_name = display_name.replace("Ews", "EWS") + return display_name + + _dash_regexp = re.compile("-") + + def name_with_underscores(self): + return self._dash_regexp.sub("_", self._name) + + def is_ews(self): + # Note: The style-queue is just like an EWS in that it has an EWS + # bubble, and it works off of the r? patches. If at some later + # point code wants to not treat the style-queue as an EWS + # (e.g. expecting is_ews() queues to have build results?) + # then we should fix all callers and change this check. + return self._name.endswith("-ews") or self._name == "style-queue" diff --git a/pool/shard001/Python/0014144_ffmpegwrapper.py b/pool/shard001/Python/0014144_ffmpegwrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..cb198970c2c2c212f336a14b3918e3058a55bd18 --- /dev/null +++ b/pool/shard001/Python/0014144_ffmpegwrapper.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python +# coding=utf-8 + +# aeneas is a Python/C library and a set of tools +# to automagically synchronize audio and text (aka forced alignment) +# +# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) +# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) +# Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +""" +This module contains the following classes: + +* :class:`~aeneas.ffmpegwrapper.FFMPEGWrapper`, a wrapper around ``ffmpeg`` to convert audio files; +* :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`, representing a failure to locate the ``ffmpeg`` executable. +""" + +from __future__ import absolute_import +from __future__ import print_function +import subprocess + +from aeneas.logger import Loggable +from aeneas.runtimeconfiguration import RuntimeConfiguration +import aeneas.globalfunctions as gf + + +class FFMPEGPathError(Exception): + """ + Error raised when the path to ``ffmpeg`` is not a valid executable. + + .. versionadded:: 1.4.1 + """ + pass + + +class FFMPEGWrapper(Loggable): + """ + A wrapper around ``ffmpeg`` to convert audio files. + + In abstract terms, it will perform a call like:: + + $ ffmpeg -i /path/to/input.mp3 [parameters] /path/to/output.wav + + :param rconf: a runtime configuration + :type rconf: :class:`~aeneas.runtimeconfiguration.RuntimeConfiguration` + :param logger: the logger object + :type logger: :class:`~aeneas.logger.Logger` + """ + + FFMPEG_SAMPLE_8000 = ["-ar", "8000"] + """ Single parameter for ``ffmpeg``: 8000 Hz sampling """ + + FFMPEG_SAMPLE_16000 = ["-ar", "16000"] + """ Single parameter for ``ffmpeg``: 16000 Hz sampling """ + + FFMPEG_SAMPLE_22050 = ["-ar", "22050"] + """ Single parameter for ``ffmpeg``: 22050 Hz sampling """ + + FFMPEG_SAMPLE_44100 = ["-ar", "44100"] + """ Single parameter for ``ffmpeg``: 44100 Hz sampling """ + + FFMPEG_SAMPLE_48000 = ["-ar", "48000"] + """ Single parameter for ``ffmpeg``: 48000 Hz sampling """ + + FFMPEG_MONO = ["-ac", "1"] + """ Single parameter for ``ffmpeg``: mono (1 channel) """ + + FFMPEG_STEREO = ["-ac", "2"] + """ Single parameter for ``ffmpeg``: stereo (2 channels) """ + + FFMPEG_OVERWRITE = ["-y"] + """ Single parameter for ``ffmpeg``: force overwriting output file """ + + FFMPEG_PLAIN_HEADER = ["-map_metadata", "-1", "-flags", "+bitexact"] + """ Single parameter for ``ffmpeg``: generate WAVE header + without extra chunks (e.g., the INFO chunk) """ + + FFMPEG_FORMAT_WAVE = ["-f", "wav"] + """ Single parameter for ``ffmpeg``: produce output in ``wav`` format + (must be the second to last argument to ``ffmpeg``, + just before path of the output file) """ + + FFMPEG_PARAMETERS_SAMPLE_KEEP = ( + FFMPEG_MONO + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` without changing the sampling rate """ + + FFMPEG_PARAMETERS_SAMPLE_8000 = ( + FFMPEG_MONO + + FFMPEG_SAMPLE_8000 + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` with 8000 Hz sampling """ + + FFMPEG_PARAMETERS_SAMPLE_16000 = ( + FFMPEG_MONO + + FFMPEG_SAMPLE_16000 + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` with 16000 Hz sampling """ + + FFMPEG_PARAMETERS_SAMPLE_22050 = ( + FFMPEG_MONO + + FFMPEG_SAMPLE_22050 + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` with 22050 Hz sampling """ + + FFMPEG_PARAMETERS_SAMPLE_44100 = ( + FFMPEG_MONO + + FFMPEG_SAMPLE_44100 + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` with 44100 Hz sampling """ + + FFMPEG_PARAMETERS_SAMPLE_48000 = ( + FFMPEG_MONO + + FFMPEG_SAMPLE_48000 + + FFMPEG_OVERWRITE + + FFMPEG_PLAIN_HEADER + + FFMPEG_FORMAT_WAVE + ) + """ Set of parameters for ``ffmpeg`` with 48000 Hz sampling """ + + FFMPEG_PARAMETERS_MAP = { + 8000: FFMPEG_PARAMETERS_SAMPLE_8000, + 16000: FFMPEG_PARAMETERS_SAMPLE_16000, + 22050: FFMPEG_PARAMETERS_SAMPLE_22050, + 44100: FFMPEG_PARAMETERS_SAMPLE_44100, + 48000: FFMPEG_PARAMETERS_SAMPLE_48000 + } + """ Map sample rate to parameter list """ + + FFMPEG_PARAMETERS_DEFAULT = FFMPEG_PARAMETERS_SAMPLE_16000 + """ Default set of parameters for ``ffmpeg`` """ + + TAG = u"FFMPEGWrapper" + + def convert( + self, + input_file_path, + output_file_path, + head_length=None, + process_length=None + ): + """ + Convert the audio file at ``input_file_path`` + into ``output_file_path``, + using the parameters set in the constructor + or through the ``parameters`` property. + + You can skip the beginning of the audio file + by specifying ``head_length`` seconds to skip + (if it is ``None``, start at time zero), + and you can specify to convert + only ``process_length`` seconds + (if it is ``None``, process the entire input file length). + + By specifying both ``head_length`` and ``process_length``, + you can skip a portion at the beginning and at the end + of the original input file. + + :param string input_file_path: the path of the audio file to convert + :param string output_file_path: the path of the converted audio file + :param float head_length: skip these many seconds + from the beginning of the audio file + :param float process_length: process these many seconds of the audio file + :raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called + :raises: OSError: if ``input_file_path`` does not exist + or ``output_file_path`` cannot be written + """ + # test if we can read the input file + if not gf.file_can_be_read(input_file_path): + self.log_exc(u"Input file '%s' cannot be read" % (input_file_path), None, True, OSError) + + # test if we can write the output file + if not gf.file_can_be_written(output_file_path): + self.log_exc(u"Output file '%s' cannot be written" % (output_file_path), None, True, OSError) + + # call ffmpeg + arguments = [self.rconf[RuntimeConfiguration.FFMPEG_PATH]] + arguments.extend(["-i", input_file_path]) + if head_length is not None: + arguments.extend(["-ss", head_length]) + if process_length is not None: + arguments.extend(["-t", process_length]) + if self.rconf.sample_rate in self.FFMPEG_PARAMETERS_MAP: + arguments.extend(self.FFMPEG_PARAMETERS_MAP[self.rconf.sample_rate]) + else: + arguments.extend(self.FFMPEG_PARAMETERS_DEFAULT) + arguments.append(output_file_path) + self.log([u"Calling with arguments '%s'", arguments]) + try: + proc = subprocess.Popen( + arguments, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE + ) + proc.communicate() + proc.stdout.close() + proc.stdin.close() + proc.stderr.close() + except OSError as exc: + self.log_exc(u"Unable to call the '%s' ffmpeg executable" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]), exc, True, FFMPEGPathError) + self.log(u"Call completed") + + # check if the output file exists + if not gf.file_exists(output_file_path): + self.log_exc(u"Output file '%s' was not written" % (output_file_path), None, True, OSError) + + # returning the output file path + self.log([u"Returning output file path '%s'", output_file_path]) + return output_file_path diff --git a/pool/shard001/Python/0014151_objects.py b/pool/shard001/Python/0014151_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..488e1358fbaab6505d444965f50cad398948cc81 --- /dev/null +++ b/pool/shard001/Python/0014151_objects.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# This file is part of Viper - https://github.com/viper-framework/viper +# See the file 'LICENSE' for copying permission. + +import os +import hashlib +import binascii +import sys +from viper.common.exceptions import Python2UnsupportedUnicode +import six + +if sys.version_info < (3, 0): + # Make sure the read method returns a byte stream + from io import open + +try: + import pydeep + + HAVE_SSDEEP = True +except ImportError: + HAVE_SSDEEP = False + +try: + import magic +except ImportError: + pass + +try: + from pymisp import MISPEvent +except ImportError: + pass + + +class Singleton(type): + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + + +class MispEvent(object): + def __init__(self, event, offline=False): + if isinstance(event, MISPEvent): + self.event = event + else: + self.event = MISPEvent() + if isinstance(event, six.string_types) and os.path.exists(event): + self.event.load_file(event) + else: + self.event.load(event) + self.off = offline + if self.event.id: + self.current_dump_file = '{}.json'.format(self.event.id) + else: + self.current_dump_file = None + + def online(self): + self.off = False + + def offline(self): + self.off = True + + def get_all_ips(self): + return [a.value for a in self.event.attributes if a.type in ['ip-dst', 'ip-src']] + + def get_all_domains(self): + return [a.value for a in self.event.attributes if a.type in ['domain', 'hostname']] + + def get_all_urls(self): + return [a.value for a in self.event.attributes if a.type == 'url'] + + def get_all_hashes(self): + event_hashes = [] + sample_hashes = [] + for a in self.event.attributes: + h = None + if a.type in ('md5', 'sha1', 'sha256'): + h = a.value + event_hashes.append(h) + elif a.type in ('filename|md5', 'filename|sha1', 'filename|sha256'): + h = a.value.split('|')[1] + event_hashes.append(h) + elif a.type == 'malware-sample': + h = a.value.split('|')[1] + sample_hashes.append(h) + return event_hashes, sample_hashes + + +class File(object): + def __init__(self, path): + self.id = None + self.path = path + self.name = '' + self.size = 0 + self.type = '' + self.mime = '' + self.md5 = '' + self.sha1 = '' + self.sha256 = '' + self.sha512 = '' + self.crc32 = '' + self.ssdeep = '' + self.tags = '' + self.parent = '' + self.children = '' + + if self.is_valid(): + self.name = os.path.basename(self.path) + self.size = os.path.getsize(self.path) + self.type = self.get_type() + self.mime = self.get_mime() + self.get_hashes() + self.ssdeep = self.get_ssdeep() + + @property + def data(self): + with open(self.path, 'rb') as f: + return f.read() + + def is_valid(self): + if not os.path.exists(self.path): + return False + if not os.path.isfile(self.path): + return False + + if sys.version_info < (3, 0): + # on Python2 make sure to only handle ASCII filenames + try: + self.path.decode('ascii') + except UnicodeEncodeError as err: + raise Python2UnsupportedUnicode("Non ASCII character(s) in file name not supported on Python2.\n" + "EncodeError: {}\n" + "File: {}\n" + "Please use Python >= 3.4".format(self.path.encode("utf-8"), err), "error") + except UnicodeDecodeError as err: + raise Python2UnsupportedUnicode("Non ASCII character(s) in file name not supported on Python2.\n" + "DecodeError: {}\n" + "File: {}\n" + "Please use Python >= 3.4".format(self.path, err), "error") + + return True + + def get_chunks(self): + try: + with open(self.path, 'rb') as fd: + while True: + chunk = fd.read(16 * 1024) + if not chunk: + break + yield chunk + except Exception: + return + + def get_hashes(self): + crc = 0 + md5 = hashlib.md5() + sha1 = hashlib.sha1() + sha256 = hashlib.sha256() + sha512 = hashlib.sha512() + + for chunk in self.get_chunks(): + crc = binascii.crc32(chunk, crc) + md5.update(chunk) + sha1.update(chunk) + sha256.update(chunk) + sha512.update(chunk) + + self.crc32 = ''.join('%02X' % ((crc >> i) & 0xff) for i in [24, 16, 8, 0]) + self.md5 = md5.hexdigest() + self.sha1 = sha1.hexdigest() + self.sha256 = sha256.hexdigest() + self.sha512 = sha512.hexdigest() + + def get_ssdeep(self): + if not HAVE_SSDEEP: + return '' + + try: + return pydeep.hash_file(self.path).decode() + except Exception: + return '' + + def get_type(self): + try: + ms = magic.open(magic.MAGIC_NONE) + ms.load() + file_type = ms.file(self.path) + except: + try: + file_type = magic.from_file(self.path) + except: + try: + import subprocess + file_process = subprocess.Popen(['file', '-b', self.path], stdout=subprocess.PIPE) + file_type = file_process.stdout.read().strip() + except: + return '' + finally: + try: + ms.close() + except: + pass + + return file_type + + def get_mime(self): + try: + ms = magic.open(magic.MIME) + ms.load() + mime_type = ms.file(self.path) + except: + try: + mime = magic.Magic(mime=True) + mime_type = mime.from_file(self.path) + except: + return '' + + return mime_type + + +class Dictionary(dict): + """Viper custom dict.""" + + def __getattr__(self, key): + return self.get(key, None) + + __setattr__ = dict.__setitem__ + __delattr__ = dict.__delitem__ diff --git a/pool/shard001/Python/0014153_xres.py b/pool/shard001/Python/0014153_xres.py new file mode 100644 index 0000000000000000000000000000000000000000..822d7dd0e494c60e9dd643ca3641f65aca23ffd4 --- /dev/null +++ b/pool/shard001/Python/0014153_xres.py @@ -0,0 +1,27 @@ +# Copyright 2017 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. + +"""Simply prints out screen resolution.""" + + +import Tkinter + + +def main(): + root = Tkinter.Tk() + print '%sx%s' % (root.winfo_screenwidth(), root.winfo_screenheight()) + root.destroy() + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014157_fibo.py b/pool/shard001/Python/0014157_fibo.py new file mode 100644 index 0000000000000000000000000000000000000000..de5c4c5272f9c2d7e31b6f80036f704e7e6a3339 --- /dev/null +++ b/pool/shard001/Python/0014157_fibo.py @@ -0,0 +1,89 @@ +"""A web app to test multi-threading.""" + +import logging +import sys +import threading +import time + +from google.appengine.api import memcache +from google.appengine.ext import webapp +from google.appengine.ext.webapp import util + +import ndb + + +@ndb.tasklet +def fibonacci(n): + """A recursive Fibonacci to exercise task switching.""" + if n <= 1: + raise ndb.Return(n) + a, b = yield fibonacci(n-1),fibonacci(n-2) + raise ndb.Return(a + b) + + +class FibonacciMemo(ndb.Model): + arg = ndb.IntegerProperty() + value = ndb.IntegerProperty() + + +@ndb.tasklet +def memoizing_fibonacci(n): + """A memoizing recursive Fibonacci to exercise RPCs.""" + if n <= 1: + raise ndb.Return(n) + key = ndb.Key(FibonacciMemo, str(n)) + memo = yield key.get_async(ndb_should_cache=False) + if memo is not None: + assert memo.arg == n + logging.info('memo hit: %d -> %d', n, memo.value) + raise ndb.Return(memo.value) + logging.info('memo fail: %d', n) + a = yield memoizing_fibonacci(n-1) + b = yield memoizing_fibonacci(n-2) + ans = a + b + memo = FibonacciMemo(key=key, arg=n, value=ans) + logging.info('memo write: %d -> %d', n, memo.value) + yield memo.put_async(ndb_should_cache=False) + raise ndb.Return(ans) + + +TRUE_VALUES = frozenset(['1', 'on', 't', 'true', 'y', 'yes']) + + +class FiboHandler(webapp.RequestHandler): + + @ndb.toplevel + def get(self): + num = 10 + try: + num = int(self.request.get('num')) + except Exception: + pass + if self.request.get('reset') in TRUE_VALUES: + logging.info('flush') + yield ndb.delete_multi_async(x.key for x in FibonacciMemo.query()) + t0 = time.time() + if self.request.get('memo') in TRUE_VALUES: + memo_type = 'memoizing ' + ans = yield memoizing_fibonacci(num) + else: + memo_type = '' + ans = yield fibonacci(num) + t1 = time.time() + self.response.out.write('%sfibonacci(%d) == %d # computed in %.3f\n' % + (memo_type, num, ans, t1-t0)) + + +urls = [ + ('/fibo', FiboHandler), + ] + +app = webapp.WSGIApplication(urls) + + +def main(): + util.run_wsgi_app(app) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014164_release.py b/pool/shard001/Python/0014164_release.py new file mode 100644 index 0000000000000000000000000000000000000000..0921d827b12a271cc61c16d5415d2f6fc0d34463 --- /dev/null +++ b/pool/shard001/Python/0014164_release.py @@ -0,0 +1,9 @@ +import os +import shutil + +with open('bin/.vale_version') as f: + version = f.read().splitlines()[0] +release = f'vale-release-{version}' +print(release) +shutil.copytree('bin', f'releases/{release}/{release}/bin', ignore = shutil.ignore_patterns('z3.exe')) +shutil.make_archive(f'releases/{release}', 'zip', f'releases/{release}') diff --git a/pool/shard001/Python/0014171_test_elementfinder.py b/pool/shard001/Python/0014171_test_elementfinder.py new file mode 100644 index 0000000000000000000000000000000000000000..beeaabc681d7054843359b6d00d4c2927e01c004 --- /dev/null +++ b/pool/shard001/Python/0014171_test_elementfinder.py @@ -0,0 +1,29 @@ +import unittest + +import mock + +from AppiumLibrary.locators import ElementFinder + + +class ElementFinderTests(unittest.TestCase): + """ElementFinder keyword test class.""" + + def setUp(self): + """Instantiate the element finder class.""" + self.browser = mock.Mock() + self.finder = ElementFinder() + + def test_should_have_strategies(self): + """Element Finder instance should contain expected strategies.""" + self.assertTrue('android' in self.finder._strategies) + self.assertTrue('ios' in self.finder._strategies) + + def test_should_use_android_finder(self): + """android strategy should use android finder.""" + self.finder.find(self.browser, 'android=UI Automator', tag=None) + self.browser.find_elements_by_android_uiautomator.assert_called_with("UI Automator") + + def test_should_use_ios_finder(self): + """ios strategy should use ios finder.""" + self.finder.find(self.browser, 'ios=UI Automation', tag=None) + self.browser.find_elements_by_ios_uiautomation.assert_called_with("UI Automation") diff --git a/pool/shard001/Python/0014173_twitter_data_fetcher.py b/pool/shard001/Python/0014173_twitter_data_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef0ac411c381b82e48c8fd62b71175bc5f3a9b4 --- /dev/null +++ b/pool/shard001/Python/0014173_twitter_data_fetcher.py @@ -0,0 +1,151 @@ +import logging +import pprint + +import tweepy + + +class PrettyJson(): + def __init__(self, obj): + self.obj = obj + + def __repr__(self): + return pprint.pformat(self.obj) + + +class DataFetcher: + def __init__(self, config_name, auth): + ######################################################################## + # Read config for tweets collection + ######################################################################## + from configparser import ConfigParser + self.auth = auth + self.api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) + self.config_name = config_name + config = ConfigParser() + config.read(config_name) + # self.config = config + self.friends_no_to_retrieve = int(config['general']['friends_no_to_retrieve']) + self.friends_sort_by = config['general']['friends_sort_by'] + self.tweets_no_per_friend = int(config['general']['tweets_no_per_friend']) + + # Display progress logs on stdout + logging.basicConfig(level=logging.INFO, + format='>>> %(asctime)s %(levelname)s %(message)s') + + self.friends_fields = ['id', 'screen_name', 'created_at', 'lang', 'followers_count', 'friends_count', + 'following', 'location', 'statuses_count', 'time_zone', 'url', 'verified'] + + global api + api = self.api + + ######################################################################## + # Retrieve the list of friends (who specified account following) + ######################################################################## + def get_list_of_friends(self, account_name): + """ + Retrieve list of friends for specified screen_name (account_name) and return corresponding fields. + :param account_name: screen_name + :return: + """ + friends_no_to_retrieve = self.friends_no_to_retrieve + friends_fields = self.friends_fields + friends_sort_by = self.friends_sort_by + + logging.info("Retrieving the list of friends") + all_friends_to_be_sorted = [] + for friend in tweepy.Cursor(api.friends, screen_name=account_name).items(friends_no_to_retrieve): + friend_short = {} + for k, v in friend._json.items(): + if k in friends_fields: + friend_short[k] = v + # pprint.pprint(friend._json) + # print('\n') + # pprint.pprint(friend_json_short) + all_friends_to_be_sorted.append(friend_short) + logging.debug('Retrieved info for friend {}'.format(friend_short['screen_name'])) + # print('\n') + + # pprint.pprint(all_friends_sorted) + all_friends_sorted = sorted(all_friends_to_be_sorted, key=lambda key: key[friends_sort_by]) + return all_friends_sorted + + def download_friends_timeline(self, target_user): + try: + redirect_url = self.auth.get_authorization_url() + except tweepy.TweepError: + print('Error! Failed to get request token.') + + def timeline_shortener(timeline, parent_user): + tweet_fields = {'created_at', 'favorite_count', 'id', 'lang', 'retweet_count', 'text'} + timeline_short = [] + try: + for twt in timeline: + # pprint.pprint(twt) + tweet_short = {} + for field, value in twt.items(): + if field in tweet_fields: + tweet_short[field] = value + if twt['place'] is None: + tweet_short['country'] = None + tweet_short['country_code'] = None + else: + tweet_short['country'] = twt['place']['country'] + tweet_short['country_code'] = twt['place']['country_code'] + timeline_short.append(tweet_short) + # pprint.pprint(timeline_short) + # print() + item = { + 'tweets': timeline_short, + 'n_tweets': len(timeline_short), + 'screen_name': timeline[0]['user']['screen_name'], + 'user_id': timeline[0]['user']['id'], + 'lang': timeline[0]['lang'], + 'parent_account': parent_user + } + except Exception as e: + logging.error("Unable to process data for user {}".format(parent_user), e) + + return item + + ######################################################################## + # Retrieve and save tweets for top friends + ######################################################################## + def get_user_timeline(account_name, tweets_no_per_friend=self.tweets_no_per_friend): + """ + Retrieve specified number of tweets for screen_name "account_name". + :param account_name: + :param tweets_no_per_friend: + :return: tweets (list of jsons) + """ + tweets = [] + logging.info('Retrieve most recent tweets for user {}'.format(account_name)) + try: + for status in tweepy.Cursor(api.user_timeline, id=account_name).items(tweets_no_per_friend): + # pprint.pprint(status._json) + # print('\n\n\n') + tweets.append(status._json) + except Exception as e: + logging.error("FAILED: Unexpected error: " + str(e)) # sys.exc_info()[0]) + return tweets + + ######################################################################## + # Main part + ######################################################################## + # Initialise Mongo DB + from twitter_data_to_mongodb import MongoDBHandler + mongodb = MongoDBHandler('credentials.ini') + + # get tweets for user's friends, but for user first + all_friends = self.get_list_of_friends(target_user) + all_tweets = [] + + for friend in all_friends[:self.friends_no_to_retrieve + 1]: + tweets_item = timeline_shortener(get_user_timeline(friend['screen_name']), target_user) + logging.debug(PrettyJson(tweets_item)) + all_tweets.append(tweets_item) + print("Saving tweets to Mongo DB") + mongodb.save_user_timeline(tweets_item) + # all_tweets[target_user] = get_user_timeline(target_user) + return all_tweets + + diff --git a/pool/shard001/Python/0014174_fourier.py b/pool/shard001/Python/0014174_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..579e9290f1c59ce01e7ff3c08e334cb7786ff817 --- /dev/null +++ b/pool/shard001/Python/0014174_fourier.py @@ -0,0 +1,96 @@ +from .imag_ffts import _ImagFFTBasis +import numpy as np + + +class FourierBasis(_ImagFFTBasis): + + r""" + Discretize a continuous field into `deg` local states using complex + exponentials such that, + + .. math:: + + \frac{1}{\Delta x} \int_s m(h, x) dx = + \sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) + + and the local state space :math:`H` is mapped into the orthogonal domain + + .. math:: + + 0 \le H \le 2 \pi + + The mapping of :math:`H` into the domain is done automatically in PyMKS by + using the `domain` key work argument. + + >>> n_states = 3 + >>> X = np.array([[0., np.pi / 3], + ... [2 * np.pi / 3, 2 * np.pi]]) + >>> X_result = np.array(([[[1, 1, 1], + ... [1, np.exp(np.pi / 3 * 1j), + ... np.exp(- np.pi / 3 * 1j)]], + ... [[1, np.exp(2 *np.pi / 3 * 1j), + ... np.exp(- 2 * np.pi / 3 * 1j)], + ... [1, 1, 1]]])) + >>> basis = FourierBasis(n_states, [0., 2 * np.pi]) + >>> assert(np.allclose(basis.discretize(X), X_result)) + + If the microstructure local state values fall outside of the period of + the specified domain, the values will be mapped back into the domain. + + >>> n_states = 2 + >>> X = np.array([[0, 1.5]]) + >>> four_basis = FourierBasis(n_states, domain=[0, 1]) + >>> X_result = np.array([[[1, 1], + ... [1, -1]]]) + >>> assert np.allclose(X_result, four_basis.discretize(X)) + """ + + def __init__(self, n_states=5, domain=None): + + r""" + Instantiate a `FourierBasis` + + Args: + n_states (int, list): The number of local states, or list of local + states to be used. + domain (list, optional): indicate the range of expected values for + the microstructure, default is [0, 2\pi]. + """ + self.n_states = n_states + if isinstance(self.n_states, int): + n_states = ((np.arange(self.n_states + 1) // 2)[1:] * + (-1) ** np.arange(1, self.n_states + 1)) + if domain is None: + domain = [0, 2. * np.pi] + super(FourierBasis, self).__init__(n_states=n_states, domain=domain) + + def discretize(self, X): + """ + Discretize `X`. + + Args: + X (ND array): The microstructure, an `(n_samples, n_x, ...)` + shaped array where `n_samples` is the number of samples and + `n_x` is the spatial discretization. + Returns: + Float valued field of Fourier series coefficients in the following + order 0, 1, ,-1, 2, -2, with shaped `(n_samples, n_x, ..., + n_states)`. + + >>> X = np.array([[-1, -1./2, 0., 1./2, 1]]) + >>> f_basis = FourierBasis(4, [-1, 1.]) + >>> X_result = np.array([[[1, 1, 1, 1], + ... [1, 1j, -1j, -1], + ... [1, -1, -1, 1], + ... [1, -1j, 1j, -1], + ... [1, 1, 1, 1]]]) + >>> assert(np.allclose(X_result, f_basis.discretize(X))) + + """ + self._select_axes(X) + X_scaled = 2. * np.pi * ((X.astype(float) - self.domain[0]) / + (self.domain[1] - self.domain[0])) + nones = ([None for i in X.shape]) + X_states = np.zeros(X_scaled.shape + (len(self.n_states),)) + X_states[..., :] = np.array(self.n_states)[nones] + return np.exp(X_scaled[..., None] * X_states * 1j) diff --git a/pool/shard001/Python/0014190_flickr.py b/pool/shard001/Python/0014190_flickr.py new file mode 100644 index 0000000000000000000000000000000000000000..4efa78ef45e4c66576103b613967234eaf0ba8c0 --- /dev/null +++ b/pool/shard001/Python/0014190_flickr.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python + +__all__ = ['flickr_download_main'] + +from ..common import * + +import json + +pattern_url_photoset = r'https?://www\.flickr\.com/photos/.+/(?:(?:sets)|(?:albums))?/([^/]+)' +pattern_url_photostream = r'https?://www\.flickr\.com/photos/([^/]+)(?:/|(?:/page))?$' +pattern_url_single_photo = r'https?://www\.flickr\.com/photos/[^/]+/(\d+)' +pattern_url_gallery = r'https?://www\.flickr\.com/photos/[^/]+/galleries/(\d+)' +pattern_url_group = r'https?://www\.flickr\.com/groups/([^/]+)' +pattern_url_favorite = r'https?://www\.flickr\.com/photos/([^/]+)/favorites' + +pattern_inline_title = r'([^<]*)' +pattern_inline_api_key = r'api\.site_key\s*=\s*"([^"]+)"' +pattern_inline_img_url = r'"url":"([^"]+)","key":"[^"]+"}}' +pattern_inline_NSID = r'"nsid"\s*:\s*"([^"]+)"' +pattern_inline_video_mark = r'("mediaType":"video")' + +# (api_key, method, ext, page) +tmpl_api_call = ( + 'https://api.flickr.com/services/rest?' + '&format=json&nojsoncallback=1' + # UNCOMMENT FOR TESTING + #'&per_page=5' + '&per_page=500' + # this parameter CANNOT take control of 'flickr.galleries.getPhotos' + # though the doc said it should. + # it's always considered to be 500 + '&api_key=%s' + '&method=flickr.%s' + '&extras=url_sq,url_q,url_t,url_s,url_n,url_m,url_z,url_c,url_l,url_h,url_k,url_o,media' + '%s&page=%d' +) + +tmpl_api_call_video_info = ( + 'https://api.flickr.com/services/rest?' + '&format=json&nojsoncallback=1' + '&method=flickr.video.getStreamInfo' + '&api_key=%s' + '&photo_id=%s' + '&secret=%s' +) + +tmpl_api_call_photo_info = ( + 'https://api.flickr.com/services/rest?' + '&format=json&nojsoncallback=1' + '&method=flickr.photos.getInfo' + '&api_key=%s' + '&photo_id=%s' +) + +# looks that flickr won't return urls for all sizes +# we required in 'extras field without a acceptable header +dummy_header = { + 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0' +} +def get_content_headered(url): + return get_content(url, dummy_header) + +def get_photoset_id(url, page): + return match1(url, pattern_url_photoset) + +def get_photo_id(url, page): + return match1(url, pattern_url_single_photo) + +def get_gallery_id(url, page): + return match1(url, pattern_url_gallery) + +def get_api_key(page): + match = match1(page, pattern_inline_api_key) + # this happens only when the url points to a gallery page + # that contains no inline api_key(and never makes xhr api calls) + # in fact this might be a better approch for getting a temporary api key + # since there's no place for a user to add custom infomation that may + # misguide the regex in the homepage + if not match: + return match1(get_html('https://flickr.com'), pattern_inline_api_key) + return match + +def get_NSID(url, page): + return match1(page, pattern_inline_NSID) + +# [ +# ( +# regex_match_url, +# remote_api_method, +# additional_query_parameter_for_method, +# parser_for_additional_parameter, +# field_where_photourls_are_saved +# ) +# ] +url_patterns = [ + # www.flickr.com/photos/{username|NSID}/sets|albums/{album-id} + ( + pattern_url_photoset, + 'photosets.getPhotos', + 'photoset_id', + get_photoset_id, + 'photoset' + ), + # www.flickr.com/photos/{username|NSID}/{pageN}? + ( + pattern_url_photostream, + # according to flickr api documentation, this method needs to be + # authenticated in order to filter photo visible to the calling user + # but it seems works fine anonymously as well + 'people.getPhotos', + 'user_id', + get_NSID, + 'photos' + ), + # www.flickr.com/photos/{username|NSID}/galleries/{gallery-id} + ( + pattern_url_gallery, + 'galleries.getPhotos', + 'gallery_id', + get_gallery_id, + 'photos' + ), + # www.flickr.com/groups/{groupname|groupNSID}/ + ( + pattern_url_group, + 'groups.pools.getPhotos', + 'group_id', + get_NSID, + 'photos' + ), + # www.flickr.com/photos/{username|NSID}/favorites/* + ( + pattern_url_favorite, + 'favorites.getList', + 'user_id', + get_NSID, + 'photos' + ) +] + +def flickr_download_main(url, output_dir = '.', merge = False, info_only = False, **kwargs): + urls = None + size = 'o' # works for collections only + title = None + if 'stream_id' in kwargs: + size = kwargs['stream_id'] + if match1(url, pattern_url_single_photo): + url, title = get_single_photo_url(url) + urls = [url] + else: + urls, title = fetch_photo_url_list(url, size) + index = 0 + for url in urls: + mime, ext, size = url_info(url) + print_info('Flickr.com', title, mime, size) + if not info_only: + suffix = '[%d]' % index + download_urls([url], title + suffix, ext, False, output_dir, None, False, False) + index = index + 1 + +def fetch_photo_url_list(url, size): + for pattern in url_patterns: + # FIXME: fix multiple matching since the match group is dropped + if match1(url, pattern[0]): + return fetch_photo_url_list_impl(url, size, *pattern[1:]) + raise NotImplementedError('Flickr extractor is not supported for %s.' % url) + +def fetch_photo_url_list_impl(url, size, method, id_field, id_parse_func, collection_name): + page = get_html(url) + api_key = get_api_key(page) + ext_field = '' + if id_parse_func: + ext_field = '&%s=%s' % (id_field, id_parse_func(url, page)) + page_number = 1 + urls = [] + while True: + call_url = tmpl_api_call % (api_key, method, ext_field, page_number) + photoset = json.loads(get_content_headered(call_url))[collection_name] + pagen = photoset['page'] + pages = photoset['pages'] + for info in photoset['photo']: + url = get_url_of_largest(info, api_key, size) + urls.append(url) + page_number = page_number + 1 + # the typeof 'page' and 'pages' may change in different methods + if str(pagen) == str(pages): + break + return urls, match1(page, pattern_inline_title) + +# image size suffixes used in inline json 'key' field +# listed in descending order +size_suffixes = ['o', 'k', 'h', 'l', 'c', 'z', 'm', 'n', 's', 't', 'q', 'sq'] + +def get_orig_video_source(api_key, pid, secret): + parsed = json.loads(get_content_headered(tmpl_api_call_video_info % (api_key, pid, secret))) + for stream in parsed['streams']['stream']: + if stream['type'] == 'orig': + return stream['_content'].replace('\\', '') + return None + +def get_url_of_largest(info, api_key, size): + if info['media'] == 'photo': + sizes = size_suffixes + if size in sizes: + sizes = sizes[sizes.index(size):] + for suffix in sizes: + if 'url_' + suffix in info: + return info['url_' + suffix].replace('\\', '') + return None + else: + return get_orig_video_source(api_key, info['id'], info['secret']) + +def get_single_photo_url(url): + page = get_html(url) + pid = get_photo_id(url, page) + title = match1(page, pattern_inline_title) + if match1(page, pattern_inline_video_mark): + api_key = get_api_key(page) + reply = get_content(tmpl_api_call_photo_info % (api_key, get_photo_id(url, page))) + secret = json.loads(reply)['photo']['secret'] + return get_orig_video_source(api_key, pid, secret), title + #last match always has the best resolution + match = match1(page, pattern_inline_img_url) + return 'https:' + match.replace('\\', ''), title + +site_info = "Flickr.com" +download = flickr_download_main +download_playlist = playlist_not_supported('flickr'); diff --git a/pool/shard001/Python/0014191_test_tick_processors.py b/pool/shard001/Python/0014191_test_tick_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..8df5dc097965dca8b16978461b6524d072ed989d --- /dev/null +++ b/pool/shard001/Python/0014191_test_tick_processors.py @@ -0,0 +1,103 @@ +# Copyright (c) 2011, Found IT A/S and Piped Project Contributors. +# See LICENSE for details. +from twisted.application import service +from twisted.internet import defer +from twisted.trial import unittest + +from piped import processing, util +from piped.processors import tick_processors +from piped.providers import tick_provider + + +class TickProcessorTest(unittest.TestCase): + timeout = 1 + + def setUp(self): + self.runtime_environment = processing.RuntimeEnvironment() + self.runtime_environment.application = service.MultiService() + self.runtime_environment.application.startService() + + self.runtime_environment.resource_manager.register('pipeline.test_pipeline', self) + + self.dependency_manager = self.runtime_environment.dependency_manager + self.dependency_manager.configure(self.runtime_environment) + + self.provider = tick_provider.TickProvider() + self.provider.setServiceParent(self.runtime_environment.application) + + self.intervals = dict() + self.runtime_environment.configuration_manager.set('ticks.interval', self.intervals) + + self.start_processor = tick_processors.StartInterval('test_interval') + self.stop_processor = tick_processors.StopInterval('test_interval') + + self.ticks = defer.DeferredQueue() + + def tearDown(self): + self.runtime_environment.application.stopService() + + def add_consumer(self, resource_dependency): + resource_dependency.on_resource_ready(self.process) + + def process(self, baton): + return self.ticks.put(baton) + + @defer.inlineCallbacks + def test_starting_an_interval(self): + self.intervals['test_interval'] = dict(interval=0, auto_start=False, processor='pipeline.test_pipeline') + + self.provider.configure(self.runtime_environment) + self.start_processor.configure(self.runtime_environment) + self.dependency_manager.resolve_initial_states() + + # since the interval isn't started, no ticks should have been created + self.assertEquals(self.ticks.pending, list()) + + # running the start processor should start the ticking: + self.start_processor.process(dict()) + yield self.ticks.get() + self.assertEquals(self.ticks.pending, list()) + + @defer.inlineCallbacks + def test_stopping_an_interval(self): + self.intervals['test_interval'] = dict(interval=0, processor='pipeline.test_pipeline') + + self.provider.configure(self.runtime_environment) + self.stop_processor.configure(self.runtime_environment) + self.dependency_manager.resolve_initial_states() + + # the interval autostarts and produces a tick + self.assertEquals(len(self.ticks.pending), 1) + yield self.ticks.get() + + # running the stop processor should stop the ticking: + yield self.stop_processor.process(dict()) + yield util.wait(0) + self.assertEquals(self.ticks.pending, list()) + + @defer.inlineCallbacks + def test_restarting_an_interval(self): + self.intervals['test_interval'] = dict(interval=0, auto_start=False, processor='pipeline.test_pipeline') + + self.provider.configure(self.runtime_environment) + self.start_processor.configure(self.runtime_environment) + self.stop_processor.configure(self.runtime_environment) + self.dependency_manager.resolve_initial_states() + + # since the interval isn't started, no ticks should have been created + self.assertEquals(self.ticks.pending, list()) + + # running the start processor should start the ticking: + self.start_processor.process(dict()) + yield self.ticks.get() + self.assertEquals(self.ticks.pending, list()) + + # running the stop processor should stop the ticking: + yield self.stop_processor.process(dict()) + yield util.wait(0) + self.assertEquals(self.ticks.pending, list()) + + # running the start processor again should restart the ticking: + self.start_processor.process(dict()) + yield self.ticks.get() + self.assertEquals(self.ticks.pending, list()) \ No newline at end of file diff --git a/pool/shard001/Python/0014196_test_haar_cascade.py b/pool/shard001/Python/0014196_test_haar_cascade.py new file mode 100644 index 0000000000000000000000000000000000000000..1942ccf771efc1727327614fd3e4737f70ce04e0 --- /dev/null +++ b/pool/shard001/Python/0014196_test_haar_cascade.py @@ -0,0 +1,30 @@ +#!/usr/bin/python + +from SimpleCV import * + +FACECASCADE = 'face.xml' + +testimage = "sampleimages/orson_welles.jpg" +testoutput = "sampleimages/orson_welles_face.jpg" + +testneighbor_in = "sampleimages/04000.jpg" +testneighbor_out = "sampleimages/04000_face.jpg" + +def test_haarcascade(): + img = Image(testimage) + faces = img.findHaarFeatures(FACECASCADE) + + if (faces): + faces.draw() + img.save(testoutput) + else: + assert False + +def test_minneighbors(img_in=testneighbor_in, img_out=testneighbor_out): + img = Image(img_in) + faces = img.findHaarFeatures(FACECASCADE, min_neighbors=20) + if faces: + faces.draw() + img.save(img_out) + # if len(faces) > 1 + assert len(faces) <= 1, "Haar Cascade is potentially ignoring the 'HIGH' min_neighbors of 20" diff --git a/pool/shard001/Python/0014202_foo.py b/pool/shard001/Python/0014202_foo.py new file mode 100644 index 0000000000000000000000000000000000000000..623aeb155c3ed274ef31a1634e3ae9c2a89be55d --- /dev/null +++ b/pool/shard001/Python/0014202_foo.py @@ -0,0 +1,21 @@ +try: + x=2; y=3; + if(x>y): + result = x; + else: + result = y; + print(result) + print("FIRST CASE:\nOK\n") + for i in "qwerty": + if ord(i) < 100: + print(i) + print("SECOND CASE:\nBAD INDENTATION OF CODE\n") + for i in "axby": + if ord(i) < 100: + print(ord(i)) + else: + i + print("\nTHIRD CASE:\nBAD INDENTATION OF CODE\nBADLY PLACED IF\ + \nAMBIVALENT ELSE [if or for clause]\n") +except Error as e: + print(e) diff --git a/pool/shard001/Python/0014206_scripts.py b/pool/shard001/Python/0014206_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..53379c3c2cbafa6d6635d47332aed2425ee7672e --- /dev/null +++ b/pool/shard001/Python/0014206_scripts.py @@ -0,0 +1,30 @@ +import logging + +from org.openbaton.v2.cmd import BaseObCmd +from org.openbaton.v2.errors import ActionNotSupported +from org.openbaton.v2.utils import get_result_to_list, get_result_to_show, parse_path_or_json, result_to_str + + +class Scripts(BaseObCmd): + """Command to manage Scripts. It allows to: + * show a Script passing an id + """ + + log = logging.getLogger(__name__) + keys_to_list = ["id", "name", "vendor", "version"] + keys_to_exclude = [] + + def find(self, params): + if not params: + return "ERROR: missing " + script_id = params[0] + return "".join(chr(i) for i in self.app.ob_client.get_script(script_id).get("payload")) + + def create(self, params): + raise ActionNotSupported("Action 'create' is not supported") + + def delete(self, params): + raise ActionNotSupported("Action 'delete' is not supported") + + def list(self, params=None): + raise ActionNotSupported("Action 'list' is not supported") diff --git a/pool/shard001/Python/0014207_package.py b/pool/shard001/Python/0014207_package.py new file mode 100644 index 0000000000000000000000000000000000000000..075f7fa0000778e04850ba04ad33d2199a23eb3b --- /dev/null +++ b/pool/shard001/Python/0014207_package.py @@ -0,0 +1,21 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from spack import * + + +class PyBigfloat(PythonPackage): + """Arbitrary-precision correctly-rounded floating-point arithmetic, via MPFR.""" + + homepage = "https://github.com/mdickinson/bigfloat" + pypi = "bigfloat/bigfloat-0.4.0.tar.gz" + + version('0.4.0', sha256='58b96bde872aca5989d13d82eba3acf2aa1b94e22117dd72a16ba5911b0c0cb8') + + depends_on('python@2.7:2.8,3.5:', type=('build', 'run')) + depends_on('py-setuptools', type='build') + depends_on('py-six', type=('build', 'run')) + depends_on('gmp', type='link') + depends_on('mpfr', type=('build', 'link')) diff --git a/pool/shard001/Python/0014213_minidns.py b/pool/shard001/Python/0014213_minidns.py new file mode 100644 index 0000000000000000000000000000000000000000..5da77a53e58c3119e5282ae9dbcc8290b0e00c9c --- /dev/null +++ b/pool/shard001/Python/0014213_minidns.py @@ -0,0 +1,206 @@ +# Copyright 2011 Andrew Bogott for the Wikimedia Foundation +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import os + +from oslo_config import cfg +from oslo_log import log as logging +import six + +from nova import exception +from nova.i18n import _ +from nova.network import dns_driver + + +CONF = cfg.CONF +LOG = logging.getLogger(__name__) + + +class MiniDNS(dns_driver.DNSDriver): + """Trivial DNS driver. This will read/write to either a local, + flat file or an in memory StringIO and have no effect on your actual + DNS system. This class is strictly for testing purposes, and should + keep you out of dependency hell. + + A file is used when CONF.log_dir is set. This is relevant for when + two different DNS driver instances share the same data file. + + Note that there is almost certainly a race condition here that + will manifest anytime instances are rapidly created and deleted. + A proper implementation will need some manner of locking. + """ + + def __init__(self): + filename = None + if CONF.log_dir: + filename = os.path.join(CONF.log_dir, "dnstest.txt") + self.file = open(filename, 'w+') + else: + self.file = six.StringIO() + if not filename or not os.path.exists(filename): + self.file.write("# minidns\n\n\n") + self.file.flush() + + def get_domains(self): + entries = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if entry and entry['address'] == 'domain': + entries.append(entry['name']) + return entries + + def qualify(self, name, domain): + if domain: + qualified = "%s.%s" % (name, domain) + else: + qualified = name + + return qualified.lower() + + def create_entry(self, name, address, type, domain): + if name is None: + raise exception.InvalidInput(_("Invalid name")) + + if type.lower() != 'a': + raise exception.InvalidInput(_("This driver only supports " + "type 'a'")) + + if self.get_entries_by_name(name, domain): + raise exception.FloatingIpDNSExists(name=name, domain=domain) + + self.file.seek(0, os.SEEK_END) + self.file.write("%s %s %s\n" % + (address, self.qualify(name, domain), type)) + self.file.flush() + + def parse_line(self, line): + vals = line.split() + if len(vals) < 3: + return None + else: + entry = {} + entry['address'] = vals[0].lower() + entry['name'] = vals[1].lower() + entry['type'] = vals[2].lower() + if entry['address'] == 'domain': + entry['domain'] = entry['name'] + else: + entry['domain'] = entry['name'].partition('.')[2] + return entry + + def delete_entry(self, name, domain): + if name is None: + raise exception.InvalidInput(_("Invalid name")) + + deleted = False + keeps = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if (not entry or + entry['name'] != self.qualify(name, domain)): + keeps.append(line) + else: + deleted = True + self.file.truncate(0) + self.file.seek(0) + self.file.write(''.join(keeps)) + self.file.flush() + if not deleted: + LOG.warning('Cannot delete entry |%s|', self.qualify(name, domain)) + raise exception.NotFound + + def modify_address(self, name, address, domain): + + if not self.get_entries_by_name(name, domain): + raise exception.NotFound + + lines = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if (entry and + entry['name'] == self.qualify(name, domain)): + lines.append("%s %s %s\n" % + (address, self.qualify(name, domain), entry['type'])) + else: + lines.append(line) + self.file.truncate(0) + self.file.seek(0) + self.file.write(''.join(lines)) + self.file.flush() + + def get_entries_by_address(self, address, domain): + entries = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if entry and entry['address'] == address.lower(): + if entry['name'].endswith(domain.lower()): + name = entry['name'].split(".")[0] + if name not in entries: + entries.append(name) + + return entries + + def get_entries_by_name(self, name, domain): + entries = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if (entry and + entry['name'] == self.qualify(name, domain)): + entries.append(entry['address']) + return entries + + def delete_dns_file(self): + self.file.close() + try: + if os.path.exists(self.file.name): + try: + os.remove(self.file.name) + except OSError: + pass + except AttributeError: + # This was a BytesIO, which has no name. + pass + + def create_domain(self, fqdomain): + if self.get_entries_by_name(fqdomain, ''): + raise exception.FloatingIpDNSExists(name=fqdomain, domain='') + + self.file.seek(0, os.SEEK_END) + self.file.write("%s %s %s\n" % ('domain', fqdomain, 'domain')) + self.file.flush() + + def delete_domain(self, fqdomain): + deleted = False + keeps = [] + self.file.seek(0) + for line in self.file: + entry = self.parse_line(line) + if (not entry or + entry['domain'] != fqdomain.lower()): + keeps.append(line) + else: + LOG.info("deleted %s", entry) + deleted = True + self.file.truncate(0) + self.file.seek(0) + self.file.write(''.join(keeps)) + self.file.flush() + if not deleted: + LOG.warning('Cannot delete domain |%s|', fqdomain) + raise exception.NotFound diff --git a/pool/shard001/Python/0014219_visualize.py b/pool/shard001/Python/0014219_visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..60c26c981cb883f318b1291e30906c3b8240c2db --- /dev/null +++ b/pool/shard001/Python/0014219_visualize.py @@ -0,0 +1,219 @@ +# #START_LICENSE########################################################### +# +# +# This file is part of the Environment for Tree Exploration program +# (ETE). http://etetoolkit.org +# +# ETE is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# ETE is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +# License for more details. +# +# You should have received a copy of the GNU General Public License +# along with ETE. If not, see . +# +# +# ABOUT THE ETE PACKAGE +# ===================== +# +# ETE is distributed under the GPL copyleft license (2008-2015). +# +# If you make use of ETE in published work, please cite: +# +# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. +# ETE: a python Environment for Tree Exploration. Jaime BMC +# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 +# +# Note that extra references to the specific methods implemented in +# the toolkit may be available in the documentation. +# +# More info at http://etetoolkit.org. Contact: huerta@embl.de +# +# +# #END_LICENSE############################################################# +import re + +def draw_tree(tree, conf, outfile): + try: + from ete2 import (add_face_to_node, AttrFace, TextFace, TreeStyle, RectFace, CircleFace, + SequenceFace, random_color, SeqMotifFace) + except ImportError as e: + print e + return + + def ly_basic(node): + if node.is_leaf(): + node.img_style['size'] = 0 + else: + node.img_style['size'] = 0 + node.img_style['shape'] = 'square' + if len(MIXED_RES) > 1 and hasattr(node, "tree_seqtype"): + if node.tree_seqtype == "nt": + node.img_style["bgcolor"] = "#CFE6CA" + ntF = TextFace("nt", fsize=6, fgcolor='#444', ftype='Helvetica') + add_face_to_node(ntF, node, 10, position="branch-bottom") + if len(NPR_TREES) > 1 and hasattr(node, "tree_type"): + node.img_style['size'] = 4 + node.img_style['fgcolor'] = "steelblue" + + node.img_style['hz_line_width'] = 1 + node.img_style['vt_line_width'] = 1 + + def ly_leaf_names(node): + if node.is_leaf(): + spF = TextFace(node.species, fsize=10, fgcolor='#444444', fstyle='italic', ftype='Helvetica') + add_face_to_node(spF, node, column=0, position='branch-right') + if hasattr(node, 'genename'): + geneF = TextFace(" (%s)" %node.genename, fsize=8, fgcolor='#777777', ftype='Helvetica') + add_face_to_node(geneF, node, column=1, position='branch-right') + + def ly_supports(node): + if not node.is_leaf() and node.up: + supFace = TextFace("%0.2g" %(node.support), fsize=7, fgcolor='indianred') + add_face_to_node(supFace, node, column=0, position='branch-top') + + def ly_tax_labels(node): + if node.is_leaf(): + c = LABEL_START_COL + largest = 0 + for tname in TRACKED_CLADES: + if hasattr(node, "named_lineage") and tname in node.named_lineage: + linF = TextFace(tname, fsize=10, fgcolor='white') + linF.margin_left = 3 + linF.margin_right = 2 + linF.background.color = lin2color[tname] + add_face_to_node(linF, node, c, position='aligned') + c += 1 + + for n in xrange(c, len(TRACKED_CLADES)): + add_face_to_node(TextFace('', fsize=10, fgcolor='slategrey'), node, c, position='aligned') + c+=1 + + def ly_full_alg(node): + pass + + def ly_block_alg(node): + if node.is_leaf(): + if 'sequence' in node.features: + seqFace = SeqMotifFace(node.sequence, []) + # [10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name"], + motifs = [] + last_lt = None + for c, lt in enumerate(node.sequence): + if lt != '-': + if last_lt is None: + last_lt = c + if c+1 == len(node.sequence): + start, end = last_lt, c + motifs.append([start, end, "()", 0, 12, "slategrey", "slategrey", None]) + last_lt = None + elif lt == '-': + if last_lt is not None: + start, end = last_lt, c-1 + motifs.append([start, end, "()", 0, 12, "grey", "slategrey", None]) + last_lt = None + + seqFace = SeqMotifFace(node.sequence, motifs, + intermotif_format="line", + seqtail_format="line", scale_factor=ALG_SCALE) + add_face_to_node(seqFace, node, ALG_START_COL, aligned=True) + + + TRACKED_CLADES = ["Eukaryota", "Viridiplantae", "Fungi", + "Alveolata", "Metazoa", "Stramenopiles", "Rhodophyta", + "Amoebozoa", "Crypthophyta", "Bacteria", + "Alphaproteobacteria", "Betaproteobacteria", "Cyanobacteria", + "Gammaproteobacteria",] + + # ["Opisthokonta", "Apicomplexa"] + + colors = random_color(num=len(TRACKED_CLADES), s=0.45) + lin2color = dict([(ln, colors[i]) for i, ln in enumerate(TRACKED_CLADES)]) + + NAME_FACE = AttrFace('name', fsize=10, fgcolor='#444444') + + LABEL_START_COL = 10 + ALG_START_COL = 40 + ts = TreeStyle() + ts.draw_aligned_faces_as_table = False + ts.draw_guiding_lines = False + ts.show_leaf_name = False + ts.show_branch_support = False + ts.scale = 160 + + ts.layout_fn = [ly_basic, ly_leaf_names, ly_supports, ly_tax_labels] + + MIXED_RES = set() + MAX_SEQ_LEN = 0 + NPR_TREES = [] + for n in tree.traverse(): + if hasattr(n, "tree_seqtype"): + MIXED_RES.add(n.tree_seqtype) + if hasattr(n, "tree_type"): + NPR_TREES.append(n.tree_type) + seq = getattr(n, "sequence", "") + MAX_SEQ_LEN = max(len(seq), MAX_SEQ_LEN) + + if MAX_SEQ_LEN: + ALG_SCALE = min(1, 1000./MAX_SEQ_LEN) + ts.layout_fn.append(ly_block_alg) + + if len(NPR_TREES) > 1: + rF = RectFace(4, 4, "steelblue", "steelblue") + rF.margin_right = 10 + rF.margin_left = 10 + ts.legend.add_face(rF, 0) + ts.legend.add_face(TextFace(" NPR node"), 1) + ts.legend_position = 3 + + if len(MIXED_RES) > 1: + rF = RectFace(20, 20, "#CFE6CA", "#CFE6CA") + rF.margin_right = 10 + rF.margin_left = 10 + ts.legend.add_face(rF, 0) + ts.legend.add_face(TextFace(" Nucleotide based alignment"), 1) + ts.legend_position = 3 + + + try: + tree.set_species_naming_function(spname) + annotate_tree_with_ncbi(tree) + a = tree.search_nodes(species='Dictyostelium discoideum')[0] + b = tree.search_nodes(species='Chondrus crispus')[0] + #out = tree.get_common_ancestor([a, b]) + #out = tree.search_nodes(species='Haemophilus parahaemolyticus')[0].up + tree.set_outgroup(out) + tree.swap_children() + except Exception: + pass + + tree.render(outfile, tree_style=ts, w=170, units='mm', dpi=150) + tree.render(outfile+'.svg', tree_style=ts, w=170, units='mm', dpi=150) + tree.render(outfile+'.pdf', tree_style=ts, w=170, units='mm', dpi=150) + +def annotate_tree_with_ncbi(tree): + from ete2.ncbi_taxonomy import ncbiquery as ncbi + ncbi.connect_database() + name2sp = ncbi.get_name_translator(tree.get_species()) + for lf in tree.iter_leaves(): + lf.add_features(taxid=name2sp.get(lf.species, 0)) + lf.add_features(genename=re.sub('\{[^}]+\}', '', lf.name).strip()) + ncbi.annotate_tree(tree, attr_name='taxid') + +def spname(name): + m = re.search('\{([^}]+)\}', name) + if m: + return m.groups()[0] + else: + return name.split('|')[0].strip().replace('_', ' ') + taxid = name.split('.', 1)[0] + + tax2name = ncbi.get_taxid_translator([taxid]) + if int(taxid) not in tax2name: + print 'name', name , taxid, tax2name + return tax2name.get(int(taxid), taxid) diff --git a/pool/shard001/Python/0014222_exp_neg_one.py b/pool/shard001/Python/0014222_exp_neg_one.py new file mode 100644 index 0000000000000000000000000000000000000000..4dffb88b072609c7a1a3a4c0385061b37da61383 --- /dev/null +++ b/pool/shard001/Python/0014222_exp_neg_one.py @@ -0,0 +1,17 @@ +from opcodes import AND, ISZERO, MOD, SUB +from rule import Rule +from util import BVUnsignedMax +from z3 import BitVec, BitVecVal, If + +""" +Checking conversion of exp(-1, X) to sub(isZero(and(X, 1)), and(X, 1)) +""" + +rule = Rule() +n_bits = 256 + +X = BitVec('X', n_bits) + +exp_neg_one = If(MOD(X, 2) == 0, BitVecVal(1, n_bits), BVUnsignedMax(n_bits, n_bits)) + +rule.check(SUB(ISZERO(AND(X, 1)), AND(X, 1)), exp_neg_one) diff --git a/pool/shard001/Python/0014223_run_all.py b/pool/shard001/Python/0014223_run_all.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea405a9043ed98f42e181b62368540e939728ae --- /dev/null +++ b/pool/shard001/Python/0014223_run_all.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com +# +# Python tests originally created or extracted from other peoples work. The +# parts were too small to be protected. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os, sys + +# Find common code relative in file system. Not using packages for test stuff. +sys.path.insert( + 0, + os.path.normpath( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), + ".." + ) + ) +) +from test_common import ( + my_print, + setup, + compareWithCPython, + createSearchMode, + decideFilenameVersionSkip +) + +python_version = setup(needs_io_encoding = True) + +search_mode = createSearchMode() + +for filename in sorted(os.listdir('.')): + if not filename.endswith(".py"): + continue + + if not decideFilenameVersionSkip(filename): + continue + + active = search_mode.consider( + dirname = None, + filename = filename + ) + + if active: + extra_flags = ["expect_failure", "remove_output"] + + compareWithCPython( + dirname = None, + filename = filename, + extra_flags = extra_flags, + search_mode = search_mode, + needs_2to3 = False + ) + else: + my_print("Skipping", filename) + +search_mode.finish() diff --git a/pool/shard001/Python/0014224_back.py b/pool/shard001/Python/0014224_back.py new file mode 100644 index 0000000000000000000000000000000000000000..8e943ec1c3f1730c806bac18854fbb0f3f24cd4d --- /dev/null +++ b/pool/shard001/Python/0014224_back.py @@ -0,0 +1,25 @@ +from mesa.visualization.ModularVisualization import VisualizationElement +import collections + +class Visualization(VisualizationElement): + + def __init__(self, cellW, cellH,canvas_width=500, canvas_height=500): + self.grid_width = cellW + self.grid_height = cellH + self.canvas_width = canvas_width + self.canvas_height = canvas_height + + new_element = ("new VisualModule({}, {}, {}, {})" + .format(self.canvas_width, self.canvas_height, + self.grid_width, self.grid_height )) + + self.js_code = "elements.push(" + new_element + ");" + + def render(self, model): + data = collections.defaultdict(list) + data[1] = list() + if model.FireControl != False: + for fire in model.FireControl.fireExpansion: + x, y = fire.pos + data[1].append({"x" : x, "y" : y}) + return data \ No newline at end of file diff --git a/pool/shard001/Python/0014226_INLFileSet.py b/pool/shard001/Python/0014226_INLFileSet.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae4f26383bec164deb0fe6e146362e28dfa3ee3 --- /dev/null +++ b/pool/shard001/Python/0014226_INLFileSet.py @@ -0,0 +1,19 @@ +from ..slidesets import FileSet, INLSetInterface + +## +# A basic class for reading Remark markdown files directly +class INLFileSet(FileSet, INLSetInterface): + + ## + # Valid parameters for the FileSet object + @staticmethod + def validParams(): + params = FileSet.validParams() + params += INLSetInterface.validParams() + return params + + ## + # Performs INL slide parsing + def _parseSlide(self, slide, raw): + INLSetInterface.applySlideSettings(slide) + FileSet._parseSlide(self, slide, raw) diff --git a/pool/shard001/Python/0014227_urls.py b/pool/shard001/Python/0014227_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd1f784a81961c08a4e5fb551c3c002e23ddfc5 --- /dev/null +++ b/pool/shard001/Python/0014227_urls.py @@ -0,0 +1,16 @@ +from django.conf.urls import url +from blogapp import views + +urlpatterns = [ + url(r'^$',views.home,name='home'), + url(r'^register/$',views.register,name='register'), + url(r'^login/$',views.login,name='login'), + url(r'^success/$',views.success,name='success'), + url(r'^logout/$',views.logout,name='logout'), + url(r'^profile/$',views.profile,name='profile'), + url(r'^profile_view/$',views.profile_view,name='profile_view'), + url(r'^post/list/$',views.post_list,name='post_list'), # to see all post + url(r'^post/(?P[0-9]+)/$',views.post_detail,name='post_detail'), #to see a specific post + url(r'^post/new/$',views.post_new,name='post_new'), # for creating new post + url(r'^post/(?P[0-9]+)/edit/$',views.post_edit,name='post_edit'), #For editing any previous post +] \ No newline at end of file diff --git a/pool/shard001/Python/0014229_test_website_route_meta.py b/pool/shard001/Python/0014229_test_website_route_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..0ccedb0ca4594577630b684b220f8d3337ef1eae --- /dev/null +++ b/pool/shard001/Python/0014229_test_website_route_meta.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, Frappe Technologies and Contributors +# See license.txt +from __future__ import unicode_literals + +import frappe +import unittest +from frappe.utils import set_request +from frappe.website.render import render + +test_dependencies = ['Blog Post'] +class TestWebsiteRouteMeta(unittest.TestCase): + def test_meta_tag_generation(self): + blogs = frappe.get_all('Blog Post', fields=['name', 'route'], + filters={'published': 1, 'route': ('!=', '')}, limit=1) + + blog = blogs[0] + + # create meta tags for this route + doc = frappe.new_doc('Website Route Meta') + doc.append('meta_tags', { + 'key': 'type', + 'value': 'blog_post' + }) + doc.append('meta_tags', { + 'key': 'og:title', + 'value': 'My Blog' + }) + doc.name = blog.route + doc.insert() + + # set request on this route + set_request(path=blog.route) + response = render() + + self.assertTrue(response.status_code, 200) + + html = response.get_data().decode() + + self.assertTrue('''''' in html) + self.assertTrue('''''' in html) + + def tearDown(self): + frappe.db.rollback() diff --git a/pool/shard001/Python/0014233_test_scan.py b/pool/shard001/Python/0014233_test_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..a12cbc7d0a49cf6c34f15001fab9a9a15b511c6c --- /dev/null +++ b/pool/shard001/Python/0014233_test_scan.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +from strscan import StringScanner + +import re +import pytest + +def t_000(): + s = StringScanner('hello world!') + + t = s.scan('hello') + assert t == 'hello' + + t = s.scan(r'\s+') + assert t == ' ' + + assert s.scan(re.compile('\w+!')) == 'world!' + + assert s.scan('\w+') is None + assert s.scan(r'\w+') is None + + with pytest.raises(TypeError): + s.scan(None) diff --git a/pool/shard001/Python/0014234_louvain.py b/pool/shard001/Python/0014234_louvain.py new file mode 100644 index 0000000000000000000000000000000000000000..94af06839af7fa376bb7bf686cfc48f043edb8c6 --- /dev/null +++ b/pool/shard001/Python/0014234_louvain.py @@ -0,0 +1,234 @@ +from types import MappingProxyType +from typing import Optional, Tuple, Sequence, Type, Mapping, Any + +import numpy as np +import pandas as pd +from anndata import AnnData +from natsort import natsorted +from scipy.sparse import spmatrix +from packaging import version + +from ._utils_clustering import rename_groups, restrict_adjacency +from .. import _utils, logging as logg +from .._compat import Literal +from .._utils import _choose_graph + +try: + from louvain.VertexPartition import MutableVertexPartition +except ImportError: + + class MutableVertexPartition: + pass + + MutableVertexPartition.__module__ = 'louvain.VertexPartition' + + +def louvain( + adata: AnnData, + resolution: Optional[float] = None, + random_state: _utils.AnyRandom = 0, + restrict_to: Optional[Tuple[str, Sequence[str]]] = None, + key_added: str = 'louvain', + adjacency: Optional[spmatrix] = None, + flavor: Literal['vtraag', 'igraph', 'rapids'] = 'vtraag', + directed: bool = True, + use_weights: bool = False, + partition_type: Optional[Type[MutableVertexPartition]] = None, + partition_kwargs: Mapping[str, Any] = MappingProxyType({}), + neighbors_key: Optional[str] = None, + obsp: Optional[str] = None, + copy: bool = False, +) -> Optional[AnnData]: + """\ + Cluster cells into subgroups [Blondel08]_ [Levine15]_ [Traag17]_. + + Cluster cells using the Louvain algorithm [Blondel08]_ in the implementation + of [Traag17]_. The Louvain algorithm has been proposed for single-cell + analysis by [Levine15]_. + + This requires having ran :func:`~scanpy.pp.neighbors` or + :func:`~scanpy.external.pp.bbknn` first, + or explicitly passing a ``adjacency`` matrix. + + Parameters + ---------- + adata + The annotated data matrix. + resolution + For the default flavor (``'vtraag'``) or for ```RAPIDS```, you can provide a + resolution (higher resolution means finding more and smaller clusters), + which defaults to 1.0. + See “Time as a resolution parameter” in [Lambiotte09]_. + random_state + Change the initialization of the optimization. + restrict_to + Restrict the clustering to the categories within the key for sample + annotation, tuple needs to contain ``(obs_key, list_of_categories)``. + key_added + Key under which to add the cluster labels. (default: ``'louvain'``) + adjacency + Sparse adjacency matrix of the graph, defaults to neighbors connectivities. + flavor + Choose between to packages for computing the clustering. + ``'vtraag'`` is much more powerful, and the default. + directed + Interpret the ``adjacency`` matrix as directed graph? + use_weights + Use weights from knn graph. + partition_type + Type of partition to use. + Only a valid argument if ``flavor`` is ``'vtraag'``. + partition_kwargs + Key word arguments to pass to partitioning, + if ``vtraag`` method is being used. + neighbors_key + Use neighbors connectivities as adjacency. + If not specified, louvain looks .obsp['connectivities'] for connectivities + (default storage place for pp.neighbors). + If specified, louvain looks + .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities. + obsp + Use .obsp[obsp] as adjacency. You can't specify both + `obsp` and `neighbors_key` at the same time. + copy + Copy adata or modify it inplace. + + Returns + ------- + :obj:`None` + By default (``copy=False``), updates ``adata`` with the following fields: + + ``adata.obs['louvain']`` (:class:`pandas.Series`, dtype ``category``) + Array of dim (number of samples) that stores the subgroup id + (``'0'``, ``'1'``, ...) for each cell. + + :class:`~anndata.AnnData` + When ``copy=True`` is set, a copy of ``adata`` with those fields is returned. + """ + partition_kwargs = dict(partition_kwargs) + start = logg.info('running Louvain clustering') + if (flavor != 'vtraag') and (partition_type is not None): + raise ValueError( + '`partition_type` is only a valid argument ' 'when `flavour` is "vtraag"' + ) + adata = adata.copy() if copy else adata + if adjacency is None: + adjacency = _choose_graph(adata, obsp, neighbors_key) + if restrict_to is not None: + restrict_key, restrict_categories = restrict_to + adjacency, restrict_indices = restrict_adjacency( + adata, + restrict_key, + restrict_categories, + adjacency, + ) + if flavor in {'vtraag', 'igraph'}: + if flavor == 'igraph' and resolution is not None: + logg.warning('`resolution` parameter has no effect for flavor "igraph"') + if directed and flavor == 'igraph': + directed = False + if not directed: + logg.debug(' using the undirected graph') + g = _utils.get_igraph_from_adjacency(adjacency, directed=directed) + if use_weights: + weights = np.array(g.es["weight"]).astype(np.float64) + else: + weights = None + if flavor == 'vtraag': + import louvain + + if partition_type is None: + partition_type = louvain.RBConfigurationVertexPartition + if resolution is not None: + partition_kwargs["resolution_parameter"] = resolution + if use_weights: + partition_kwargs["weights"] = weights + if version.parse(louvain.__version__) < version.parse("0.7.0"): + louvain.set_rng_seed(random_state) + else: + partition_kwargs["seed"] = random_state + logg.info(' using the "louvain" package of Traag (2017)') + part = louvain.find_partition( + g, + partition_type, + **partition_kwargs, + ) + # adata.uns['louvain_quality'] = part.quality() + else: + part = g.community_multilevel(weights=weights) + groups = np.array(part.membership) + elif flavor == 'rapids': + # nvLouvain only works with undirected graphs, + # and `adjacency` must have a directed edge in both directions + import cudf + import cugraph + + offsets = cudf.Series(adjacency.indptr) + indices = cudf.Series(adjacency.indices) + if use_weights: + sources, targets = adjacency.nonzero() + weights = adjacency[sources, targets] + if isinstance(weights, np.matrix): + weights = weights.A1 + weights = cudf.Series(weights) + else: + weights = None + g = cugraph.Graph() + + if hasattr(g, 'add_adj_list'): + g.add_adj_list(offsets, indices, weights) + else: + g.from_cudf_adjlist(offsets, indices, weights) + + logg.info(' using the "louvain" package of rapids') + if resolution is not None: + louvain_parts, _ = cugraph.louvain(g, resolution=resolution) + else: + louvain_parts, _ = cugraph.louvain(g) + groups = ( + louvain_parts.to_pandas() + .sort_values('vertex')[['partition']] + .to_numpy() + .ravel() + ) + elif flavor == 'taynaud': + # this is deprecated + import networkx as nx + import community + + g = nx.Graph(adjacency) + partition = community.best_partition(g) + groups = np.zeros(len(partition), dtype=int) + for k, v in partition.items(): + groups[k] = v + else: + raise ValueError('`flavor` needs to be "vtraag" or "igraph" or "taynaud".') + if restrict_to is not None: + if key_added == 'louvain': + key_added += '_R' + groups = rename_groups( + adata, + key_added, + restrict_key, + restrict_categories, + restrict_indices, + groups, + ) + adata.obs[key_added] = pd.Categorical( + values=groups.astype('U'), + categories=natsorted(map(str, np.unique(groups))), + ) + adata.uns['louvain'] = {} + adata.uns['louvain']['params'] = dict( + resolution=resolution, + random_state=random_state, + ) + logg.info( + ' finished', + time=start, + deep=( + f'found {len(np.unique(groups))} clusters and added\n' + f' {key_added!r}, the cluster labels (adata.obs, categorical)' + ), + ) + return adata if copy else None diff --git a/pool/shard001/Python/0014236_urls.py b/pool/shard001/Python/0014236_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..43b8691826b743551e5ceb987e795242e9ad6383 --- /dev/null +++ b/pool/shard001/Python/0014236_urls.py @@ -0,0 +1,23 @@ +from django.conf import settings +from django.conf.urls import patterns, include, url +from django.http import HttpResponseRedirect + +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + url(r'^admin/doc/', include('django.contrib.admindocs.urls')), + url(r'^admin/', include(admin.site.urls)), + url(r'^gofish/', include('gofish.urls')), + url(r'^charts/', include('charts.urls')), + url(r'^convert/', include('lazysignup.urls')), + url(r'^$', lambda r: HttpResponseRedirect('gofish/')), +) + +if settings.DEBUG: + urlpatterns += patterns( + 'django.views.static', + (r'media/(?P.*)', + 'serve', + {'document_root': settings.MEDIA_ROOT}), + ) diff --git a/pool/shard001/Python/0014245_test_simrunners.py b/pool/shard001/Python/0014245_test_simrunners.py new file mode 100644 index 0000000000000000000000000000000000000000..256cb33ebb2d69282bf8022db68cbf359867043a --- /dev/null +++ b/pool/shard001/Python/0014245_test_simrunners.py @@ -0,0 +1,49 @@ +import numpy as np +from unittest import TestCase +import unittest +import active_subspaces.utils.simrunners as sruns + +def fun(x): + return 0.5*np.dot(x, x.T) + +def dfun1(x): + m = x.size + return x.reshape((m,1)) + +def dfun2(x): + m = x.size + return x.reshape((1,m)) + +def dfun3(x): + m = x.size + return x.reshape(m) + +class TestSimrunners(TestCase): + + def test_simulation_runner(self): + X = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + sr = sruns.SimulationRunner(fun) + ftrue = np.array([[0.5], [0.5], [0.0]]) + f = sr.run(X) + np.testing.assert_almost_equal(f, ftrue) + + def test_simulation_grad_runner1(self): + X = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + sgr = sruns.SimulationGradientRunner(dfun1) + df = sgr.run(X) + np.testing.assert_almost_equal(df, X) + + def test_simulation_grad_runner2(self): + X = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + sgr = sruns.SimulationGradientRunner(dfun2) + df = sgr.run(X) + np.testing.assert_almost_equal(df, X) + + def test_simulation_grad_runner3(self): + X = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + sgr = sruns.SimulationGradientRunner(dfun3) + df = sgr.run(X) + np.testing.assert_almost_equal(df, X) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0014247_GLWidget.py b/pool/shard001/Python/0014247_GLWidget.py new file mode 100644 index 0000000000000000000000000000000000000000..d57221ad92fca62ff322136138ff4bdd8b6f6c16 --- /dev/null +++ b/pool/shard001/Python/0014247_GLWidget.py @@ -0,0 +1,218 @@ +########################################################################## +# +# Copyright (c) 2011, John Haddon. All rights reserved. +# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above +# copyright notice, this list of conditions and the following +# disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided with +# the distribution. +# +# * Neither the name of John Haddon nor the names of +# any other contributors to this software may be used to endorse or +# promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +########################################################################## + +import os +import ctypes +import logging + +# the OpenGL module loves spewing things into logs, and for some reason +# when running in maya 2012 the default log level allows info messages through. +# so we set a specific log level on the OpenGL logger to keep it quiet. +logging.getLogger( "OpenGL" ).setLevel( logging.WARNING ) + +import IECore + +import Gaffer +import GafferUI + +# import lazily to improve startup of apps which don't use GL functionality +GL = Gaffer.lazyImport( "OpenGL.GL" ) +IECoreGL = Gaffer.lazyImport( "IECoreGL" ) + +QtCore = GafferUI._qtImport( "QtCore" ) +QtGui = GafferUI._qtImport( "QtGui" ) +QtOpenGL = GafferUI._qtImport( "QtOpenGL", lazy=True ) + +## The GLWidget is a base class for all widgets which wish to draw using OpenGL. +# Derived classes override the _draw() method to achieve this. +class GLWidget( GafferUI.Widget ) : + + ## This enum defines the optional elements of the GL buffer used + # for display. + BufferOptions = IECore.Enum.create( + "Alpha", + "Depth", + "Double" + ) + + ## Note that you won't always get the buffer options you ask for - a best fit is found + # among the available formats. In particular it appears that a depth buffer is often present + # even when not requested. + def __init__( self, bufferOptions = set(), **kw ) : + + format = QtOpenGL.QGLFormat() + format.setRgba( True ) + + format.setAlpha( self.BufferOptions.Alpha in bufferOptions ) + format.setDepth( self.BufferOptions.Depth in bufferOptions ) + format.setDoubleBuffer( self.BufferOptions.Double in bufferOptions ) + + if hasattr( format, "setVersion" ) : # setVersion doesn't exist in qt prior to 4.7. + format.setVersion( 2, 1 ) + + GafferUI.Widget.__init__( self, self.__createQGLWidget( format ), **kw ) + + self._qtWidget().resizeGL = Gaffer.WeakMethod( self.__resizeGL ) + self._qtWidget().paintGL = Gaffer.WeakMethod( self.__paintGL ) + + ## Called whenever the widget is resized. May be reimplemented by derived + # classes if necessary. + def _resize( self, size ) : + + GL.glViewport( 0, 0, size.x, size.y ) + + ## Derived classes must override this to draw their contents using + # OpenGL calls. + def _draw( self ) : + + raise NotImplementedError + + ## Derived classes may call this when they wish to trigger a redraw. + def _redraw( self, immediate=False ) : + + if immediate : + self._qtWidget().updateGL() + else : + self._qtWidget().update() + + def __resizeGL( self, width, height ) : + + self._resize( IECore.V2i( width, height ) ) + + def __paintGL( self ) : + + # we need to call the init method after a GL context has been + # created. ideally we'd call it in a QGLWidget.initializeGL override but + # at the time of writing that's not getting called. calling it here does + # mean we call init() way more than needed, but it's safe. + IECoreGL.init( True ) + + self._draw() + + # We keep a single hidden widget which owns the texture and display lists + # and then share those with all the widgets we really want to make. + __shareWidget = None + @classmethod + def __createQGLWidget( cls, format ) : + + # try to make a host specific widget if necessary. + result = cls.__createMayaQGLWidget( format ) + if result is not None : + return result + + # and if it wasn't necessary, just breathe a sigh of relief + # and make a nice normal one. + if cls.__shareWidget is None : + cls.__shareWidget = QtOpenGL.QGLWidget() + + return QtOpenGL.QGLWidget( format, shareWidget = cls.__shareWidget ) + + @classmethod + def __createMayaQGLWidget( cls, format ) : + + # We want to be able to share OpenGL resources between gaffer uis + # and maya viewport uis, because IECoreGL will be used in both. + # So we implement our own QGLContext class which creates a context + # which shares with maya. + + try : + import maya.OpenMayaRender + except ImportError : + # we're not in maya - createQGLWidget() will just make a + # normal widget. + return None + + import OpenGL.GLX + + # This is our custom context class which allows us to share gl + # resources with maya's contexts. We define it in here rather than + # at the top level because we want to import QtOpenGL lazily and + # don't want to trigger a full import until the last minute. + ## \todo Call glXDestroyContext appropriately, although as far as I + # can tell this is impossible. The base class implementation calls it + # in reset(), but that's not virtual, and we can't store it in d->cx + # (which is what the base class destroys) because that's entirely + # on the C++ side of things. + class MayaGLContext( QtOpenGL.QGLContext ) : + + def __init__( self, format, paintDevice ) : + + QtOpenGL.QGLContext.__init__( self, format, paintDevice ) + + self.__paintDevice = paintDevice + self.__context = None + + def chooseContext( self, shareContext ) : + + assert( self.__context is None ) + + # We have to call this to get d->vi set in the base class, because + # QGLWidget::setContext() accesses it directly, and will crash if we don't. + QtOpenGL.QGLContext.chooseContext( self, shareContext ) + + # Get maya's global resource context - we'll create our context + # to be sharing with this one. + import maya.OpenMayaRender + mayaRenderer = maya.OpenMayaRender.MHardwareRenderer.theRenderer() + mayaRenderer.makeResourceContextCurrent( mayaRenderer.backEndString() ) + mayaResourceContext = OpenGL.GLX.glXGetCurrentContext() + self.__display = OpenGL.GLX.glXGetCurrentDisplay() + + # Get a visual - we let the base class figure this out, but then we need + # to convert it from the form given by the qt bindings into the ctypes form + # needed by PyOpenGL. + visual = self.chooseVisual() + visual = ctypes.cast( int( visual ), ctypes.POINTER( OpenGL.raw._GLX.XVisualInfo ) ) + + # Make our context. + self.__context = OpenGL.GLX.glXCreateContext( + OpenGL.GLX.glXGetCurrentDisplay()[0], + visual, + OpenGL.GLX.glXGetCurrentContext(), + True + ) + + return True + + def makeCurrent( self ) : + + success = OpenGL.GLX.glXMakeCurrent( self.__display, self.__paintDevice.effectiveWinId(), self.__context ) + assert( success ) + + result = QtOpenGL.QGLWidget() + result.setContext( MayaGLContext( format, result ) ) + return result diff --git a/pool/shard001/Python/0014248_English_to_Latin_Translator.py b/pool/shard001/Python/0014248_English_to_Latin_Translator.py new file mode 100644 index 0000000000000000000000000000000000000000..96d379808f518d638dbc12f5a42c55bfce9f6e27 --- /dev/null +++ b/pool/shard001/Python/0014248_English_to_Latin_Translator.py @@ -0,0 +1,16 @@ +print "Welcome to English to Latin Translator","\n" + +pyg = 'ay' + +original = raw_input('Enter a word :') +word = original.lower() +first = word[0] +if len(original) > 0 and original.isalpha(): + if first=='a' or first=='e' or first=='i' or first=='o' or first=='u': + new_word = word+pyg + print "Latin of %s ="%(word),new_word + else: + new_word = word[1:len(word)+1]+word[0]+pyg + print "Latin of %s ="%(word),new_word +else: + print "\n",'Invalid Input.Try with a valid one.' diff --git a/pool/shard001/Python/0014251_edit_structural_element.py b/pool/shard001/Python/0014251_edit_structural_element.py new file mode 100644 index 0000000000000000000000000000000000000000..4598ba2489d400f2b4bffc4ff4c7e882553e775f --- /dev/null +++ b/pool/shard001/Python/0014251_edit_structural_element.py @@ -0,0 +1,116 @@ +from .opt_cards import DCONSTR + +def add_dtable(se, key, value): + """Add a DTABLE entry to the SE and the optmodel + + Parameters + ---------- + key : str + The DTABLE unique key. The algorithm automatically attempts to add + a sufix to prevent repeated keys. + value : float + The value corresponding to `key`. + + Returns + ------- + key : str + The resulting key. + + """ + optmodel = se.model.optmodel + origkey = key + if key in optmodel.dtables.keys(): + if len(key) >= 8: + raise ValueError('{0} is an already existing DTABLE entry!'. + format(key)) + if key in optmodel.dtable_prefixes: + optmodel.dtable_prefixes[key] += 1 + else: + optmodel.dtable_prefixes[key] = 0 + sufix = str(optmodel.dtable_prefixes[key]) + key = key + sufix.rjust(8 - len(key), '0') + if len(key) > 8: + raise ValueError('Use a smaller key') + + if origkey in se.dtables.keys(): + raise + se.dtables[origkey] = [key, value] + optmodel.dtables[key] = float(value) + + return key + + +def add_dresp(se, dresp): + """Add a DRESP(123) entry to the SE and the optmodel + + Parameters + ---------- + dresp : :class:`DRESP1`, :class:`DRESP2` or :class:`DRESP3` + The response object. + + """ + se.dresps.append(dresp) + se.model.optmodel.dresps[dresp.id] = dresp + if isinstance(dresp, DRESP3): + se.model.optmodel.groups.add(dresp.group) + + +def add_deqatn(se, deqatn): + """Add a DEQATN entry to the SE and the optmodel + + Parameters + ---------- + deqatn : :class:`DEQATN` + The equation to be added. + + """ + se.deqatns.append(deqatn) + se.model.optmodel.deqatns[deqatn.id] = deqatn + + +def add_dvar(se, dvar): + """Add a DESVAR entry to the SE and the optmodel + + Parameters + ---------- + dvar : :class:`DESVAR` + Design variable object. + + """ + if dvar.label in se.dvars.keys(): + raise + se.dvars[dvar.label] = dvar + se.model.optmodel.dvars[dvar.id] = dvar + + +def add_dvprel(se, dvprel): + """Add a DVPREL(12) entry to the SE and the optmodel + + Parameters + ---------- + dvprel : :class:`DVPREL1` or :class:`DVPREL2` + Design property-to-variable object. + + """ + se.dvprels.append(dvprel) + se.model.optmodel.dvprels[dvprel.id] = dvprel + + +def add_constraint(se, dcid, dresp, lb, ub): + """Add a DCONSTR entry to the SE and the optmodel + + Parameters + ---------- + dcid : int + Design constraint set id. + dresp : :class:`DRESP1`, :class:`DRESP2` or :class:`DRESP3` + The response object. + lb : float or None + Lower boundary for the constraint. + ub : float or None + Upper boundary for the constraint. + + """ + dconstr = DCONSTR(dcid, dresp.id, lb, ub) + se.dconstrs.append(dconstr) + se.model.optmodel.dconstrs[dconstr.id] = dconstr diff --git a/pool/shard001/Python/0014254_index0.py b/pool/shard001/Python/0014254_index0.py new file mode 100644 index 0000000000000000000000000000000000000000..f41b383da2c42861dacc599bc6ba5df077205729 --- /dev/null +++ b/pool/shard001/Python/0014254_index0.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue May 09 19:04:05 2017 + +""" + +import sys +import re + +WORD_RE = re.compile(r'\w+') + +index = {} +#with open("1.txt", encoding='utf-8') as fp: +with open("1.txt") as fp: + for line_no, line in enumerate(fp, 1): + for match in WORD_RE.finditer(line): + word = match.group() + column_no = match.start()+1 + location = (line_no, column_no) + + #1 + #occurrences = index.get(word, []) + #occurrences.append(location) + #index[word] = occurrences + + #2 + index.setdefault(word, []).append(location) + +for word in sorted(index, key=str.upper): + print word, index[word] \ No newline at end of file diff --git a/pool/shard001/Python/0014258_Requirement.py b/pool/shard001/Python/0014258_Requirement.py new file mode 100644 index 0000000000000000000000000000000000000000..4395427904ddc5b966ba4e00d05646e1b7e7c455 --- /dev/null +++ b/pool/shard001/Python/0014258_Requirement.py @@ -0,0 +1,144 @@ +#* This file is part of the MOOSE framework +#* https://www.mooseframework.org +#* +#* All rights reserved, see COPYRIGHT for full restrictions +#* https://github.com/idaholab/moose/blob/master/COPYRIGHT +#* +#* Licensed under LGPL 2.1, please see LICENSE for details +#* https://www.gnu.org/licenses/lgpl-2.1.html +import enum +import mooseutils + +class TestSpecification(object): + """Object for storing Test specification information w/r/t SQA""" + + def __init__(self, *args, **kwargs): + self.name = kwargs.pop('name', None) + self.filename = kwargs.pop('filename', None) + self.local = kwargs.pop('local', None) + self.line = kwargs.pop('line', None) + self.type = kwargs.pop('type', None) + self.prerequisites = kwargs.pop('prerequisites', set()) + self.skip = kwargs.pop('skip', False) + self.deleted = kwargs.pop('deleted', False) + self.text = kwargs.pop('text', None) + + @property + def testable(self): + out = [self.skip, self.deleted] + return not any([v for v in out]) + + def __str__(self): + return 'Specification: {}'.format(self.name) + +class Requirement(object): + """struct for storing Requirement information.""" + + def __init__(self, *args, **kwargs): + self.name = kwargs.pop('name', None) + self.filename = kwargs.pop('filename', None) + self.line = kwargs.pop('line', None) + self.specification = kwargs.pop('specification', None) + self.details = kwargs.pop('details', list()) + self.requirement = kwargs.pop('requirement', None) + self.requirement_line = kwargs.pop('requirement_line', None) + self.issues = kwargs.pop('issues', None) + self.issues_line = kwargs.pop('issues_line', None) + self.design = kwargs.pop('design', None) + self.design_line = kwargs.pop('design_line', None) + self.collections = kwargs.pop('collections', None) + self.collections_line = kwargs.pop('collections_line', None) + self.classification = kwargs.pop('classification', None) + self.classification_line = kwargs.pop('classification_line', None) + self.deprecated = kwargs.pop('deprecated', False) + self.deprecated_line = kwargs.pop('deprecated_line', None) + self.verification = kwargs.pop('verification', None) + self.verification_line = kwargs.pop('verification_line', None) + self.validation = kwargs.pop('validation', None) + self.validation_line = kwargs.pop('validation_line', None) + self.label = kwargs.pop('label', None) + self.duplicate = kwargs.pop('duplicate', False) + self.prefix = kwargs.pop('prefix', None) + + @property + def names(self): + out = set() + if self.specification is not None: + out.add(self.specification.name) + + elif self.details: + for d in self.details: + if d.specification is not None: + out.add(d.specification.name) + return out + + @property + def testable(self): + if self.specification is not None: + return self.specification.testable + elif self.details: + return all([d.specification.testable for d in self.details if d.specification is not None]) + return False + + @property + def prerequisites(self): + prereq = set() + if self.specification is not None: + prereq.update(self.specification.prerequisites) + elif self.details: + for d in self.details: + if d.specification is not None: + prereq.update(d.specification.prerequisites) + return prereq + + @property + def types(self): + test_types = set() + if self.specification is not None: + test_types.add(self.specification.type) + elif self.details: + for d in self.details: + if d.specification is not None: + test_types.add(d.specification.type) + return {t for t in test_types if t is not None} or None + + @property + def specifications(self): + if self.specification is not None: + yield self.specification + elif self.details: + for d in self.details: + if d.specification is not None: + yield d.specification + + def __str__(self): + out = 'Requirement: {}; requirement = {}; design = {}; issues = {}' + + if self.specification: + out += '; specification = ' + str(self.specification) + elif self.details: + for d in self.details: + out += '\n ' + str(d) + return out.format(self.name, repr(self.requirement), repr(self.design), repr(self.issues)) + +class Detail(object): + """struct for storing Detail information of a Requirement.""" + + def __init__(self, *args, **kwargs): + self.name = kwargs.pop('name', None) + self.filename = kwargs.pop('filename', None) + self.line = kwargs.pop('line', None) + self.detail = kwargs.pop('detail', None) + self.detail_line = kwargs.pop('detail_line', None) + self.specification = kwargs.pop('specification', None) + self.duplicate = kwargs.pop('duplicate', False) + + @property + def testable(self): + if self.specification is not None: + out = [self.specification.skip, self.specification.deleted] + return not any([v for v in out]) + return False + + def __str__(self): + return 'Detail: {}; specification = {}'.format(self.name, self.specification.name) diff --git a/pool/shard001/Python/0014263_transpositionFileCipher.py b/pool/shard001/Python/0014263_transpositionFileCipher.py new file mode 100644 index 0000000000000000000000000000000000000000..b94dc4b424e353a80159aa578bc3efc5220c5b66 --- /dev/null +++ b/pool/shard001/Python/0014263_transpositionFileCipher.py @@ -0,0 +1,64 @@ +"""Transposition Cipher Encrypt/Decrypt File + +Implements a transposition cipher that can encrypt/decrypt a file. + +Note: + https://www.nostarch.com/crackingcodes/ (BSD Licensed) +""" + +import time +import os +import sys +from pythontutorials.books.CrackingCodes.Ch07.transpositionEncrypt import encryptMessage +from pythontutorials.books.CrackingCodes.Ch08.transpositionDecrypt import decryptMessage + + +def main(): + inputFilename = 'frankenstein.txt' + # BE CAREFUL! If a file with the outputFilename name already exists, + # this program will overwrite that file: + outputFilename = 'frankenstein.encrypted.txt' + myKey = 10 + myMode = 'encrypt' # Set to 'encrypt' or 'decrypt' + + # If the input file does not exist, the program terminates early: + if not os.path.exists(inputFilename): + print('The file %s does not exist. Quitting...' % inputFilename) + sys.exit() + + # If the output file already exists, give the user a chance to quit: + if os.path.exists(outputFilename): + print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % outputFilename) + response = input('> ') + if not response.lower().startswith('c'): + sys.exit() + + # Read in the message from the input file: + fileObj = open(inputFilename) + content = fileObj.read() + fileObj.close() + + print('%sing...' % (myMode.title())) + + # Measure how long the encryption/decryption takes: + startTime = time.time() + if myMode == 'encrypt': + translated = encryptMessage(myKey, content) + elif myMode == 'decrypt': + translated = decryptMessage(myKey, content) + totalTime = round(time.time() - startTime, 2) + print('%sion time: %s seconds' % (myMode.title(), totalTime)) + + # Write out the translated message to the output file: + outputFileObj = open(outputFilename, 'w') + outputFileObj.write(translated) + outputFileObj.close() + + print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content))) + print('%sed file is %s.' % (myMode.title(), outputFilename)) + + +# If transpositionCipherFile.py is run (instead of imported as a module), +# call the main() function: +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014264_test_depth_to_space.py b/pool/shard001/Python/0014264_test_depth_to_space.py new file mode 100644 index 0000000000000000000000000000000000000000..1366c6a86346594d26c1a437e020e060004e4caf --- /dev/null +++ b/pool/shard001/Python/0014264_test_depth_to_space.py @@ -0,0 +1,78 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +"""Arm(R) Ethos(TM)-N integration depth-to-space tests""" + +import pytest +import numpy as np +import tvm +from tvm import relay +from tvm.testing import requires_ethosn +from . import infrastructure as tei + + +def _get_model(shape, block, dtype, layout): + a = relay.var("a", shape=shape, dtype=dtype) + depth = relay.nn.depth_to_space(a, layout=layout, block_size=block) + return depth + + +@requires_ethosn +@pytest.mark.parametrize("dtype", ["uint8", "int8"]) +def test_depth_to_space(dtype): + trials = [ + (1, 16, 16, 16), + (1, 64, 32, 16), + ] + + np.random.seed(0) + for shape in trials: + inputs = { + "a": tvm.nd.array( + np.random.randint( + np.iinfo(dtype).min, np.iinfo(dtype).max + 1, size=shape, dtype=dtype + ) + ) + } + outputs = [] + for npu in [False, True]: + model = _get_model(shape, 2, dtype, "NHWC") + mod = tei.make_module(model, {}) + outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu)) + + tei.verify(outputs, dtype, 1) + + +@requires_ethosn +def test_depth_to_space_failure(): + trials = [ + ((2, 16, 16, 16), 2, "uint8", "NHWC", "batch size=2, batch size must = 1"), + ( + (1, 16, 16, 16), + 2, + "int16", + "NHWC", + "dtype='int16', dtype must be either uint8, int8 or int32;", + ), + ((1, 16, 16, 16), 4, "uint8", "NHWC", "Only block size of 2 is supported"), + ((1, 16, 16, 16), 2, "uint8", "NCHW", "layout=NCHW, layout must = NHWC"), + ] + + for shape, block, dtype, layout, err_msg in trials: + model = _get_model(shape, block, dtype, layout) + mod = tei.make_ethosn_partition(model) + tei.test_error(mod, {}, err_msg) diff --git a/pool/shard001/Python/0014265_driverGaussianWSinAndParabola.py b/pool/shard001/Python/0014265_driverGaussianWSinAndParabola.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9973ee4f3af6839b4241466911f9efd01ac5c5 --- /dev/null +++ b/pool/shard001/Python/0014265_driverGaussianWSinAndParabola.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +"""Method of exact solution driver""" + +from bout_runners.bout_runners import basic_runner +import numpy as np +import sys, os +# If we add to sys.path, then it must be an absolute path +common_dir = os.path.abspath('./../../../common') +# Sys path is a list of system paths +sys.path.append(common_dir) + +from CELMAPy.MES import perform_MES_test + +# The options for the run +# ============================================================================= +# Spatial domain (+2 adds the ghost points) +nz = [2**n+2 for n in range(4, 12)] + +# Additional options +remove_old = False +directory = "gaussianWSinAndParabola" +make = True +nproc = 4 +# ============================================================================= + + +# Create the runner +# ============================================================================= +my_runs = basic_runner(\ + directory = directory ,\ + nproc = nproc ,\ + # Spatial domain + nz = nz,\ + # Copy the source file + cpy_source = True ,\ + make = make ,\ + # Sort the runs by the spatial domain + sort_by = 'spatial_domain' + ) +# ============================================================================= + + +# Perform the run +# ============================================================================= +my_runs.execute_runs(\ + remove_old = remove_old,\ + # Set the proper directory + post_processing_function = perform_MES_test,\ + post_process_after_every_run = False,\ + # Below are the kwargs arguments being passed to + # the post processing function + show_plot = False,\ + use_dx = False,\ + use_dy = False,\ + use_dz = True ,\ + xz_error_plot = True ,\ + extension = 'pdf',\ + ) +# ============================================================================= diff --git a/pool/shard001/Python/0014268_enums.py b/pool/shard001/Python/0014268_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..c76e4863d740261b2579332c01538f88885aea10 --- /dev/null +++ b/pool/shard001/Python/0014268_enums.py @@ -0,0 +1,82 @@ +import enum + +from django.utils.functional import Promise + +__all__ = ['Choices', 'IntegerChoices', 'TextChoices'] + + +class ChoicesMeta(enum.EnumMeta): + """A metaclass for creating a enum choices.""" + + def __new__(metacls, classname, bases, classdict): + labels = [] + for key in classdict._member_names: + value = classdict[key] + if ( + isinstance(value, (list, tuple)) and + len(value) > 1 and + isinstance(value[-1], (Promise, str)) + ): + *value, label = value + value = tuple(value) + else: + label = key.replace('_', ' ').title() + labels.append(label) + # Use dict.__setitem__() to suppress defenses against double + # assignment in enum's classdict. + dict.__setitem__(classdict, key, value) + cls = super().__new__(metacls, classname, bases, classdict) + cls._value2label_map_ = dict(zip(cls._value2member_map_, labels)) + # Add a label property to instances of enum which uses the enum member + # that is passed in as "self" as the value to use when looking up the + # label in the choices. + cls.label = property(lambda self: cls._value2label_map_.get(self.value)) + cls.do_not_call_in_templates = True + return enum.unique(cls) + + def __contains__(cls, member): + if not isinstance(member, enum.Enum): + # Allow non-enums to match against member values. + return member in {x.value for x in cls} + return super().__contains__(member) + + @property + def names(cls): + empty = ['__empty__'] if hasattr(cls, '__empty__') else [] + return empty + [member.name for member in cls] + + @property + def choices(cls): + empty = [(None, cls.__empty__)] if hasattr(cls, '__empty__') else [] + return empty + [(member.value, member.label) for member in cls] + + @property + def labels(cls): + return [label for _, label in cls.choices] + + @property + def values(cls): + return [value for value, _ in cls.choices] + + +class Choices(enum.Enum, metaclass=ChoicesMeta): + """Class for creating enumerated choices.""" + + def __str__(self): + """ + Use value when cast to str, so that Choices set as model instance + attributes are rendered as expected in templates and similar contexts. + """ + return str(self.value) + + +class IntegerChoices(int, Choices): + """Class for creating enumerated integer choices.""" + pass + + +class TextChoices(str, Choices): + """Class for creating enumerated string choices.""" + + def _generate_next_value_(name, start, count, last_values): + return name diff --git a/pool/shard001/Python/0014270_id_codec.py b/pool/shard001/Python/0014270_id_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..15e96f78612ef87a3e435bffcf9c95a91bf7e72e --- /dev/null +++ b/pool/shard001/Python/0014270_id_codec.py @@ -0,0 +1,14 @@ +"""Defines a reversible way to label an id with a scope and type to make it unique.""" + +import base64 + + +def encode_id(scope, id_type, id_value): + """Encode a scope-type-value tuple into a single ID string.""" + return base64.b32encode('|'.join([scope, id_type, id_value])) + + +def decode_id(encoded_id): + """Decode an ID string back to the original scope-type-value tuple.""" + scope, id_type, id_value = base64.b32decode(encoded_id).split('|') + return scope, id_type, id_value diff --git a/pool/shard001/Python/0014271_tv3.py b/pool/shard001/Python/0014271_tv3.py new file mode 100644 index 0000000000000000000000000000000000000000..a994d6a22ece5b745e7a24e9d7d84317204d12d2 --- /dev/null +++ b/pool/shard001/Python/0014271_tv3.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +#------------------------------------------------------------ +# pelisalacarta - XBMC Plugin +# Conector para TV3 +# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ +#------------------------------------------------------------ + +import re +from core import scrapertools +from core import logger +from core import jsontools + +def get_video_url(page_url, premium = False, user="", password="", video_password="", page_data=""): + + logger.info("[tv3.py] get_video_url(page_url='%s')" % page_url) + + video = [] + urlbase = "http://dinamics.ccma.cat/pvideo/media.jsp?media=video&version=0s&idint=%s&profile=tv" + + try: + # Se mira si la URL tiene el formato nuevo o el antiguo y entonces se usa un patrón u otro para extraer + # el número de video, que es lo único que importa para obtener en última instancia la URL del video en MP4. + # Precondición: los dos únicos tipos de URLs que pueden llegar aquí son, por ejemplo: + # http://www.ccma.cat/tv3/alacarta/telenoticies/telenoticies-vespre-17042015/video/5505723/ + # http://www.tv3.cat/videos/5495372/La-baldana + # + if page_url.startswith("http://www.ccma.cat"): + + id_video = scrapertools.find_single_match(page_url,'/tv3/alacarta/.*?/.*?/video/(\d+)') + if id_video=="": + id_video = scrapertools.find_single_match(page_url,'/tv3/super3/.*?/.*?/video/(\d+)') + if id_video=="": + id_video = scrapertools.find_single_match(page_url,'/tv3/super3/.*?/.*?/video/fitxa-programa/(\d+)') + if id_video=="": + id_video = scrapertools.find_single_match(page_url,'/video/(\d+)') + else: + id_video = scrapertools.find_single_match(page_url,'/videos/(\d+)/.*?') + + if id_video<>"": + data = scrapertools.cachePage(urlbase % id_video) + response = jsontools.load_json(data.decode('iso-8859-1').encode('utf8')) + for entry in response['media']['url']: + video.append([ "http [mp4 %s]" % entry['label'], entry['file']]) + else: + # Es URL de video en directo + video.append([ "http [mp4]", page_url]) + + except: + import traceback + logger.info(traceback.format_exc()) + + video.reverse() + + return video + diff --git a/pool/shard001/Python/0014273_analysis.py b/pool/shard001/Python/0014273_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..b168be536099207a1051eb6020f04c2392c4d0dc --- /dev/null +++ b/pool/shard001/Python/0014273_analysis.py @@ -0,0 +1,142 @@ +import sys +import contextlib +from collections import defaultdict + +import logging +l = logging.getLogger('angr.analysis') + +registered_analyses = {} + +def register_analysis(analysis, name): + registered_analyses[name] = analysis + +class AnalysisLogEntry(object): + def __init__(self, message, exc_info=False): + if exc_info: + (e_type, value, traceback) = sys.exc_info() + self.exc_type = e_type + self.exc_value = value + self.exc_traceback = traceback + else: + self.exc_type = None + self.exc_value = None + self.exc_traceback = None + + self.message = message + + def __getstate__(self): + return str(self.__dict__.get("exc_type")), \ + str(self.__dict__.get("exc_value")), \ + str(self.__dict__.get("exc_traceback")), \ + self.message + + def __setstate__(self, s): + self.exc_type, self.exc_value, self.exc_traceback, self.message = s + + def __repr__(self): + if self.exc_type is None: + msg_str = repr(self.message) + if len(msg_str) > 70: + msg_str = msg_str[:66] + '...' + if msg_str[0] in ('"', "'"): + msg_str += msg_str[0] + return '' % msg_str + else: + msg_str = repr(self.message) + if len(msg_str) > 40: + msg_str = msg_str[:36] + '...' + if msg_str[0] in ('"', "'"): + msg_str += msg_str[0] + return '' % (msg_str, self.exc_type.__name__, self.exc_value) + +class Analyses(object): + """ + This class contains functions for all the registered and runnable analyses, + """ + def __init__(self, p): + """ + Creates an Analyses object + + :ivar p: A project + :type p: angr.Project + :ivar analysis_results: The result cache. + """ + self.project = p + self._registered_analyses = {} + self.reload_analyses() + + def reload_analyses(self): + for analysis_name, analysis in registered_analyses.iteritems(): + self._registered_analyses[analysis_name] = self._specialize_analysis(analysis, analysis_name) + + def _specialize_analysis(self, analysis, name): + def make_analysis(*args, **kwargs): # pylint: disable=unused-argument + fail_fast = kwargs.pop('fail_fast', False) + kb = kwargs.pop('kb', self.project.kb) + + oself = analysis.__new__(analysis) + oself.named_errors = {} + oself.errors = [] + oself.log = [] + + oself._fail_fast = fail_fast + oself._name = name + oself.project = self.project + oself.kb = kb + + oself.__init__(*args, **kwargs) + return oself + + make_analysis.__doc__ = analysis.__init__.__doc__ + return make_analysis + + def __getstate__(self): + return self.project + + def __setstate__(self, s): + self.__init__(s) + + def __getattr__(self, k): + r = super(Analyses, self).__getattribute__('_registered_analyses') + if k == '_registered_analyses': + return r + if k in r: + return r[k] + return super(Analyses, self).__getattribute__(k) + + def __dir__(self): + return dir(Analyses) + self._registered_analyses.keys() + + +class Analysis(object): + """ + This class represents an analysis on the program. + + + :ivar project: The project for this analysis. + :type project: angr.Project + """ + project = None + kb = None + _fail_fast = None + _name = None + errors = [] + named_errors = defaultdict(list) + + @contextlib.contextmanager + def _resilience(self, name=None, exception=Exception): + try: + yield + except exception: # pylint:disable=broad-except + if self._fail_fast: + raise + else: + error = AnalysisLogEntry("exception occurred", exc_info=True) + l.error("Caught and logged %s with resilience: %s", error.exc_type.__name__, error.exc_value) + if name is None: + self.errors.append(error) + else: + self.named_errors[name].append(error) + + def __repr__(self): + return '<%s Analysis Result at %#x>' % (self._name, id(self)) diff --git a/pool/shard001/Python/0014274_parse_search_dirs.py b/pool/shard001/Python/0014274_parse_search_dirs.py new file mode 100644 index 0000000000000000000000000000000000000000..adbebe08a5932bf9bec0d78f4c19a5921b978a24 --- /dev/null +++ b/pool/shard001/Python/0014274_parse_search_dirs.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import absolute_import, division, print_function, unicode_literals + +import logging +import os +import re + +from twitter.common.collections import OrderedSet + +from pants.subsystem.subsystem import Subsystem +from pants.util.dirutil import is_readable_dir +from pants.util.memo import memoized_classproperty +from pants.util.process_handler import subprocess +from pants.util.strutil import safe_shlex_join + + +logger = logging.getLogger(__name__) + + +class ParseSearchDirs(Subsystem): + """Parse the output of invoking a compiler with the '-print-search-dirs' argument for lib dirs. + + This is used to expose resources from one compiler (e.g. a compiler preinstalled on the host which + has knowledge of distro-maintained system libraries such as libc) to the compilers/linkers that + Pants provides. This is also used to share resources between different :class:`BinaryTool`s with + compiler executables. + """ + + options_scope = 'parse-search-dirs' + + class ParseSearchDirsError(Exception): pass + + @memoized_classproperty + def _search_dirs_libraries_regex(cls): + return re.compile('^libraries: =(.*)$', flags=re.MULTILINE) + + def _invoke_compiler_exe(self, cmd, env): + try: + # Get stderr interspersed in the error message too -- this should not affect output parsing. + compiler_output = subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT) + except OSError as e: + # We use `safe_shlex_join` here to pretty-print the command. + raise self.ParseSearchDirsError( + "Process invocation with argv '{}' and environment {!r} failed." + .format(safe_shlex_join(cmd), env), + e) + except subprocess.CalledProcessError as e: + raise self.ParseSearchDirsError( + "Process invocation with argv '{}' and environment {!r} exited with non-zero code {}. " + "output:\n{}" + .format(safe_shlex_join(cmd), env, e.returncode, e.output), + e) + + return compiler_output + + def _parse_libraries_from_compiler_search_dirs(self, compiler_exe, env): + # This argument is supported by at least gcc and clang. + cmd = [compiler_exe, '-print-search-dirs'] + + compiler_output = self._invoke_compiler_exe(cmd, env) + + libs_line = self._search_dirs_libraries_regex.search(compiler_output) + if not libs_line: + raise self.ParseSearchDirsError( + "Could not parse libraries from output of {!r}:\n{}" + .format(safe_shlex_join(cmd), compiler_output)) + return libs_line.group(1).split(':') + + def _filter_existing_dirs(self, dir_candidates, compiler_exe): + real_dirs = OrderedSet() + + for maybe_existing_dir in dir_candidates: + # Could use a `seen_dir_paths` set if we want to avoid pinging the fs for duplicate entries. + if is_readable_dir(maybe_existing_dir): + real_dirs.add(os.path.realpath(maybe_existing_dir)) + else: + logger.debug("non-existent or non-accessible directory at {} while " + "parsing directories from {}" + .format(maybe_existing_dir, compiler_exe)) + + return list(real_dirs) + + def get_compiler_library_dirs(self, compiler_exe, env=None): + all_dir_candidates = self._parse_libraries_from_compiler_search_dirs(compiler_exe, env=env) + return self._filter_existing_dirs(all_dir_candidates, compiler_exe) diff --git a/pool/shard001/Python/0014275_setup.py b/pool/shard001/Python/0014275_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..5bba26c8e40999415f00b6d8f357004cfb6641c6 --- /dev/null +++ b/pool/shard001/Python/0014275_setup.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# coding: utf-8 +import os +import re +import sys + +from distutils.core import setup +from distutils.extension import Extension + +from distutils import sysconfig + +USE_CYTHON = False +if 'sdist' in sys.argv: + USE_CYTHON = True + +extensions = [] +for d, s, files in os.walk("django_speedboost"): + for fname in files: + if fname.endswith(".c"): + basename = fname[:-2] + extensions.append(Extension(os.path.join(d, basename), [os.path.join(d, fname)])) + +if USE_CYTHON: + from Cython.Build import cythonize + from Cython.Compiler.Options import directive_defaults + + directive_defaults['linetrace'] = True + directive_defaults['binding'] = True + extensions = cythonize("django_speedboost/*.py*") + + +def get_version(package): + """ + Return package version as listed in `__version__` in `init.py`. + """ + init_py = open(os.path.join(package, '__init__.py')).read() + return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) + +version = get_version('django_speedboost') + + +with open('README.rst') as readme_file: + readme = readme_file.read() + +with open('HISTORY.rst') as history_file: + history = history_file.read().replace('.. :changelog:', '') + +site_packages_path = sysconfig.get_python_lib(plat_specific=True) +site_packages_rel_path = site_packages_path[len(sysconfig.EXEC_PREFIX) + 1:] + +setup( + name="django_speedboost", + author="Alex Damian", + author_email="alex@yplanapp.com", + version=version, + license="MIT", + url="https://github.com/YPlan/django-speedboost", + description="Replaces select Django modules with Cython-compiled versions for great speed.", + long_description=readme + '\n\n' + history, + packages=["django_speedboost"], + ext_modules=extensions, + install_requires=['django==1.8.8'], + data_files=[(site_packages_rel_path, ["django_speedboost.pth"])], + scripts="", + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Framework :: Django', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + ], +) diff --git a/pool/shard001/Python/0014282_dreamsoft_completar_checkin_relacion.py b/pool/shard001/Python/0014282_dreamsoft_completar_checkin_relacion.py new file mode 100644 index 0000000000000000000000000000000000000000..b34278a16e17504128f62f7d568f33183c868a3b --- /dev/null +++ b/pool/shard001/Python/0014282_dreamsoft_completar_checkin_relacion.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# -------------------------------------------------------------------------- +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2012-Today Serpent Consulting Services PVT. LTD. +# () +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see +# +# --------------------------------------------------------------------------- + +import time +import datetime +from dateutil.relativedelta import relativedelta +import urllib2 +from odoo.exceptions import except_orm, ValidationError +from odoo.tools import misc, DEFAULT_SERVER_DATE_FORMAT,DEFAULT_SERVER_DATETIME_FORMAT +from odoo import models, fields, api, _ +from odoo import workflow +from decimal import Decimal +import logging +_logger = logging.getLogger(__name__) + +class hotel_completar_checkin_relacion(models.Model): + + _name = 'dreamsoft.completar_checkin_relacion' + + relacion_completar_checkin_id = fields.Many2one('dreamsoft.completar_checkin', u'Acompañante') + name = fields.Many2one('res.partner', u'Acompañante') + reservation_id = fields.Many2one('hotel.reservation', 'Reservacion') + + @api.model + def create(self, vals, check=True): + """ + sobreescribimos el metodo create para que los + usuarios no puedan sino crear un solo registro + para la configuracion de los horarios. + + @param self: The object pointer + @param vals: dictionary of fields value. + @return: new record set for hotel folio. + """ + if self._context: + keys = self._context.keys() + if 'reserva_id' in keys: + vals['reservation_id'] = self._context['reserva_id'] + return super(hotel_completar_checkin_relacion, self).create(vals) + diff --git a/pool/shard001/Python/0014284_state_setter.py b/pool/shard001/Python/0014284_state_setter.py new file mode 100644 index 0000000000000000000000000000000000000000..b760715b8f022ff63f664133a26aadf8d9db05c9 --- /dev/null +++ b/pool/shard001/Python/0014284_state_setter.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +import rospy +from lg_common import StateChanger +from lg_msg_defs.msg import StringArray +from lg_common.helpers import run_with_influx_exception_handler + + +NODE_NAME = 'state_handler' + + +def main(): + rospy.init_node(NODE_NAME) + + state_changer = StateChanger() + rospy.Subscriber('/state_handler/activate', StringArray, state_changer.locked_state_handler) + + rospy.spin() + + +if __name__ == '__main__': + run_with_influx_exception_handler(main, NODE_NAME) diff --git a/pool/shard001/Python/0014287_wsgi.py b/pool/shard001/Python/0014287_wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..9880fbcf20920149acd10bd23df0baa9fe26b2d0 --- /dev/null +++ b/pool/shard001/Python/0014287_wsgi.py @@ -0,0 +1,18 @@ +""" +WSGI config for nugacious project. + +It exposes the WSGI callable as a module-level variable named ``application``. +""" + +import os +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nugacious.settings") + +from django.core.wsgi import get_wsgi_application +_application = get_wsgi_application() + +env_variables_to_pass = ['NUGACIOUS_SECRET_KEY', ] +def application(environ, start_response): + # pass the WSGI environment variables on through to os.environ + for var in env_variables_to_pass: + os.environ[var] = environ.get(var, '') + return _application(environ, start_response) diff --git a/pool/shard001/Python/0014289_wxhorizon.py b/pool/shard001/Python/0014289_wxhorizon.py new file mode 100644 index 0000000000000000000000000000000000000000..dc859dd533f072612d368b300b8839055032dbf2 --- /dev/null +++ b/pool/shard001/Python/0014289_wxhorizon.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +""" + MAVProxy horizon indicator. +""" +import multiprocessing +import time + +class HorizonIndicator(): + ''' + A horizon indicator for MAVProxy. + ''' + def __init__(self,title='MAVProxy: Horizon Indicator'): + self.title = title + # Create Pipe to send attitude information from module to UI + self.child_pipe_recv,self.parent_pipe_send = multiprocessing.Pipe(duplex=False) + self.close_event = multiprocessing.Event() + self.close_event.clear() + self.child = multiprocessing.Process(target=self.child_task) + self.child.start() + self.child_pipe_recv.close() + + def child_task(self): + '''child process - this holds all the GUI elements''' + self.parent_pipe_send.close() + + from wx_loader import wx + from wxhorizon_ui import HorizonFrame + # Create wx application + app = wx.App(False) + app.frame = HorizonFrame(state=self, title=self.title) + app.frame.SetDoubleBuffered(True) + app.frame.Show() + app.MainLoop() + self.close_event.set() # indicate that the GUI has closed + + def close(self): + '''Close the window.''' + self.close_event.set() + if self.is_alive(): + self.child.join(2) + + def is_alive(self): + '''check if child is still going''' + return self.child.is_alive() + +if __name__ == "__main__": + # test the console + multiprocessing.freeze_support() + horizon = HorizonIndicator() + while horizon.is_alive(): + print 'test' + time.sleep(0.5) diff --git a/pool/shard001/Python/0014291_Program.py b/pool/shard001/Python/0014291_Program.py new file mode 100644 index 0000000000000000000000000000000000000000..7b397fa7cdcdae49f575709774915d443b1a4ce7 --- /dev/null +++ b/pool/shard001/Python/0014291_Program.py @@ -0,0 +1,129 @@ + +import re + +import Instructions + + +LABEL_REGEX = re.compile('^([0-9abcdef]+)\ <(.+)>:$') + + +def AddInstrRelJump(instr): + offset = (instr & 0x0FFF) + + # Extend sign bit + if ((offset & 0x0800) != 0): + # Don't ask + offset = -(((~(((~0) & (~0xFFF)) | offset))+1)<<1) + + return Instructions.RelJump(offset) + +def AddInstrPush(instr): + register = ((instr & 0x01F0) >> 4) + return Instructions.Push(register) + +def AddInstrPop(instr): + register = ((instr & 0x01F0) >> 4) + return Instructions.Pop(register) + +def AddInstrReturn(instr): + return Instructions.Return() + +def AddInstrAdd(instr): + destRegister = ((instr & 0x01F0) >> 4) + sourceRegister = (((instr & 0x0200) >> 5) | (instr & 0x000F)) + return Instructions.Add( + destRegister, + sourceRegister + ) + +def AddInstrDec(instr): + register = ((instr & 0x01F0) >> 4) + return Instructions.Decrement( + register + ) + +def AddInstrTest(instr): + register = (instr & 0x01F) + return Instructions.Test( + register + ) + +def AddInstrMove(instr): + destRegister = ((instr & 0x01F0) >> 4) + sourceRegister = (((instr & 0x0200) >> 5) | (instr & 0x000F)) + return Instructions.Move( + destRegister, + sourceRegister + ) + +def AddInstrBranchEqual(instr): + offset = ((instr & 0x03F8) >> 2) + return Instructions.BranchEqual( + offset + ) + + +OpCodeInstructionMap = { + 0x3 : AddInstrAdd, + 0x8 : AddInstrTest, + 0xB : AddInstrMove, + 0xC : AddInstrRelJump, + 0x1E1 : AddInstrBranchEqual, + 0x48F : AddInstrPop, + 0x49F : AddInstrPush, + 0x4A8 : AddInstrReturn, + 0x4AA : AddInstrDec + } + + +def GetOpCode(instr): + + opcode = 0 + + msNibble = ((instr & 0xF000)>>12) + if (msNibble == 0x9): + opcode = ((msNibble << 7) | ((instr & 0x0E00) >> 5) | (instr & 0x000F)) + elif (msNibble == 0xF): + opcode = ((msNibble << 5) | ((instr & 0x0C00) >> 7) | (instr & 0x0007)) + elif (msNibble == 0x0 or msNibble == 0x2): + opcode = ((msNibble << 2) | ((instr & 0x0C00) >> 10)) + else: + opcode = msNibble + + return opcode + + +class Program: + + def __init__( + self, + programFile + ): + + self.labels = {} + self.instructions = [] + + while (True): + + curLine = programFile.readline() + if (curLine == ''): + break + + # Process label + labelMatches = LABEL_REGEX.match(curLine) + if (labelMatches != None and len(labelMatches.groups()) == 2): + label = labelMatches.group(2) + addr = int(labelMatches.group(1), 16) + self.labels[label] = addr + continue + + # Process instruction + instr = int(curLine, 16) + opCode = GetOpCode(instr) + if (opCode not in OpCodeInstructionMap): + print('Error: %x not a valid instruction.' % instr) + break + + instrCreator = OpCodeInstructionMap[opCode] + self.instructions.append(instrCreator(instr)) + diff --git a/pool/shard001/Python/0014296_data_entry_flow.py b/pool/shard001/Python/0014296_data_entry_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..acd0befda4e166a6831f74dc016b98fe83a3710b --- /dev/null +++ b/pool/shard001/Python/0014296_data_entry_flow.py @@ -0,0 +1,182 @@ +"""Classes to help gather user submissions.""" +import logging +from typing import Dict, Any, Callable, Hashable, List, Optional # noqa pylint: disable=unused-import +import uuid +import voluptuous as vol +from .core import callback, HomeAssistant +from .exceptions import HomeAssistantError + +_LOGGER = logging.getLogger(__name__) + +RESULT_TYPE_FORM = 'form' +RESULT_TYPE_CREATE_ENTRY = 'create_entry' +RESULT_TYPE_ABORT = 'abort' + + +class FlowError(HomeAssistantError): + """Error while configuring an account.""" + + +class UnknownHandler(FlowError): + """Unknown handler specified.""" + + +class UnknownFlow(FlowError): + """Uknown flow specified.""" + + +class UnknownStep(FlowError): + """Unknown step specified.""" + + +class FlowManager: + """Manage all the flows that are in progress.""" + + def __init__(self, hass: HomeAssistant, async_create_flow: Callable, + async_finish_flow: Callable) -> None: + """Initialize the flow manager.""" + self.hass = hass + self._progress = {} # type: Dict[str, Any] + self._async_create_flow = async_create_flow + self._async_finish_flow = async_finish_flow + + @callback + def async_progress(self) -> List[Dict]: + """Return the flows in progress.""" + return [{ + 'flow_id': flow.flow_id, + 'handler': flow.handler, + 'context': flow.context, + } for flow in self._progress.values()] + + async def async_init(self, handler: Hashable, *, + context: Optional[Dict] = None, + data: Any = None) -> Any: + """Start a configuration flow.""" + flow = await self._async_create_flow( + handler, context=context, data=data) + flow.hass = self.hass + flow.handler = handler + flow.flow_id = uuid.uuid4().hex + flow.context = context + self._progress[flow.flow_id] = flow + + return await self._async_handle_step(flow, flow.init_step, data) + + async def async_configure( + self, flow_id: str, user_input: Optional[Dict] = None) -> Any: + """Continue a configuration flow.""" + flow = self._progress.get(flow_id) + + if flow is None: + raise UnknownFlow + + step_id, data_schema = flow.cur_step + + if data_schema is not None and user_input is not None: + user_input = data_schema(user_input) + + return await self._async_handle_step( + flow, step_id, user_input) + + @callback + def async_abort(self, flow_id: str) -> None: + """Abort a flow.""" + if self._progress.pop(flow_id, None) is None: + raise UnknownFlow + + async def _async_handle_step(self, flow: Any, step_id: str, + user_input: Optional[Dict]) -> Dict: + """Handle a step of a flow.""" + method = "async_step_{}".format(step_id) + + if not hasattr(flow, method): + self._progress.pop(flow.flow_id) + raise UnknownStep("Handler {} doesn't support step {}".format( + flow.__class__.__name__, step_id)) + + result = await getattr(flow, method)(user_input) # type: Dict + + if result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_CREATE_ENTRY, + RESULT_TYPE_ABORT): + raise ValueError( + 'Handler returned incorrect type: {}'.format(result['type'])) + + if result['type'] == RESULT_TYPE_FORM: + flow.cur_step = (result['step_id'], result['data_schema']) + return result + + # We pass a copy of the result because we're mutating our version + result = await self._async_finish_flow(flow, dict(result)) + + # _async_finish_flow may change result type, check it again + if result['type'] == RESULT_TYPE_FORM: + flow.cur_step = (result['step_id'], result['data_schema']) + return result + + # Abort and Success results both finish the flow + self._progress.pop(flow.flow_id) + + return result + + +class FlowHandler: + """Handle the configuration flow of a component.""" + + # Set by flow manager + flow_id = None + hass = None + handler = None + cur_step = None + context = None + + # Set by _async_create_flow callback + init_step = 'init' + + # Set by developer + VERSION = 1 + + @callback + def async_show_form(self, *, step_id: str, data_schema: vol.Schema = None, + errors: Optional[Dict] = None, + description_placeholders: Optional[Dict] = None) \ + -> Dict: + """Return the definition of a form to gather user input.""" + return { + 'type': RESULT_TYPE_FORM, + 'flow_id': self.flow_id, + 'handler': self.handler, + 'step_id': step_id, + 'data_schema': data_schema, + 'errors': errors, + 'description_placeholders': description_placeholders, + } + + @callback + def async_create_entry(self, *, title: str, data: Dict, + description: Optional[str] = None, + description_placeholders: Optional[Dict] = None) \ + -> Dict: + """Finish config flow and create a config entry.""" + return { + 'version': self.VERSION, + 'type': RESULT_TYPE_CREATE_ENTRY, + 'flow_id': self.flow_id, + 'handler': self.handler, + 'title': title, + 'data': data, + 'description': description, + 'description_placeholders': description_placeholders, + } + + @callback + def async_abort(self, *, reason: str, + description_placeholders: Optional[Dict] = None) -> Dict: + """Abort the config flow.""" + return { + 'type': RESULT_TYPE_ABORT, + 'flow_id': self.flow_id, + 'handler': self.handler, + 'reason': reason, + 'description_placeholders': description_placeholders, + } diff --git a/pool/shard001/Python/0014307_eventloop_test.py b/pool/shard001/Python/0014307_eventloop_test.py new file mode 100644 index 0000000000000000000000000000000000000000..70de70534cf68d792b0b86b4975dd5a7aecfa1d3 --- /dev/null +++ b/pool/shard001/Python/0014307_eventloop_test.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python +# +# Copyright 2007 Google LLC +# +# 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. +# + + + + + + + + + + + + + + +"""Tests for eventloop.py.""" + +import logging +import os +import time + +from google.appengine.api import apiproxy_stub_map +from google.appengine.datastore import datastore_rpc + +from absl.testing import absltest as unittest + +from google.appengine.ext.ndb import eventloop +from google.appengine.ext.ndb import test_utils + + +class EventLoopTests(test_utils.NDBTest): + + def setUp(self): + super(EventLoopTests, self).setUp() + if eventloop._EVENT_LOOP_KEY in os.environ: + del os.environ[eventloop._EVENT_LOOP_KEY] + self.ev = eventloop.get_event_loop() + + the_module = eventloop + + def testQueueTasklet(self): + def f(unused_number, unused_string, unused_a, unused_b): return 1 + + def g(unused_number, unused_string): return 2 + + def h(unused_c, unused_d): return 3 + t_before = time.time() + eventloop.queue_call(1, f, 42, 'hello', unused_a=1, unused_b=2) + eventloop.queue_call(3, h, unused_c=3, unused_d=4) + eventloop.queue_call(2, g, 100, 'abc') + t_after = time.time() + self.assertEqual(len(self.ev.queue), 3) + [(t1, f1, a1, k1), (t2, f2, a2, k2), (t3, f3, a3, k3)] = self.ev.queue + self.assertTrue(t1 < t2) + self.assertTrue(t2 < t3) + self.assertTrue(abs(t1 - (t_before + 1)) <= t_after - t_before) + self.assertTrue(abs(t2 - (t_before + 2)) <= t_after - t_before) + self.assertTrue(abs(t3 - (t_before + 3)) <= t_after - t_before) + self.assertEqual(f1, f) + self.assertEqual(f2, g) + self.assertEqual(f3, h) + self.assertEqual(a1, (42, 'hello')) + self.assertEqual(a2, (100, 'abc')) + self.assertEqual(a3, ()) + self.assertEqual(k1, {'unused_a': 1, 'unused_b': 2}) + self.assertEqual(k2, {}) + self.assertEqual(k3, {'unused_c': 3, 'unused_d': 4}) + + ev = eventloop.get_event_loop() + ev.queue = [] + ev.rpcs = {} + + def testFifoOrderForEventsWithDelayNone(self): + order = [] + + def foo(arg): order.append(arg) + + eventloop.queue_call(None, foo, 2) + eventloop.queue_call(None, foo, 1) + eventloop.queue_call(0, foo, 0) + + self.assertEqual(len(self.ev.current), 2) + self.assertEqual(len(self.ev.queue), 1) + + [(_f1, a1, _k1), (_f2, a2, _k2)] = self.ev.current + self.assertEqual(a1, (2,)) + self.assertEqual(a2, (1,)) + (_t, _f, a, _k) = self.ev.queue[0] + + self.assertEqual(a, (0,)) + + eventloop.run() + + self.assertEqual(order, [2, 1, 0]) + + def testRun(self): + record = [] + + def foo(arg): + record.append(arg) + eventloop.queue_call(0.2, foo, 42) + eventloop.queue_call(0.1, foo, arg='hello') + eventloop.run() + self.assertEqual(record, ['hello', 42]) + + def testRunWithRpcs(self): + record = [] + + def foo(arg): + record.append(arg) + eventloop.queue_call(0.1, foo, 42) + config = datastore_rpc.Configuration(on_completion=foo) + rpc = self.conn.async_get(config, []) + if not isinstance(rpc, apiproxy_stub_map.UserRPC): + self.assertEqual(len(rpc.rpcs), 1) + rpc = rpc.rpcs[0] + eventloop.queue_rpc(rpc) + eventloop.run() + self.assertEqual(record, [rpc, 42]) + self.assertEqual(rpc.state, 2) + + def testIdle(self): + counters = [0, 0, 0] + + def idler1(): + logging.info('idler1 running') + counters[0] += 1 + return False + + def idler2(a, b=None): + logging.info('idler2 running: a=%s, b=%s', a, b) + counters[1] += 1 + return False + + def idler3(k=None): + logging.info('idler3 running: k=%s', k) + counters[2] += 1 + return None + self.ev.add_idle(idler1) + self.ev.add_idle(idler2, 10, 20) + eventloop.add_idle(idler3, k=42) + self.ev.run() + self.assertEqual(counters, [1, 1, 1]) + self.ev.run() + self.assertEqual(counters, [2, 2, 1]) + + def testMultiRpcReadiness(self): + from google.appengine.ext.ndb import key + k1 = key.Key('Foo', 1) + k2 = key.Key('Foo', 2) + r1 = self.conn.async_get(None, [k1]) + r2 = self.conn.async_get(None, [k2]) + rpc = datastore_rpc.MultiRpc([r1, r2]) + r1.wait() + r2.wait() + calls = [] + + def callback(): + calls.append(1) + eventloop.queue_rpc(rpc, callback) + eventloop.run() + self.assertEqual(calls, [1]) + + def testCleanUpStaleEvents(self): + + from google.appengine.ext.ndb import model + + class M(model.Model): + pass + M().put() + M().put() + M().put() + + + + + M.query().fetch_page(2) + ev = eventloop.get_event_loop() + self.assertEqual(len(ev.rpcs), 1) + del os.environ[eventloop._EVENT_LOOP_KEY] + ev = eventloop.get_event_loop() + self.assertEqual(len(ev.rpcs), 0) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0014310_test055.py b/pool/shard001/Python/0014310_test055.py new file mode 100644 index 0000000000000000000000000000000000000000..6691eb68012edc32066073d9a380a02ba8d1d26f --- /dev/null +++ b/pool/shard001/Python/0014310_test055.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# +# + +import common + +TEST_CASE = "ATOS open locked dryrun" + +from atoslib import process + +with open("test", "w") as tmpfile: + tmpfile.write("hello\n") + +process.setup({'dryrun': True}) +with process.open_locked('test') as inf: + out = inf.readline() + assert out == 'hello\n' + +with process.open_locked('aa', 'w') as outf: + outf.write(1) + diff --git a/pool/shard001/Python/0014311_mixins.py b/pool/shard001/Python/0014311_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..75e491605d6a7756cfddb09a94eec0ec1b8b15d3 --- /dev/null +++ b/pool/shard001/Python/0014311_mixins.py @@ -0,0 +1,22 @@ +#encoding:utf-8 +from datetime import date, timedelta, datetime +from kstore.helpers.dates import get_week + +class JerarquiaMixin(object): + jerarquia = ['Home', 'Index'] + + def get_context_data(self, **kwargs): + context = super(JerarquiaMixin, self).get_context_data(**kwargs) + context["jerarquia"] = self.jerarquia + return context + +class DateRangeMixin(object): + final_date = date.today() + d = timedelta(days=365) + initial_date = final_date - d + dates = [initial_date, final_date] + + def get_context_data(self, **kwargs): + context = super(DateRangeMixin, self).get_context_data(**kwargs) + context["dates"] = self.dates + return context diff --git a/pool/shard001/Python/0014313_scraper.py b/pool/shard001/Python/0014313_scraper.py new file mode 100644 index 0000000000000000000000000000000000000000..426ac297d0e46fb626c08d405da3c44bbd75ab18 --- /dev/null +++ b/pool/shard001/Python/0014313_scraper.py @@ -0,0 +1,30 @@ +import requests +from pyquery import PyQuery as pq + + +entry_points = [ + 'http://vancouver.en.craigslist.ca/search/apa/rch?query=&srchType=A&minAsk=800&maxAsk=1500&bedrooms=&hasPic=1', + 'http://vancouver.en.craigslist.ca/search/apa/rch?hasPic=1&maxAsk=1500&minAsk=800&srchType=A&s=100' + ] + + +entry_points = [ + 'http://vancouver.en.craigslist.ca/apa/', + 'http://vancouver.en.craigslist.ca/apa/index100.html', + 'http://vancouver.en.craigslist.ca/apa/index200.html', + 'http://vancouver.en.craigslist.ca/apa/index300.html' + ] + + +ads = [] + + +for url in entry_points: + html = requests.get(url).content + selector = pq(html) + ads.extend([ n.get('href') for n in selector('.row a') ]) + + +for url in ads: + #print "'" + url + "'," + print url \ No newline at end of file diff --git a/pool/shard001/Python/0014317_conf.py b/pool/shard001/Python/0014317_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..4cdcea46af5cbe18448863a4f9f03b96073bd9fc --- /dev/null +++ b/pool/shard001/Python/0014317_conf.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# 102shows documentation build configuration file, created by +# sphinx-quickstart on Wed Jan 11 01:00:44 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + + +# Code source (for autodoc) +import os +import sys + +sys.path.insert(0, os.path.abspath('../server')) + +on_rtd = os.environ.get('READTHEDOCS', None) is not None # are we building on readthedocs.io? + +if not on_rtd: + import sphinx_rtd_theme + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +needs_sphinx = '1.5.1' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. + +extensions = ['sphinx.ext.autodoc', + 'sphinx_autodoc_typehints', + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', + 'sphinx.ext.mathjax'] + +# include constructor descriptions +autoclass_content = 'both' + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = '102shows' +copyright = '2017, Simon Leiner' +author = 'Simon Leiner' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.2' +# The full version, including alpha/beta/rc tags. +release = '0.2-post' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' +html_style = 'css/custom_theme.css' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = '102showsdoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + 'papersize': 'a4paper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, '102shows.tex', '102shows Documentation', + 'Simon Leiner', 'manual'), +] + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, '102shows', '102shows Documentation', + [author], 1) +] + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, '102shows', '102shows Documentation', + author, '102shows', 'Raspberry Pi + APA102 + MQTT + 102shows = LED awesomeness!', + 'Home Automation'), +] + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/3.4/': None} + diff --git a/pool/shard001/Python/0014319_fetcher.py b/pool/shard001/Python/0014319_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..9543d401bb1cae3e1ad80aeee7f3e7b058b741dd --- /dev/null +++ b/pool/shard001/Python/0014319_fetcher.py @@ -0,0 +1,49 @@ +from __future__ import absolute_import + +from abc import abstractmethod +import random + +from .base import maybe_requirement +from .compatibility import AbstractClass + + +class FetcherBase(AbstractClass): + """ + A fetcher takes a Requirement and tells us where to crawl to find it. + """ + @abstractmethod + def urls(self, req): + raise NotImplementedError + + +class Fetcher(FetcherBase): + def __init__(self, urls): + self._urls = urls + + def urls(self, _): + return self._urls + + +class PyPIFetcher(FetcherBase): + PYPI_BASE = 'pypi.python.org' + + @classmethod + def resolve_mirrors(cls, base): + """Resolve mirrors per PEP-0381.""" + import socket + def crange(ch1, ch2): + return [chr(ch) for ch in range(ord(ch1), ord(ch2) + 1)] + last, _, _ = socket.gethostbyname_ex('last.' + base) + assert last.endswith(cls.PYPI_BASE) + last_prefix = last.split('.')[0] + # TODO(wickman) Is implementing > z really necessary? + last_prefix = 'z' if len(last_prefix) > 1 else last_prefix[0] + return ['%c.%s' % (letter, base) for letter in crange('a', last_prefix)] + + def __init__(self, pypi_base=PYPI_BASE, use_mirrors=False): + self.mirrors = self.resolve_mirrors(pypi_base) if use_mirrors else [pypi_base] + + def urls(self, req): + req = maybe_requirement(req) + random_mirror = random.choice(self.mirrors) + return ['https://%s/simple/%s/' % (random_mirror, req.project_name)] diff --git a/pool/shard001/Python/0014322_log.py b/pool/shard001/Python/0014322_log.py new file mode 100644 index 0000000000000000000000000000000000000000..88b62bfdcdc694efade38f1bd146be092959d4fa --- /dev/null +++ b/pool/shard001/Python/0014322_log.py @@ -0,0 +1,66 @@ +from threading import Thread +from Queue import Queue, Empty +from time import strftime, sleep +from bcolors import BColors + + +class Logger(Thread): + counter = 0 + INFO = 3 + WARNING = 2 + ERROR = 1 + DEBUG = 0 + LEVEL_STR = ['DEBUG', 'ERROR', 'WARNING', 'INFO'] + + def __init__(self, group=None, + target=None, + name=None, + args=(), + kwargs={}): + super(Logger, self).__init__(group, name, args, kwargs) + self.queue = Queue() + self.__stop = False + self.level = kwargs.get('level', Logger.ERROR) + self.id = Logger.counter + Logger.counter += 1 + + def run(self): + self.send(__name__, Logger.WARNING, + 'Logger(%d) thread started' % (self.id)) + self.send(__name__, Logger.DEBUG, + 'Logger(%d) verbosity' 'level = %s' % ( + self.id, + Logger.LEVEL_STR[self.level])) + while(1): + try: + print(self.queue.get(timeout=0.5)) + except Empty as e: + if(self.__stop): + break + else: + continue + + def send(self, modName, level, msg): + if(self.level <= level): + if(level == Logger.WARNING): + color = BColors.WARNING + elif(level == Logger.ERROR): + color = BColors.FAIL + elif(level == Logger.DEBUG): + color = BColors.OKGREEN + else: + color = '' + date = strftime('%d.%m.%Y/%H:%M:%S') + msg = '%s[%s] %s <%s>: %s %s' % ( + color, + date, + Logger.LEVEL_STR[level], + modName, + msg, + BColors.ENDC) + self.queue.put(msg, block=False) + + def stop(self): + self.send(__name__, Logger.WARNING, + 'Logger(%d) thread stopped' % (self.id)) + self.__stop = True diff --git a/pool/shard001/Python/0014325_layer_benchmarks_test.py b/pool/shard001/Python/0014325_layer_benchmarks_test.py new file mode 100644 index 0000000000000000000000000000000000000000..850e7efdf4557e83973230c6969d7901cf3ce43b --- /dev/null +++ b/pool/shard001/Python/0014325_layer_benchmarks_test.py @@ -0,0 +1,225 @@ +# Copyright 2020 The TensorFlow Authors. 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. +# ============================================================================== +"""Benchmarks on Keras layers.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools +import numpy as np +import six + +import tensorflow as tf +from tensorflow.python.keras.benchmarks import benchmark_util +from tensorflow.python.keras.benchmarks.layer_benchmarks import layer_benchmarks_test_base +from tensorflow.python.platform import benchmark + + +def _get_metadata(name): + return { + "model_name": "ideal_layers", + "parameters": name[1] + "_shape", + } + + +def _get_input_data(inputs): + if "input_shape" in inputs: + return tf.ones(inputs["input_shape"]) + elif "input" in inputs: + return inputs["input"] + else: + raise ValueError("Please specificy either `input_shape` or `input`" + "for the benchmark test") + + +def _layer_call_backward(layer, x): + with tf.GradientTape() as tape: + y = layer(x) + loss = tf.reduce_mean(y**2) + + _ = tape.gradient(loss, layer.trainable_variables) + + +class KerasLayerBenchmarks(six.with_metaclass( + benchmark.ParameterizedBenchmark, + layer_benchmarks_test_base.LayerBenchmarksBase)): + + # The parameter of each layer benchmark is a tuple, and the first one is + # the benchmark name. It must follow the convention of + # "{layer_name}_{small|normal|large}_shape" to make it compatible with + # `self.report_benchmark()` method. + _benchmark_parameters = benchmark_util.generate_benchmark_params_cpu_gpu([ + ("Conv2D_small_shape", tf.keras.layers.Conv2D, { + "filters": 1, + "kernel_size": 1, + "activation": "relu" + }, { + "input_shape": (1, 1, 1, 1) + }, 10), + ("Conv2D_normal_shape", tf.keras.layers.Conv2D, { + "filters": 1, + "kernel_size": 1, + "activation": "relu" + }, { + "input_shape": (64, 28, 28, 3) + }, 10), + ("LSTM_small_shape", tf.keras.layers.LSTM, { + "units": 1 + }, { + "input_shape": (1, 1, 1) + }, 10), + ("LSTM_normal_shape", tf.keras.layers.LSTM, { + "units": 4 + }, { + "input_shape": (32, 10, 8) + }, 10), + ("Embedding_small_shape", tf.keras.layers.Embedding, { + "input_dim": 1, + "output_dim": 1, + "input_length": 1 + }, { + "input": np.random.randint(1, size=(1, 1)) + }, 10), + ("Embedding_normal_shape", tf.keras.layers.Embedding, { + "input_dim": 1000, + "output_dim": 64, + "input_length": 10 + }, { + "input": np.random.randint(1000, size=(32, 10)) + }, 10), + ]) + + def benchmark_layer_call(self, layer_cls, layer_args, inputs, num_iters): + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + + fn = functools.partial(layer, x) + name = benchmark_util.get_benchmark_name(self._get_name()) + metadata = {"implementation": name[0] + ".layer.call"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + def benchmark_layer_call_with_function( + self, layer_cls, layer_args, inputs, num_iters): + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + layer.call = tf.function(layer.call) + + fn = functools.partial(layer, x) + name = benchmark_util.get_benchmark_name(self._get_name()) + metadata = {"implementation": name[0] + ".layer.call.function"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + def benchmark_layer_call_with_xla( + self, layer_cls, layer_args, inputs, num_iters): + name = benchmark_util.get_benchmark_name(self._get_name()) + # TODO(b/173461426) + if layer_cls is tf.keras.layers.Embedding and name[-1] == "GPU": + return + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + layer.call = tf.function( + layer.call, jit_compile=True) + + fn = functools.partial(layer, x) + metadata = {"implementation": name[0] + ".layer.call.xla"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + def benchmark_layer_call_backward( + self, layer_cls, layer_args, inputs, num_iters): + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + + fn = functools.partial(_layer_call_backward, layer, x) + name = benchmark_util.get_benchmark_name(self._get_name()) + metadata = {"implementation": name[0] + ".layer.call.backward"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + def benchmark_layer_call_backward_with_function( + self, layer_cls, layer_args, inputs, num_iters): + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + layer.call = tf.function(layer.call) + + fn = functools.partial(_layer_call_backward, layer, x) + name = benchmark_util.get_benchmark_name(self._get_name()) + metadata = {"implementation": name[0] + ".layer.call.backward.function"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + +class KerasLayerBenchmarksBackwardXLA(six.with_metaclass( + benchmark.ParameterizedBenchmark, + layer_benchmarks_test_base.LayerBenchmarksBase)): + + _benchmark_parameters = benchmark_util.generate_benchmark_params_cpu_gpu([ + ("Conv2D_small_shape", tf.keras.layers.Conv2D, { + "filters": 1, + "kernel_size": 1, + "activation": "relu" + }, { + "input_shape": (1, 1, 1, 1) + }, 10000), + ("Conv2D_normal_shape", tf.keras.layers.Conv2D, { + "filters": 1, + "kernel_size": 1, + "activation": "relu" + }, { + "input_shape": (64, 28, 28, 3) + }, 10000), + # TODO(b/153480400) + # ("LSTM_small_shape", tf.keras.layers.LSTM, + # {"units": 1}, {"input_shape": (1, 1, 1)}, 10000), + # ("LSTM_normal_shape", tf.keras.layers.LSTM, + # {"units": 4}, {"input_shape": (32, 10, 8)}, 10000), + ("Embedding_small_shape", tf.keras.layers.Embedding, { + "input_dim": 1, + "output_dim": 1, + "input_length": 1 + }, { + "input": np.random.randint(1, size=(1, 1)) + }, 10), + ("Embedding_normal_shape", tf.keras.layers.Embedding, { + "input_dim": 1000, + "output_dim": 64, + "input_length": 10 + }, { + "input": np.random.randint(1000, size=(32, 10)) + }, 10), + ]) + + def benchmark_layer_call_backward_with_xla( + self, layer_cls, layer_args, inputs, num_iters): + name = benchmark_util.get_benchmark_name(self._get_name()) + # TODO(b/173461426) + if layer_cls is tf.keras.layers.Embedding and name[-1] == "GPU": + return + layer = layer_cls(**layer_args) + x = _get_input_data(inputs) + layer.call = tf.function( + layer.call, jit_compile=True) + + fn = functools.partial(_layer_call_backward, layer, x) + metadata = {"implementation": name[0] + ".layer.call.backward.xla"} + metadata.update(_get_metadata(name)) + self.run_report(fn, num_iters, metadata) + + +if __name__ == "__main__": + tf.test.main() diff --git a/pool/shard001/Python/0014332_measureit_render.py b/pool/shard001/Python/0014332_measureit_render.py new file mode 100644 index 0000000000000000000000000000000000000000..27cf9bfbfadb0565f6508cbca2775659bf625ced --- /dev/null +++ b/pool/shard001/Python/0014332_measureit_render.py @@ -0,0 +1,334 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENCE BLOCK ***** + +# PEP8 compliant (https://www.python.org/dev/peps/pep-0008) + +# ---------------------------------------------------------- +# File: measureit_render.py +# support routines for render measures in final image +# Author: Antonio Vazquez (antonioya) +# +# ---------------------------------------------------------- +# noinspection PyUnresolvedReferences +import bpy +# noinspection PyUnresolvedReferences +import bgl +# noinspection PyUnresolvedReferences +import blf +# noinspection PyUnresolvedReferences +import mathutils +# noinspection PyUnresolvedReferences +import bmesh +import os +import sys +# noinspection PyUnresolvedReferences +import bpy_extras.image_utils as img_utils +# noinspection PyUnresolvedReferences +import bpy_extras.object_utils as object_utils +# noinspection PyUnresolvedReferences +from bpy_extras import view3d_utils +from math import ceil +from measureit_geometry import * + + +# ------------------------------------------------------------- +# Render image main entry point +# +# ------------------------------------------------------------- +def render_main(self, context, animation=False): + # noinspection PyBroadException,PyBroadException + try: + # Get visible layers + layers = [] + scene = context.scene + for x in range(0, 20): + if scene.layers[x] is True: + layers.extend([x]) + + # Get object list + objlist = context.scene.objects + # -------------------- + # Get resolution + # -------------------- + scene = bpy.context.scene + render_scale = scene.render.resolution_percentage / 100 + + width = int(scene.render.resolution_x * render_scale) + height = int(scene.render.resolution_y * render_scale) + + # --------------------------------------- + # Get output path + # --------------------------------------- + ren_path = bpy.context.scene.render.filepath + if len(ren_path) > 0: + if ren_path.endswith(os.path.sep): + initpath = os.path.realpath(ren_path) + os.path.sep + else: + (initpath, filename) = os.path.split(ren_path) + outpath = os.path.join(initpath, "measureit_tmp_render.png") + else: + self.report({'ERROR'}, + "MeasureIt: Unable to save temporary render image. Define a valid render path") + return False + + # Get Render Image + img = get_render_image(outpath) + if img is None: + self.report({'ERROR'}, + "MeasureIt: Unable to save temporary render image. Define a valid render path") + return False + + # ----------------------------- + # Calculate rows and columns + # ----------------------------- + tile_x = 240 + tile_y = 216 + row_num = ceil(height / tile_y) + col_num = ceil(width / tile_x) + print("MeasureIt: Image divided in " + str(row_num) + "x" + str(col_num) + " tiles") + + # pixels out of visible area + cut4 = (col_num * tile_x * 4) - width * 4 # pixels aout of drawing area + totpixel4 = width * height * 4 # total pixels RGBA + + viewport_info = bgl.Buffer(bgl.GL_INT, 4) + bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info) + + # Load image on memory + img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST) + tex = img.bindcode + + # -------------------------------------------- + # Create output image (to apply texture) + # -------------------------------------------- + if "measureit_output" in bpy.data.images: + out_img = bpy.data.images["measureit_output"] + if out_img is not None: + out_img.user_clear() + bpy.data.images.remove(out_img) + + out = bpy.data.images.new("measureit_output", width, height) + tmp_pixels = [1] * totpixel4 + + # -------------------------------- + # Loop for all tiles + # -------------------------------- + for row in range(0, row_num): + for col in range(0, col_num): + buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4) + bgl.glDisable(bgl.GL_SCISSOR_TEST) # if remove this line, get blender screenshot not image + bgl.glViewport(0, 0, tile_x, tile_y) + + bgl.glMatrixMode(bgl.GL_PROJECTION) + bgl.glLoadIdentity() + + # defines ortographic view for single tile + x1 = tile_x * col + y1 = tile_y * row + bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y) + + # Clear + bgl.glClearColor(0.0, 0.0, 0.0, 0.0) + bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT) + + bgl.glEnable(bgl.GL_TEXTURE_2D) + bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex) + + # defines drawing area + bgl.glBegin(bgl.GL_QUADS) + + bgl.glColor3f(1.0, 1.0, 1.0) + bgl.glTexCoord2f(0.0, 0.0) + bgl.glVertex2f(0.0, 0.0) + + bgl.glTexCoord2f(1.0, 0.0) + bgl.glVertex2f(width, 0.0) + + bgl.glTexCoord2f(1.0, 1.0) + bgl.glVertex2f(width, height) + + bgl.glTexCoord2f(0.0, 1.0) + bgl.glVertex2f(0.0, height) + + bgl.glEnd() + + # ----------------------------- + # Loop to draw all lines + # ----------------------------- + for myobj in objlist: + if myobj.hide is False: + if 'MeasureGenerator' in myobj: + # verify visible layer + for x in range(0, 20): + if myobj.layers[x] is True: + if x in layers: + op = myobj.MeasureGenerator[0] + draw_segments(context, myobj, op, None, None) + break + + # ----------------------------- + # Loop to draw all debug + # ----------------------------- + if scene.measureit_debug is True: + selobj = bpy.context.selected_objects + for myobj in selobj: + if scene.measureit_debug_vertices is True: + draw_vertices(context, myobj, None, None) + if scene.measureit_debug_faces is True or scene.measureit_debug_normals is True: + draw_faces(context, myobj, None, None) + + + + if scene.measureit_rf is True: + bgl.glColor3f(1.0, 1.0, 1.0) + rfcolor = scene.measureit_rf_color + rfborder = scene.measureit_rf_border + rfline = scene.measureit_rf_line + + bgl.glLineWidth(rfline) + bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3]) + + x1 = rfborder + x2 = width - rfborder + y1 = int(math.ceil(rfborder / (width / height))) + y2 = height - y1 + draw_rectangle((x1, y1), (x2, y2)) + + # -------------------------------- + # copy pixels to temporary area + # -------------------------------- + bgl.glFinish() + bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer) # read image data + for y in range(0, tile_y): + # final image pixels position + p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4) + p2 = p1 + (tile_x * 4) + # buffer pixels position + b1 = y * width * 4 + b2 = b1 + (tile_x * 4) + + if p1 < totpixel4: # avoid pixel row out of area + if col == col_num - 1: # avoid pixel columns out of area + p2 -= cut4 + b2 -= cut4 + + tmp_pixels[p1:p2] = buffer[b1:b2] + + # ----------------------- + # Copy temporary to final + # ----------------------- + out.pixels = tmp_pixels[:] # Assign image data + img.gl_free() # free opengl image memory + + # delete image + img.user_clear() + bpy.data.images.remove(img) + # remove temp file + os.remove(outpath) + # reset + bgl.glEnable(bgl.GL_SCISSOR_TEST) + # ----------------------- + # restore opengl defaults + # ----------------------- + bgl.glLineWidth(1) + bgl.glDisable(bgl.GL_BLEND) + bgl.glColor4f(0.0, 0.0, 0.0, 1.0) + # Saves image + if out is not None and (scene.measureit_render is True or animation is True): + ren_path = bpy.context.scene.render.filepath + filename = "mit_frame" + if len(ren_path) > 0: + if ren_path.endswith(os.path.sep): + initpath = os.path.realpath(ren_path) + os.path.sep + else: + (initpath, filename) = os.path.split(ren_path) + + ftxt = "%04d" % scene.frame_current + outpath = os.path.join(initpath, filename + ftxt + ".png") + + save_image(self, outpath, out) + + return True + + except: + print("Unexpected error:" + str(sys.exc_info())) + self.report({'ERROR'}, "MeasureIt: Unable to create render image") + return False + + +# -------------------------------------------------------------------- +# Get the final render image and return as image object +# +# return None if no render available +# -------------------------------------------------------------------- +def get_render_image(outpath): + saved = False + # noinspection PyBroadException + try: + # noinspection PyBroadException + try: + result = bpy.data.images['Render Result'] + if result.has_data is False: + # this save produce to fill data image + result.save_render(outpath) + saved = True + except: + print("No render image found") + return None + + # Save and reload + if saved is False: + result.save_render(outpath) + + img = img_utils.load_image(outpath) + + return img + except: + print("Unexpected render image error") + return None + + +# ------------------------------------- +# Save image to file +# ------------------------------------- +def save_image(self, filepath, myimage): + # noinspection PyBroadException + try: + + # Save old info + settings = bpy.context.scene.render.image_settings + myformat = settings.file_format + mode = settings.color_mode + depth = settings.color_depth + + # Apply new info and save + settings.file_format = 'PNG' + settings.color_mode = "RGBA" + settings.color_depth = '8' + myimage.save_render(filepath) + print("MeasureIt: Image " + filepath + " saved") + + # Restore old info + settings.file_format = myformat + settings.color_mode = mode + settings.color_depth = depth + except: + print("Unexpected error:" + str(sys.exc_info())) + self.report({'ERROR'}, "MeasureIt: Unable to save render image") + return diff --git a/pool/shard001/Python/0014333_data.py b/pool/shard001/Python/0014333_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d297fb9dd6cefe7200187f2ef41de667f235313f --- /dev/null +++ b/pool/shard001/Python/0014333_data.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# Amara, universalsubtitles.org +# +# Copyright (C) 2013 Participatory Culture Foundation +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see +# http://www.gnu.org/licenses/agpl-3.0.html. +"""Data creation and retrieval functions for the video tests.""" + +from babelsubs.storage import SubtitleLine +from auth.models import CustomUser as User +from videos.models import Video +from subtitles import pipeline +from subtitles.models import SubtitleLanguage +from teams.models import Team, TeamMember, TeamVideo, Workflow +from teams.permissions_const import ( + ROLE_OWNER, ROLE_ADMIN, ROLE_MANAGER, ROLE_CONTRIBUTOR +) + +# Normal Users ---------------------------------------------------------------- +def get_user(n=1): + username = 'test_user_%s' % n + email = "test_user_%s@example.com" % n + try: + user = User.objects.get(username=username) + except User.DoesNotExist: + user = User.objects.create( + username=username, email=email, + is_active=True, is_superuser=False, is_staff=False, + password="sha1$6b3dc$72c6a16f127d2c217f72009632c745effef7eb3f", + ) + user.set_password('password') + user.save() + return user + + +# Site Admins ----------------------------------------------------------------- +def get_site_admin(n=1): + username = 'test_admin_%s' % n + email = "test_admin_%s@example.com" % n + try: + user = User.objects.get(username=username) + except User.DoesNotExist: + user = User.objects.create( + username=username, email=email, + is_active=True, is_superuser=True, is_staff=True, + password="sha1$6b3dc$72c6a16f127d2c217f72009632c745effef7eb3f", + ) + return user + + +# Videos ---------------------------------------------------------------------- +VIDEO_URLS = ('http://youtu.be/heKK95DAKms', + 'http://youtu.be/e4MSN6IImpI', + 'http://youtu.be/i_0DXxNeaQ0',) + +def get_video(n=1, user=None, url=None): + if not url: + url = VIDEO_URLS[n] + video, _ = Video.get_or_create_for_url(url, user=user) + return video + + +# Subtitle Languages ---------------------------------------------------------- +def make_subtitle_language(video, language_code): + sl = SubtitleLanguage(video=video, language_code=language_code) + sl.save() + return sl + + +# Subtitle Versions ----------------------------------------------------------- +def make_subtitle_lines(count, is_synced=True): + lines = [] + for line_num in xrange(0, count): + lines.append(SubtitleLine( + line_num * 1000 if is_synced else None, + line_num * 1000 + 900 if is_synced else None, + "%s" % line_num, + {} + )) + return lines + +def make_subtitle_version(subtitle_language, subtitles=[], author=None, + parents=None, committer=None, complete=None, + title=None, description=None, created=None,note=None): + committer = committer or author + return pipeline.add_subtitles(subtitle_language.video, + subtitle_language.language_code, + subtitles, + author=author, + parents=parents, + committer=committer, + complete=complete, + title=title, + created=created, + note=note, + description=description) + +def make_rollback_to(subtitle_language, version_number): + return pipeline.rollback_to(subtitle_language.video, + subtitle_language.language_code, + version_number) + + +# Teams ----------------------------------------------------------------------- +def get_team(n=1, reviewers='', approvers=''): + slug = 'test_team_%s' % n + try: + team = Team.objects.get(slug=slug) + except Team.DoesNotExist: + team = Team.objects.create(name='Test Team %s' % n, + slug=slug) + + if reviewers or approvers: + reviewers = reviewers.rstrip('s') + approvers = approvers.rstrip('s') + + review = {'peer': 10, 'manager': 20, 'admin': 30}.get(reviewers, 00) + approve = {'manager': 10, 'admin': 20}.get(approvers, 00) + + Workflow.objects.create(team=team, review_allowed=review, + approve_allowed=approve) + + team.workflow_enabled = True + team.save() + + return team + +def get_team_member(user, team, role='contributor'): + try: + tm = TeamMember.objects.get(user=user, team=team) + except TeamMember.DoesNotExist: + role = { + 'contributor': ROLE_CONTRIBUTOR, + 'manager': ROLE_MANAGER, + 'admin': ROLE_ADMIN, + 'owner': ROLE_OWNER, + }.get(role) + tm = TeamMember.objects.create(user=user, team=team, role=role) + + return tm + +def get_team_video(video, team, user): + try: + tv = TeamVideo.objects.get(video=video, team=team) + except TeamVideo.DoesNotExist: + tv = TeamVideo.objects.create(video=video, team=team, added_by=user) + + return tv diff --git a/pool/shard001/Python/0014335_03-zeppelin-spark-smoke.py b/pool/shard001/Python/0014335_03-zeppelin-spark-smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..b7cb918dae187a779c726eda57d7ebdfcfcb842f --- /dev/null +++ b/pool/shard001/Python/0014335_03-zeppelin-spark-smoke.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 + +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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 amulet +import re +import unittest + + +class TestSmokeSpark(unittest.TestCase): + """ + Smoke test for Apache Bigtop Zeppelin using remote Spark resources. + """ + @classmethod + def setUpClass(cls): + cls.d = amulet.Deployment(series='xenial') + cls.d.add('zeppelin') + cls.d.add('zeppelin-test-spark', charm='spark') + + cls.d.relate('zeppelin-test-spark:client', 'zeppelin:spark') + + cls.d.setup(timeout=1800) + cls.d.sentry.wait_for_messages({'zeppelin': re.compile('ready with')}, timeout=1800) + cls.zeppelin = cls.d.sentry['zeppelin'][0] + + @classmethod + def tearDownClass(cls): + # NB: seems to be a remove_service issue with amulet. However, the + # unit does still get removed. Pass OSError for now: + # OSError: juju command failed ['remove-application', ...]: + # ERROR allocation for service ... owned by ... not found + try: + cls.d.remove_service('zeppelin-test-spark') + except OSError as e: + print("IGNORE: Amulet remove_service failed: {}".format(e)) + pass + + def test_zeppelin(self): + """ + Validate Zeppelin by running the smoke-test action. + """ + uuid = self.zeppelin.run_action('smoke-test') + result = self.d.action_fetch(uuid, full_output=True) + # action status=completed on success + if (result['status'] != "completed"): + self.fail('Zeppelin smoke-test failed: %s' % result) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0014337_vlans.py b/pool/shard001/Python/0014337_vlans.py new file mode 100644 index 0000000000000000000000000000000000000000..314c12899ed6327c0cfa5f7fa9dd59fb4d7aa5b9 --- /dev/null +++ b/pool/shard001/Python/0014337_vlans.py @@ -0,0 +1,52 @@ + +from vsvlandb import dbo +from vsvlandb.helpers import sitesAndSubnets +from vsvlandb.models import VLAN, Subnet, Site + +from flask import flash + +def delete_id(vlan_id, flash_msg=True): + vlan = VLAN.query.filter_by(id=vlan_id).limit(1).first() + + if vlan: + dbo.session.delete(vlan) + dbo.session.commit() + + if flash_msg: + flash("Deleted VLAN {}".format(vlan.vlan), category='success') + +def delete_vlan(vlan, flash_msg=True): + vlans = VLAN.query.filter_by(vlan=vlan).all() + + if vlans: + for vlan in vlans: + dbo.session.delete(vlan) + dbo.session.commit() + + if flash_msg: + flash("Deleted VLAN {}".format(vlan), category='success') + +def edit(form, vlan_id, flash_msg=True): + sites,subnets = sitesAndSubnets(form) + + if sites or subnets: + delete_vlan(form.vlanid.data, False) + add(form, False) + else: + delete_id(vlan_id, False) + add(form, False) + + if flash_msg: + flash("Updated VLAN {0}".format(form.vlanid.data), category='success') + +def add(form, flash_msg=True): + sites,subnets = sitesAndSubnets(form) + + vlan = VLAN(form.vlanid.data, subnets=subnets, sites=sites, isactive=form.isactive.data, enhanced=form.enhanced.data) + dbo.session.add(vlan) + dbo.session.commit() + + if flash_msg: + flash("Added VLAN {0}".format(form.vlanid.data), category='success') + + diff --git a/pool/shard001/Python/0014338_urls.py b/pool/shard001/Python/0014338_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0a34e2b1fc6ed8e05e0f3342951b0aca424ec1 --- /dev/null +++ b/pool/shard001/Python/0014338_urls.py @@ -0,0 +1,21 @@ +# Copyright (c) 2007-2009 The PyAMF Project. +# See LICENSE.txt for details. + +""" +@since: 0.1.0 +""" + +from django.conf.urls.defaults import * +import os + +urlpatterns = patterns('', + + # AMF Remoting Gateway + # The gateway parameter may also be a direct reference + # to a pyamf.remoting.gateway.django.DjangoGateway instance + (r'^$', 'echo.gateway.echoGateway'), + + # Serve crossdomain.xml from the directory below __file__ + (r'^crossdomain.xml$', 'django.views.static.serve', + {'document_root': os.path.abspath(os.path.join(os.path.dirname(__file__), '..')), 'path': 'crossdomain.xml'}) +) diff --git a/pool/shard001/Python/0014342_PpcPosChain.py b/pool/shard001/Python/0014342_PpcPosChain.py new file mode 100644 index 0000000000000000000000000000000000000000..d19d629c0735816d5f832b647008632e95b24d4d --- /dev/null +++ b/pool/shard001/Python/0014342_PpcPosChain.py @@ -0,0 +1,30 @@ +# Copyright(C) 2014 by Abe developers. + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public +# License along with this program. If not, see +# . + +from . import BaseChain +from .. import deserialize + +class PpcPosChain(BaseChain): + """ + A blockchain with proof-of-stake as in Peercoin. + """ + def ds_parse_transaction(chain, ds): + return deserialize.parse_Transaction(ds, has_nTime=True) + + def ds_parse_block(chain, ds): + d = BaseChain.ds_parse_block(chain, ds) + d['block_sig'] = ds.read_bytes(ds.read_compact_size()) + return d diff --git a/pool/shard001/Python/0014347_login_frame.py b/pool/shard001/Python/0014347_login_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..e66d64cfe9b411206cd05f2bbda53da702f3c072 --- /dev/null +++ b/pool/shard001/Python/0014347_login_frame.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# generated by wxGlade 0.6.5 on Mon Oct 21 10:09:44 2013 + +import wx +import time +# begin wxGlade: extracode +# end wxGlade + +# TODO implement autoclose and updates. + + +class my_login_frame(wx.Frame): + def __init__(self, *args, **kwds): + # begin wxGlade: my_login_frame.__init__ + kwds["style"] = wx.DEFAULT_FRAME_STYLE + wx.Frame.__init__(self, *args, **kwds) + self.label_1 = wx.StaticText(self, -1, "login:", style=wx.ALIGN_CENTRE) + self.text_ctrl_2 = wx.TextCtrl(self, -1, "") + self.label_2 = wx.StaticText(self, -1, "password:") + self.text_ctrl_3 = wx.TextCtrl(self, -1, "") + self.button_1 = wx.Button(self, -1, "Submit") + self.label_3 = wx.StaticText(self, -1, "") + + self.__set_properties() + self.__do_layout() + + self.Bind(wx.EVT_BUTTON, self.getvals, self.button_1) + # end wxGlade + + self.login_info = "" # login info for user + + def __set_properties(self): + # begin wxGlade: my_login_frame.__set_properties + self.SetTitle("log info") + _icon = wx.EmptyIcon() + _icon.CopyFromBitmap(wx.Bitmap("folder_music.ico", wx.BITMAP_TYPE_ANY)) + self.button_1.SetMinSize((85, 33)) + self.SetBackgroundColour(wx.Colour(127, 170, 191)) + # end wxGlade + + def __do_layout(self): + # begin wxGlade: my_login_frame.__do_layout + sizer_2 = wx.BoxSizer(wx.VERTICAL) + sizer_5 = wx.BoxSizer(wx.HORIZONTAL) + sizer_4 = wx.BoxSizer(wx.HORIZONTAL) + sizer_3 = wx.BoxSizer(wx.HORIZONTAL) + sizer_3.Add((10, 20), 0, 0, 0) + sizer_3.Add(self.label_1, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 0) + sizer_3.Add((49, 20), 0, 0, 0) + sizer_3.Add(self.text_ctrl_2, 0, wx.ALIGN_CENTER_HORIZONTAL | + wx.ALIGN_CENTER_VERTICAL, 0) + sizer_2.Add(sizer_3, 1, 0, 0) + sizer_4.Add((10, 20), 0, 0, 0) + sizer_4.Add(self.label_2, 0, wx.ALIGN_CENTER_VERTICAL, 0) + sizer_4.Add((20, 20), 0, 0, 0) + sizer_4.Add(self.text_ctrl_3, 0, wx.ALIGN_CENTER_HORIZONTAL | + wx.ALIGN_CENTER_VERTICAL, 0) + sizer_2.Add(sizer_4, 1, 0, 0) + sizer_5.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0) + sizer_5.Add(self.label_3, 0, wx.SHAPED, 0) + sizer_2.Add(sizer_5, 1, wx.EXPAND, 0) + self.SetSizer(sizer_2) + sizer_2.Fit(self) + self.Layout() + # end wxGlade + + def get_text(self): + return self.login_info + + def getvals(self, event): # wxGlade: my_login_frame. + self.login_info = self.text_ctrl_2.GetValue() + "\n" + \ + self.text_ctrl_3.GetValue() + "\n" + # TODO add server declaration + # checks to see either string has anything in them besides whitespace + if (self.text_ctrl_2.GetValue().strip() and self.text_ctrl_3.GetValue().strip()): + self.label_3.SetLabel("waiting...\nsuccess!") + # TODO add server resulsts here. + self.config = open("config.cfg", "w") + self.config.write(self.get_text()) + self.config.close() + + else: + self.label_3.SetLabel("Error with \nlogin/pass") + + +# end of class my_login_frame +if __name__ == "__main__": + app = wx.PySimpleApp(0) + wx.InitAllImageHandlers() + login = my_login_frame(None, -1, "") + app.SetTopWindow(login) + login.Show() + app.MainLoop() diff --git a/pool/shard001/Python/0014352_test_ols.py b/pool/shard001/Python/0014352_test_ols.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab27da3f1b8ec67fcf976c9a3cffba870946ea5 --- /dev/null +++ b/pool/shard001/Python/0014352_test_ols.py @@ -0,0 +1,105 @@ +from os import path + +import pandas as pd + +from econtools.metrics.util.testing import RegCompare +from econtools.metrics.api import reg +from econtools.metrics.tests.data.src_ols import (ols_std, ols_robust, ols_hc2, + ols_hc3, ols_cluster) + + +class TestOLS_std(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + cls.precision['vce'] = 6 + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = 'price' + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, addcons=True) + cls.expected = ols_std + + +class TestOLS_std_y_list(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + cls.precision['vce'] = 6 + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = ['price'] + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, addcons=True) + cls.expected = ols_std + + +class TestOLS_hc1(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = 'price' + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, vce_type='hc1', addcons=True) + cls.expected = ols_robust + + +class TestOLS_hc2(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = 'price' + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, vce_type='hc2', addcons=True) + cls.expected = ols_hc2 + + +class TestOLS_hc3(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = 'price' + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, vce_type='hc3', addcons=True) + cls.expected = ols_hc3 + + +class TestOLS_cluster(RegCompare): + + @classmethod + def setup_class(cls): + """Stata reg output from `sysuse auto; reg price mpg`""" + cls.init(cls) + test_path = path.split(path.relpath(__file__))[0] + auto_path = path.join(test_path, 'data', 'auto.dta') + autodata = pd.read_stata(auto_path) + y = 'price' + x = ['mpg', 'length'] + cls.result = reg(autodata, y, x, cluster='gear_ratio', addcons=True) + cls.expected = ols_cluster + + +if __name__ == '__main__': + import pytest + pytest.main() diff --git a/pool/shard001/Python/0014355_ostreesetup.py b/pool/shard001/Python/0014355_ostreesetup.py new file mode 100644 index 0000000000000000000000000000000000000000..ad3af7c9f8ff41946ead7d08003d722891bfe7ad --- /dev/null +++ b/pool/shard001/Python/0014355_ostreesetup.py @@ -0,0 +1,74 @@ +# +# Copyright (C) 2014 Red Hat, Inc. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions of +# the GNU General Public License v.2, or (at your option) any later version. +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY expressed or implied, including the implied warranties of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. You should have received a copy of the +# GNU General Public License along with this program; if not, write to the +# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the +# source code or documentation are not subject to the GNU General Public +# License and may only be used or replicated with the express permission of +# Red Hat, Inc. +# + +from pykickstart.base import KickstartCommand +from pykickstart.options import KSOptionParser + +class F21_OSTreeSetup(KickstartCommand): + removedKeywords = KickstartCommand.removedKeywords + removedAttrs = KickstartCommand.removedAttrs + + def __init__(self, *args, **kwargs): + KickstartCommand.__init__(self, *args, **kwargs) + self.op = self._getParser() + self.osname = kwargs.get('osname', None) + self.remote = kwargs.get("remote", self.osname) + self.url = kwargs.get('url', None) + self.ref = kwargs.get('ref', None) + self.nogpg = kwargs.get('nogpg', False) + + def __str__(self): + retval = KickstartCommand.__str__(self) + + if self.osname: + retval += "# OSTree setup\n" + retval += "ostreesetup %s\n" % self._getArgsAsStr() + + return retval + + def _getArgsAsStr(self): + retcmd = [] + if self.osname: + retcmd.append('--osname="%s"' % self.osname) + if self.remote: + retcmd.append('--remote="%s"' % self.remote) + if self.url: + retcmd.append('--url="%s"' % self.url) + if self.ref: + retcmd.append('--ref="%s"' % self.ref) + if self.nogpg: + retcmd.append('--nogpg') + return ' '.join(retcmd) + + def _getParser(self): + op = KSOptionParser() + op.add_option("--osname", dest="osname", required=1) + op.add_option("--remote", dest="remote") + op.add_option("--url", dest="url", required=1) + op.add_option("--ref", dest="ref", required=1) + op.add_option("--nogpg", action="store_true") + return op + + def parse(self, args): + (opts, _extra) = self.op.parse_args(args=args, lineno=self.lineno) + self._setToSelf(self.op, opts) + if self.remote is None: + self.remote = self.osname + return self + +RHEL7_OSTreeSetup = F21_OSTreeSetup diff --git a/pool/shard001/Python/0014356_test_contact.py b/pool/shard001/Python/0014356_test_contact.py new file mode 100644 index 0000000000000000000000000000000000000000..05c3d810952020c09e4a422e1b9811cecd6fb83c --- /dev/null +++ b/pool/shard001/Python/0014356_test_contact.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2014-present Taiga Agile LLC +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from django.urls import reverse + +from tests import factories as f +from tests.utils import helper_test_http_method + +from taiga.base.utils import json + +import pytest +pytestmark = pytest.mark.django_db + + +@pytest.fixture +def data(): + m = type("Models", (object,), {}) + m.user = f.UserFactory.create() + m.project = f.ProjectFactory.create(is_private=False) + f.MembershipFactory(user=m.project.owner, project=m.project, is_admin=True) + + return m + + +def test_contact_create(client, data): + url = reverse("contact-list") + users = [None, data.user] + + contact_data = json.dumps({ + "project": data.project.id, + "comment": "Testing comment" + }) + results = helper_test_http_method(client, 'post', url, contact_data, users) + assert results == [401, 201] diff --git a/pool/shard001/Python/0014359_test_docs.py b/pool/shard001/Python/0014359_test_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ed4a3d76d08cd486799fca297db5278821b9e0 --- /dev/null +++ b/pool/shard001/Python/0014359_test_docs.py @@ -0,0 +1,34 @@ +# -*- coding: ascii -*- + +from doctest import DocFileSuite +import unittest +import os.path +import sys + +THIS_DIR = os.path.dirname(__file__) + +README = os.path.join(THIS_DIR, os.pardir, os.pardir, 'README.txt') + + +class DocumentationTestCase(unittest.TestCase): + def test_readme_encoding(self): + '''Confirm the README.txt is pure ASCII.''' + f = open(README, 'rb') + try: + f.read().decode('ASCII') + finally: + f.close() + + +def test_suite(): + "For the Z3 test runner" + return unittest.TestSuite(( + DocumentationTestCase('test_readme_encoding'), + DocFileSuite(os.path.join(os.pardir, os.pardir, 'README.txt')))) + + +if __name__ == '__main__': + sys.path.insert( + 0, os.path.abspath(os.path.join(THIS_DIR, os.pardir, os.pardir)) + ) + unittest.main(defaultTest='test_suite') diff --git a/pool/shard001/Python/0014364_i18n.py b/pool/shard001/Python/0014364_i18n.py new file mode 100644 index 0000000000000000000000000000000000000000..adde331a094f1746e104e7cde4538337c062d997 --- /dev/null +++ b/pool/shard001/Python/0014364_i18n.py @@ -0,0 +1,74 @@ +""" +Template tags for handling i18n translations for xblocks + +Based on: https://github.com/eduNEXT/django-xblock-i18n +""" + +from contextlib import contextmanager + +from django.template import Library, Node +from django.templatetags import i18n +from django.utils.translation import trans_real, get_language + + +register = Library() + + +class ProxyTransNode(Node): + """ + This node is a proxy of a django TranslateNode. + """ + def __init__(self, do_translate_node): + """ + Initialize the ProxyTransNode + """ + self.do_translate = do_translate_node + self._translations = {} + + @contextmanager + def merge_translation(self, context): + """ + Context wrapper which modifies the given language's translation catalog using the i18n service, if found. + """ + language = get_language() + i18n_service = context.get('_i18n_service', None) + if i18n_service: + # Cache the original translation object to reduce overhead + if language not in self._translations: + self._translations[language] = trans_real.DjangoTranslation(language) + + translation = trans_real.translation(language) + translation.merge(i18n_service) + + yield + + # Revert to original translation object + if language in self._translations: + trans_real._translations[language] = self._translations[language] # pylint: disable=protected-access + # Re-activate the current language to reset translation caches + trans_real.activate(language) + + def render(self, context): + """ + Renders the translated text using the XBlock i18n service, if available. + """ + with self.merge_translation(context): + django_translated = self.do_translate.render(context) + + return django_translated + + +@register.tag('trans') +def xblock_translate(parser, token): + """ + Proxy implementation of the i18n `trans` tag. + """ + return ProxyTransNode(i18n.do_translate(parser, token)) + + +@register.tag('blocktrans') +def xblock_translate_block(parser, token): + """ + Proxy implementation of the i18n `blocktrans` tag. + """ + return ProxyTransNode(i18n.do_block_translate(parser, token)) diff --git a/pool/shard001/Python/0014368_chapters_views.py b/pool/shard001/Python/0014368_chapters_views.py new file mode 100644 index 0000000000000000000000000000000000000000..53d6a1ae5012afba5992c3198f68414c29170271 --- /dev/null +++ b/pool/shard001/Python/0014368_chapters_views.py @@ -0,0 +1,16 @@ +from django.contrib.auth.decorators import login_required +from django.shortcuts import render, redirect + +from pythonpro.modules import facade + + +@login_required +def detail_old(request, chapter_slug): + chapter = facade.get_chapter_with_contents(slug=chapter_slug) + return redirect(chapter.get_absolute_url(), permanent=True) + + +@login_required +def detail(request, module_slug, chapter_slug): + ctx = {'chapter': facade.get_chapter_with_contents(slug=chapter_slug)} + return render(request, 'chapters/chapter_detail.html', context=ctx) diff --git a/pool/shard001/Python/0014372_test_lemmatization.py b/pool/shard001/Python/0014372_test_lemmatization.py new file mode 100644 index 0000000000000000000000000000000000000000..c009e72c0016b3770c4c54481db7c12d4ded1fe9 --- /dev/null +++ b/pool/shard001/Python/0014372_test_lemmatization.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +from __future__ import unicode_literals + +import pytest + + +@pytest.mark.models +def test_lemmatizer_verb(FR): + text = "Qu'est-ce que tu fais?" + tokens = FR(text) + assert tokens[0].lemma_ == "que" + assert tokens[1].lemma_ == "être" + assert tokens[5].lemma_ == "faire" + +@pytest.mark.models +@pytest.mark.xfail(reason="sont tagged as AUX") +def test_lemmatizer_noun_verb_2(FR): + text = "Les abaissements de température sont gênants." + tokens = FR(text) + assert tokens[4].lemma_ == "être" + +@pytest.mark.models +@pytest.mark.xfail(reason="Costaricienne TAG is PROPN instead of NOUN and spacy don't lemmatize PROPN") +def test_lemmatizer_noun(FR): + text = "il y a des Costaricienne." + tokens = FR(text) + assert tokens[4].lemma_ == "Costaricain" + +@pytest.mark.models +def test_lemmatizer_noun_2(FR): + text = "Les abaissements de température sont gênants." + tokens = FR(text) + assert tokens[1].lemma_ == "abaissement" + assert tokens[5].lemma_ == "gênant" + + diff --git a/pool/shard001/Python/0014376_message.py b/pool/shard001/Python/0014376_message.py new file mode 100644 index 0000000000000000000000000000000000000000..76b06357a269ac6fccb72894a8ee70b051124d6b --- /dev/null +++ b/pool/shard001/Python/0014376_message.py @@ -0,0 +1,99 @@ +from lib.common import helpers + +class Module: + + def __init__(self, mainMenu, params=[]): + + self.info = { + 'Name': 'Invoke-Message', + + 'Author': ['@harmj0y'], + + 'Description': ("Displays a specified message to the user."), + + 'Background' : True, + + 'OutputExtension' : None, + + 'NeedsAdmin' : False, + + 'OpsecSafe' : False, + + 'Language' : 'powershell', + + 'MinLanguageVersion' : '2', + + 'Comments': [ + 'http://blog.logrhythm.com/security/do-you-trust-your-computer/' + ] + } + + # any options needed by the module, settable during runtime + self.options = { + # format: + # value_name : {description, required, default_value} + 'Agent' : { + 'Description' : 'Agent to run module on.', + 'Required' : True, + 'Value' : '' + }, + 'MsgText' : { + 'Description' : 'Message text to display.', + 'Required' : True, + 'Value' : 'Lost contact with the Domain Controller.' + }, + 'IconType' : { + 'Description' : 'Critical, Question, Exclamation, or Information', + 'Required' : True, + 'Value' : 'Critical' + }, + 'Title' : { + 'Description' : 'Title of the message box to display.', + 'Required' : True, + 'Value' : 'ERROR - 0xA801B720' + } + } + + # save off a copy of the mainMenu object to access external functionality + # like listeners/agent handlers/etc. + self.mainMenu = mainMenu + + for param in params: + # parameter format is [Name, Value] + option, value = param + if option in self.options: + self.options[option]['Value'] = value + + + def generate(self, obfuscate=False, obfuscationCommand=""): + + script = """ +function Invoke-Message { + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $True, Position = 0)] + [String] $MsgText, + + [Parameter(Mandatory = $False, Position = 1)] + [String] $IconType = 'Critical', + + [Parameter(Mandatory = $False, Position = 2)] + [String] $Title = 'ERROR - 0xA801B720' + ) + + Add-Type -AssemblyName Microsoft.VisualBasic + $null = [Microsoft.VisualBasic.Interaction]::MsgBox($MsgText, "OKOnly,MsgBoxSetForeground,SystemModal,$IconType", $Title) +} +Invoke-Message""" + + for option,values in self.options.iteritems(): + if option.lower() != "agent" and option.lower() != "computername": + if values['Value'] and values['Value'] != '': + if values['Value'].lower() == "true": + # if we're just adding a switch + script += " -" + str(option) + else: + script += " -" + str(option) + " \"" + str(values['Value'].strip("\"")) + "\"" + if obfuscate: + script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) + return script diff --git a/pool/shard001/Python/0014381_test_group.py b/pool/shard001/Python/0014381_test_group.py new file mode 100644 index 0000000000000000000000000000000000000000..4492783919b87cb2595c979c58422fe9aa1f7801 --- /dev/null +++ b/pool/shard001/Python/0014381_test_group.py @@ -0,0 +1,57 @@ +import json + +from django.core.urlresolvers import reverse +import requests + +from seahub.group.models import PublicGroup +from seahub.share.models import FileShare +from seahub.test_utils import BaseTestCase + +from tests.common.utils import randstring + +class GroupAddTest(BaseTestCase): + def setUp(self): + self.login_as(self.user) + + def test_can_add(self): + resp = self.client.post(reverse('group_add'), { + 'group_name': 'test_group_%s' % randstring(6) + }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + + assert json.loads(resp.content)['success'] is True + + def test_can_add_with_blank(self): + resp = self.client.post(reverse('group_add'), { + 'group_name': 'test group %s' % randstring(6) + }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + assert json.loads(resp.content)['success'] is True + + def test_can_add_with_hyphen(self): + resp = self.client.post(reverse('group_add'), { + 'group_name': 'test-group-%s' % randstring(6) + }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + assert json.loads(resp.content)['success'] is True + + def test_can_add_with_blank_and_hyphen(self): + resp = self.client.post(reverse('group_add'), { + 'group_name': 'test-group %s' % randstring(6) + }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + assert json.loads(resp.content)['success'] is True + + def test_can_not_add_with_invalid_name(self): + resp = self.client.post(reverse('group_add'), { + 'group_name': 'test*group(name)' + }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') + self.assertEqual(400, resp.status_code) + + +class GroupDiscussTest(BaseTestCase): + def setUp(self): + self.login_as(self.user) + + def tearDown(self): + self.remove_group() + + def test_can_render(self): + resp = self.client.get(reverse('group_discuss', args=[self.group.id])) + self.assertEqual(200, resp.status_code) diff --git a/pool/shard001/Python/0014383_svd.py b/pool/shard001/Python/0014383_svd.py new file mode 100644 index 0000000000000000000000000000000000000000..5f8c0d48b7eb7880c20fe870a0bbc39a6d226998 --- /dev/null +++ b/pool/shard001/Python/0014383_svd.py @@ -0,0 +1,33 @@ + + +import numpy as np +import pandas as pd +from collections import namedtuple + + +def svd(x): + if isinstance(x, pd.DataFrame): + x = x.values + elif isinstance(x, np.ndarray) is False: + x = np.array(x) + + ata = np.dot(np.transpose(x), + x) + + aat = np.dot(x, + np.transpose(x)) + + ata_eig = np.linalg.eig(ata) + v = ata_eig[1] + + s = np.sqrt(ata_eig[0]) + s[::-1].sort() + + aat_eig = np.linalg.eig(aat) + u = aat_eig[1] + + u = u[:, :np.sum(aat_eig[0] > 1e-6)] + + svd_mat = namedtuple('SVD', ['u', 's', 'v']) + + return svd_mat(u=u, s=s, v=np.transpose(v)) diff --git a/pool/shard001/Python/0014386_example.py b/pool/shard001/Python/0014386_example.py new file mode 100644 index 0000000000000000000000000000000000000000..f6bfae608e41cc19d3e5a6da75d1fc83db69ac2b --- /dev/null +++ b/pool/shard001/Python/0014386_example.py @@ -0,0 +1,38 @@ +# Copyright 2016 Milos Svana +# +# 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. + +''' +Simple test script which prints all HTTP responses' URLs and their total +count from a warc file whose path is passed as command line argument. + +Does not support gzipped files. +''' + +from warcreader import WarcFile +from sys import argv +from io import open + +def main(): + filename = argv[1] + with open(filename, 'rb') as raw_warc_file: + warc_file = WarcFile(raw_warc_file) + count = 0 + for webpage in warc_file: + count += 1 + print(webpage.payload) + print('Total count of HTTP responses: %d' % count) + +if __name__ == '__main__': + main() + diff --git a/pool/shard001/Python/0014387_gen_mixer.py b/pool/shard001/Python/0014387_gen_mixer.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb9bbbbd99b4f74561fc3f1f9d20270bab3fe56 --- /dev/null +++ b/pool/shard001/Python/0014387_gen_mixer.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import random +import sys + +FLAG = "flag{MixingOfGoldenBits}" +if len(FLAG) >= 31: + sys.exit("flag too long") + +bits = list(range(256)) +random.shuffle(bits) + +flips = [random.randint(0, 1) for x in range(256)] + +flag = FLAG.ljust(32, '\0') +flag = bytearray(flag) + +output = bytearray(32) + +for i in range(256): + bit = bits[i] % 8 + byte = bits[i] / 8 + b = (flag[byte] >> bit) & 1 + if flips[i]: + b ^= 1 + + bit = i % 8 + byte = i / 8 + output[byte] |= b << bit + + +with open("mixer.c", "w") as f: + f.write("uint8_t mix_bits[] = { ") + f.write(','.join(["%u" % x for x in bits])) + f.write(" };\n") + + f.write("uint8_t mix_flips[] = { ") + f.write(','.join(["%u" % x for x in flips])) + f.write(" };\n") + + f.write("uint8_t flag[] = { ") + f.write(','.join(["%u" % x for x in output])) + f.write(" };\n") + diff --git a/pool/shard001/Python/0014388_hex.py b/pool/shard001/Python/0014388_hex.py new file mode 100644 index 0000000000000000000000000000000000000000..62fd3c74cca67da316fd57c5ebb3593c5fefa0d1 --- /dev/null +++ b/pool/shard001/Python/0014388_hex.py @@ -0,0 +1,46 @@ +from construct.lib.py3compat import byte2int, int2byte, bytes2str + + +# Map an integer in the inclusive range 0-255 to its string byte representation +_printable = dict((i, ".") for i in range(256)) +_printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128)) + + +def hexdump(data, linesize): + """ + data is a bytes object. The returned result is a string. + """ + prettylines = [] + if len(data) < 65536: + fmt = "%%04X %%-%ds %%s" + else: + fmt = "%%08X %%-%ds %%s" + fmt = fmt % (3 * linesize - 1,) + for i in range(0, len(data), linesize): + line = data[i : i + linesize] + hextext = " ".join('%02x' % byte2int(b) for b in line) + rawtext = "".join(_printable[byte2int(b)] for b in line) + prettylines.append(fmt % (i, str(hextext), str(rawtext))) + return prettylines + + +try: + basecls = bytes +except NameError: + basecls = str + +class HexString(basecls): + """ + Represents bytes that will be hex-dumped to a string when its string + representation is requested. + """ + def __init__(self, data, linesize = 16): + self.linesize = linesize + def __new__(cls, data, *args, **kwargs): + return basecls.__new__(cls, data) + def __str__(self): + if not self: + return "''" + return "\n" + "\n".join(hexdump(self, self.linesize)) + + diff --git a/pool/shard001/Python/0014389_fasta.py b/pool/shard001/Python/0014389_fasta.py new file mode 100644 index 0000000000000000000000000000000000000000..35fd41acc4149323e9c7dca7850fbfc36b59067e --- /dev/null +++ b/pool/shard001/Python/0014389_fasta.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python + +import sys +from base import Base + +class Fasta(Base): + ''' + ''' + + def __init__(self, filename = None, shortheader = False, lineCnt = None): + '''shortheader cuts the header to first separator + ''' + self.myfile = filename + self.headers = [] + self.seqs = [] + self.idxs = None + self.totalLen = 0 + if filename != None: + self._read(lineCnt) + if shortheader == True: + self._cutheader() + self._check() + self.idxs = [i for i in xrange(len(self.headers))] + + + def rmGenes(self, geneIds): + ''' + ''' + headers = [] + for header in self.headers: + item = header.split()[0] + headers.append(item) + for item in geneIds: + try: + idx = headers.index(item) + del self.headers[idx] + del self.seqs[idx] + except ValueError: + print >> sys.stderr, "Fasta::rmGenes: could not delete item %s" %item + + def _argsort(self, arr): + ''' + ''' + return sorted(range(len(arr)), key=arr.__getitem__) + + + def order(self, reverse = False): + '''order to length of the ORFs + ''' + lens = [len(self.seqs[i]) for i in xrange(len(self.headers))] + self.idxs = self._argsort(lens) + if reverse == True: + self.idxs = self.idxs[::-1] + #fasta.headers = fasta.headers[idxs] + #fasta.seqs = fasta.seqs[idxs] + #print ">%s" %fasta.headers[idxs[i]] + #print "%s" %fasta.seqs[idxs[i]] + + #lens = [] + #for i in xrange(len(self.headers)): + # lens.append(len(self.seqs[i])) + #lens = array(lens) + #idxs = lens.argsort()[::-1] + #if reverse == True: + # idxs = idxs[::-1] + #headers = array(self.headers) + #seqs = array(self.seqs) + #self.headers = list(headers[idxs]) + #self.seqs = list(seqs[idxs]) + + def header(self, i): + ''' + ''' + return self.headers[self.idxs[i]] + + + def seq(self, i): + ''' + ''' + return self.seqs[self.idxs[i]] + + + def filter(self, headers): + ''' + ''' + newseqs = [] + commons = list(set(self.headers) & set(headers)) + for item in commons: + idx = self.headers.index(item) + newseqs.append(self.seqs[idx]) + self.headers = commons + self.seqs = newseqs + self._check() + #print "Number of headers is %d" %len(commons) + + + def myprint(self): + ''' + ''' + for i in xrange(len(self.headers)): + print '>' + self.headers[self.idxs[i]] + '\n', + print self.seqs[self.idxs[i]] + '\n', + + + def split(self, file1, file2): + '''Split the file in two (every second row) + ''' + h1, h2, s1, s2 = [], [], [], [] + for i in xrange(len(self.headers)): + if i % 2 == 0: + h1.append(self.headers[self.idxs[i]]) + s1.append(self.seqs[self.idxs[i]]) + else: + h2.append(self.headers[self.idxs[i]]) + s2.append(self.seqs[self.idxs[i]]) + self.write(file1, None, h1, s1) + self.write(file2, None, h2, s2) + + + def write(self, filename = None, cnt = None, headers = None, seqs = None): + ''' + ''' + if filename == None: filename = self.myfile + if headers == None: headers = self.headers + if seqs == None: seqs = self.seqs + handle = open(filename, 'w') + for i in xrange(len(headers)): + if cnt != None: + if i >= cnt: break + handle.write('>' + headers[self.idxs[i]] + '\n') + handle.write(seqs[self.idxs[i]] + '\n') + handle.close() + + + def _read(self, lineCnt): + ''' + ''' + handle = self.ropen(self.myfile) + myseq = "" + found = False + cnt = 0 + for line in handle: + line = line.strip() + if len(line) > 0: + if line[0] == '>': + if found == True: + self.seqs.append(myseq) + self.totalLen += len(myseq) + self.headers.append(line[1::]) + myseq = "" + found = True + else: + myseq += line + cnt += 1 + if lineCnt != None and cnt >= lineCnt: break + if found == True: + self.seqs.append(myseq) + self.totalLen += len(myseq) + self.rclose() + + + def _cutheader(self): + ''' + ''' + headers = [] + for item in self.headers: + newheader = item.split()[0] + headers.append(newheader) + self.headers = headers + + + def _check(self): + ''' + ''' + if len(self.headers) != len(self.seqs): + print "Fasta::__init__: number of the headers does not match to the number of the sequences %d vs. %d" %(len(self.headers), len(self.seqs)) + + def getDict(self): + ''' + ''' + myd = {} + for i in xrange(len(self.headers)): myd[self.headers[i]] = self.seqs[i] + return myd + + #def headers(self): + # ''' + # ''' + # return self.headers + # + #def seqs(self): + # ''' + # ''' + # return self.seqs + + diff --git a/pool/shard001/Python/0014391_init__.py b/pool/shard001/Python/0014391_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6598a5f2f528c2d221abcca306b4b874b1022b --- /dev/null +++ b/pool/shard001/Python/0014391_init__.py @@ -0,0 +1,49 @@ +from pyramid.config import Configurator +from pyramid.session import UnencryptedCookieSessionFactoryConfig +from social.apps.pyramid_app.models import init_social +from sqlalchemy import engine_from_config + +from .models import Base +from .models import DBSession +import sys +sys.path.append('../..') + + +def route(config: Configurator): + config.add_static_view('static', 'static', cache_max_age=3600) + config.add_route('index', '/') + config.add_route('login_callback_github', '/login/callback/github') + + +def template_enginge(config: Configurator): + config.include('pyramid_jinja2') + config.add_renderer('.html', 'pyramid_jinja2.renderer_factory') + + +def main(global_config, **settings): + """ This function returns a Pyramid WSGI application. + """ + engine = engine_from_config(settings, 'sqlalchemy.') + DBSession.configure(bind=engine) + Base.metadata.bind = engine + + session_factory = UnencryptedCookieSessionFactoryConfig('thisisasecret') + + config = Configurator(settings=settings, + session_factory=session_factory, + autocommit=True) + + config.add_request_method('.auth.get_user', 'user', reify=True) + + route(config) + + config.include('.config') + config.include('social.apps.pyramid_app') + init_social(config, Base, DBSession) + + config.scan() + config.scan('social.apps.pyramid_app') + + template_enginge(config) + + return config.make_wsgi_app() diff --git a/pool/shard001/Python/0014392_test_namespace_manager.py b/pool/shard001/Python/0014392_test_namespace_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..62fb36307a43efad41941129a87d9947a5713792 --- /dev/null +++ b/pool/shard001/Python/0014392_test_namespace_manager.py @@ -0,0 +1,114 @@ +# Copyright (c) 2015 Rackspace +# 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 mock +from oslo_utils import uuidutils + +from neutron.agent.l3 import dvr_fip_ns +from neutron.agent.l3 import dvr_snat_ns +from neutron.agent.l3 import namespace_manager +from neutron.agent.l3 import namespaces +from neutron.agent.linux import ip_lib +from neutron.tests import base + +_uuid = uuidutils.generate_uuid + + +class NamespaceManagerTestCaseFramework(base.BaseTestCase): + + def _create_namespace_manager(self): + self.agent_conf = mock.Mock() + self.driver = mock.Mock() + return namespace_manager.NamespaceManager(self.agent_conf, self.driver) + + +class TestNamespaceManager(NamespaceManagerTestCaseFramework): + + def setUp(self): + super(TestNamespaceManager, self).setUp() + self.ns_manager = self._create_namespace_manager() + + def test_get_prefix_and_id(self): + router_id = _uuid() + + ns_prefix, ns_id = self.ns_manager.get_prefix_and_id( + namespaces.NS_PREFIX + router_id) + self.assertEqual(namespaces.NS_PREFIX, ns_prefix) + self.assertEqual(router_id, ns_id) + + ns_prefix, ns_id = self.ns_manager.get_prefix_and_id( + dvr_snat_ns.SNAT_NS_PREFIX + router_id) + self.assertEqual(dvr_snat_ns.SNAT_NS_PREFIX, ns_prefix) + self.assertEqual(router_id, ns_id) + + ns_name = 'dhcp-' + router_id + self.assertIsNone(self.ns_manager.get_prefix_and_id(ns_name)) + + def test_is_managed(self): + router_id = _uuid() + + router_ns_name = namespaces.NS_PREFIX + router_id + self.assertTrue(self.ns_manager.is_managed(router_ns_name)) + router_ns_name = dvr_snat_ns.SNAT_NS_PREFIX + router_id + self.assertTrue(self.ns_manager.is_managed(router_ns_name)) + + ext_net_id = _uuid() + router_ns_name = dvr_fip_ns.FIP_NS_PREFIX + ext_net_id + self.assertTrue(self.ns_manager.is_managed(router_ns_name)) + + self.assertFalse(self.ns_manager.is_managed('dhcp-' + router_id)) + + def test_list_all(self): + ns_names = [namespaces.NS_PREFIX + _uuid(), + dvr_snat_ns.SNAT_NS_PREFIX + _uuid(), + dvr_fip_ns.FIP_NS_PREFIX + _uuid(), + 'dhcp-' + _uuid(), ] + + # Test the normal path + with mock.patch.object(ip_lib, 'list_network_namespaces', + return_value=ns_names): + retrieved_ns_names = self.ns_manager.list_all() + self.assertEqual(len(ns_names) - 1, len(retrieved_ns_names)) + for i in range(len(retrieved_ns_names)): + self.assertIn(ns_names[i], retrieved_ns_names) + self.assertNotIn(ns_names[-1], retrieved_ns_names) + + # Test path where list_network_namespaces() raises exception + with mock.patch.object(ip_lib, 'list_network_namespaces', + side_effect=RuntimeError): + retrieved_ns_names = self.ns_manager.list_all() + self.assertFalse(retrieved_ns_names) + + def test_ensure_snat_cleanup(self): + router_id = _uuid() + with mock.patch.object(self.ns_manager, '_cleanup') as mock_cleanup: + self.ns_manager.ensure_snat_cleanup(router_id) + mock_cleanup.assert_called_once_with(dvr_snat_ns.SNAT_NS_PREFIX, + router_id) + + def test_ensure_router_cleanup(self): + router_id = _uuid() + ns_names = [namespaces.NS_PREFIX + _uuid() for _ in range(5)] + ns_names += [dvr_snat_ns.SNAT_NS_PREFIX + _uuid() for _ in range(5)] + ns_names += [namespaces.NS_PREFIX + router_id, + dvr_snat_ns.SNAT_NS_PREFIX + router_id] + with mock.patch.object(ip_lib, 'list_network_namespaces', + return_value=ns_names), \ + mock.patch.object(self.ns_manager, '_cleanup') as mock_cleanup: + self.ns_manager.ensure_router_cleanup(router_id) + expected = [mock.call(namespaces.NS_PREFIX, router_id), + mock.call(dvr_snat_ns.SNAT_NS_PREFIX, router_id)] + mock_cleanup.assert_has_calls(expected, any_order=True) + self.assertEqual(2, mock_cleanup.call_count) diff --git a/pool/shard001/Python/0014395_pyp_multinomial.py b/pool/shard001/Python/0014395_pyp_multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..cfeadccea82ff0b5a292bc2ca8a77f237a663632 --- /dev/null +++ b/pool/shard001/Python/0014395_pyp_multinomial.py @@ -0,0 +1,87 @@ +import textwrap + +import numpy as np +from scipy.special import gammaln as lgamma + +import pystb + + +def falling_factorial(x, n): + return lgamma(x + 1) - lgamma(x - n + 1) + + +def rising_factorial(x, n): + return lgamma(x + n) - lgamma(x) + + +def log_prob_t_propto(t_k, n_k, alpha, theta_k, stable): + assert alpha > 0 + assert 0 <= t_k <= n_k + if n_k == 0: + assert t_k == n_k + return stable[n_k, t_k] + t_k * np.log(alpha * theta_k) + + +def sample_t(n, alpha, theta, stable): + t = np.empty_like(n, dtype=int) + for j in range(len(n)): + if n[j] == 0: + t[j] = 0 + continue + log_prob = np.array([log_prob_t_propto(s, n[j], alpha, theta[j], stable) for s in range(1, n[j] + 1)]) + prob = np.exp(log_prob - max(log_prob)) + prob /= prob.sum() + # zero probability of 0 if n_k > 0, so add 1 + t[j] = 1 + np.random.multinomial(1, prob).argmax() + return t + + +def sample_theta(t, eta): + """Sample theta from full condition. + + Default prior on theta is Dirichlet(eta * 1/K) + """ + return np.random.dirichlet(t + eta * (1.0 / len(t))) + + +def run(): + p_true = np.array([0.1, 0.1, 0.6, 0.05, 0.05, 0.05, 0.05, 0, 0]) + x = (100 * np.ones(len(p_true)) * p_true).astype(int) + K = len(x) + + print("true p:\n", p_true) + print(textwrap.dedent(r""" + Dirichlet-Multinomial with alpha,theta Dirichlet parameterization. + alpha = 1.0, theta = 1/K + Posterior for p: + """)) + alpha = 1.0 + dirichlet_post = x + alpha * (1.0 / K) + dirichlet_post = dirichlet_post / dirichlet_post.sum() + print(dirichlet_post.round(3)) + + print(textwrap.dedent(r""" + PYP-Multinomial, alpha = 1.0, theta has Dirichlet hyperprior + Dirichlet hyperprior has params \alpha^\prime = 1.0, \theta^\prime = 1/K + Posterior mean for p: + """)) + # integrate over samples of theta, posterior of PYP(0, 1, theta) is theta + num_samples = 10000 + samples = np.empty((num_samples, K)) + + t = np.zeros_like(x, dtype=int) + + # initial theta + theta = x / np.sum(x) + stable = pystb.STable(1e5, 1e5, 0) + alpha = 1.0 + + for i in range(num_samples): + t = sample_t(x, alpha, theta, stable) + theta = sample_theta(t, eta=1.0) + samples[i] = theta + print(np.mean(samples, axis=0).round(3)) + + +if __name__ == '__main__': + run() diff --git a/pool/shard001/Python/0014396_5_microsoft_FaceAPI.py b/pool/shard001/Python/0014396_5_microsoft_FaceAPI.py new file mode 100644 index 0000000000000000000000000000000000000000..b27b57b58d6ee93b24e1d01212ae0bfa611e31e2 --- /dev/null +++ b/pool/shard001/Python/0014396_5_microsoft_FaceAPI.py @@ -0,0 +1,59 @@ +''' +Based on exmaple code provided my microsoft + +''' + +import http.client, urllib.request, urllib.parse, urllib.error +import glob, time, json, sys + +headers = { + # Request headers + 'Content-Type': 'application/octet-stream', # for using local files + 'Ocp-Apim-Subscription-Key': ' ', # put your own Key here +} + +params = urllib.parse.urlencode({ + # Request parameters + 'subscription-key': " ", + 'returnFaceId': 'true', + 'returnFaceLandmarks': 'false', + 'returnFaceAttributes': 'age,smile,emotion,gender', +}) + +def make_json(candidate): + body = "" + + #candidate = 'donald_trump' + #image_filename = file_dir + '0_' + candidate + '.jpg' + + file_dir = './' + candidate + "_image_universe/" + output_dir = 'MicrosoftAPI_jsons/' + + #load image + for image_filename in glob.glob(file_dir + '*.jpg'): + print(image_filename) + + with open(image_filename, 'rb') as f: + print(f) + body = f.read() + + try: + conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com') + conn.request("POST", "/face/v1.0/detect?%s" % params, body, headers) + response = conn.getresponse() + data = response.read() + data = data.decode('utf-8') + print(data) + conn.close() + except Exception as e: + print(e.args) + + output_file = image_filename.split('/')[2] + output_file = output_file.split('.')[0] + print(output_file) + with open(output_dir + output_file + '.json', 'w', encoding='utf-8') as fp: + json.dump(data, fp) + + time.sleep(2) + +make_json('hillary_clinton' ) diff --git a/pool/shard001/Python/0014402_switchable.py b/pool/shard001/Python/0014402_switchable.py new file mode 100644 index 0000000000000000000000000000000000000000..7af153ba5a90900d0fec6d7dec31d9a0e6209ccc --- /dev/null +++ b/pool/shard001/Python/0014402_switchable.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +import unittest +from testconfig import config +from src.gsmconnectionmanager import GSMConnectionManager + +class SwitchableTest(unittest.TestCase): + """ + Test with MonetDB/PostgreSQL switch using 'testconfig'. + """ + def setUp(self): + """ + """ + if ('monetdb' in config): + self.cm = GSMConnectionManager( + use_monet=bool(config['monetdb'] == 'True'), + use_console=False) + self.is_monet = bool(config['monetdb'] == 'True') + else: + self.cm = GSMConnectionManager(use_console=False, use_monet=True) + self.is_monet = True diff --git a/pool/shard001/Python/0014408_warmup.py b/pool/shard001/Python/0014408_warmup.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec2e7089a811d91abc30d07a14a3fc5eb6ae501 --- /dev/null +++ b/pool/shard001/Python/0014408_warmup.py @@ -0,0 +1,75 @@ +# Copyright (C) 2012,2013 +# Max Planck Institute for Polymer Research +# Copyright (C) 2008,2009,2010,2011 +# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI +# +# This file is part of ESPResSo++. +# +# ESPResSo++ is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# ESPResSo++ is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +""" +*************************************** +**warmup** - method to warm up a system +*************************************** + +This method does a warm up for a system with a density of 0.85. + +The method needs the following parameters: + +* system, integrator + ESPResSo system which schoul be warmed up and the correspondig integrator e.g.: + >>>system, integrator = espressopp.standard_system.LennardJones(100,(10,10,10)) +*number + number of steps of the warm up + =80 + for a system with a desnsity of 0.85, if it explodes try a higher number +""" +import espressopp +from espressopp import Real3D + +def warmup(system, integrator, number=80): + + print "starting warmup" + + org_dt = integrator.dt + pot = system.getInteraction(0).clonePotential(0,0) + final_sigma = pot.sigma + final_epsilon = pot.epsilon + N = 50 + + integrator.dt = 0.0001 + force_capping = espressopp.integrator.CapForce(system, 0.0) + integrator.addExtension(force_capping) + + for k in range(11,number): + force_capping.setAbsCapForce(1000000.0/number*k) + pot.sigma = final_sigma/number*k + pot.epsilon = final_epsilon/number*k + system.getInteraction(0).setPotential(0,0,pot) + espressopp.tools.analyse.info(system, integrator) + integrator.run(N) + + integrator.dt = org_dt + pot.sigma = final_sigma + pot.epsilon = final_epsilon + force_capping.disconnect() + + for k in range(11): + integrator.run(70) + espressopp.tools.analyse.info(system, integrator) + + integrator.step = 0 + + print "warmup finished" diff --git a/pool/shard001/Python/0014410_core.py b/pool/shard001/Python/0014410_core.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd654da0aa442eec4552b654011830677cefcf5 --- /dev/null +++ b/pool/shard001/Python/0014410_core.py @@ -0,0 +1,86 @@ +from __future__ import unicode_literals +import os + +from flask import Flask + +from simple_chat.models.model_factory import ModelFactory + +app = Flask(__name__, '/static') +app.config.from_object('simple_chat.default_settings') + + + +key = 'SIMPLE_CHAT_SETTINGS' +if key in os.environ: + app.logger.info('Load configuration from %s=%s', key, os.environ[key]) + app.config.from_envvar(key) + + +def setup_logging(): + """Setup logging configuration + + """ + import logging.config + import yaml + + log_path = 'logging.yaml' + if os.path.exists(log_path): + config = yaml.load(open(log_path, 'rt')) + logging.config.dictConfig(config) + else: + if not app.config['DEBUG']: + logging.basicConfig(level=logging.INFO) + else: + logging.basicConfig(level=logging.DEBUG) + + +def load_deps(): + """Load dependencies + + """ + from simple_chat.views.api import api + app.register_module(api) + + +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) + +app.wsgi_app = ReverseProxied(app.wsgi_app) + + +if __name__ == '__main__': + import logging + logging.basicConfig(level=logging.DEBUG) + setup_logging() + load_deps() + app.run() \ No newline at end of file diff --git a/pool/shard001/Python/0014411_formfields.py b/pool/shard001/Python/0014411_formfields.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0cea2f52dc46ca476868b2593b79f5d8d7732f --- /dev/null +++ b/pool/shard001/Python/0014411_formfields.py @@ -0,0 +1,46 @@ +from django.models.auth import users +from django.core import formfields, validators + +class AuthenticationForm(formfields.Manipulator): + """ + Base class for authenticating users. Extend this to get a form that accepts + username/password logins. + """ + def __init__(self, request=None): + """ + If request is passed in, the manipulator will validate that cookies are + enabled. Note that the request (a HttpRequest object) must have set a + cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before + running this validator. + """ + self.request = request + self.fields = [ + formfields.TextField(field_name="username", length=15, maxlength=30, is_required=True, + validator_list=[self.isValidUser, self.hasCookiesEnabled]), + formfields.PasswordField(field_name="password", length=15, maxlength=30, is_required=True, + validator_list=[self.isValidPasswordForUser]), + ] + self.user_cache = None + + def hasCookiesEnabled(self, field_data, all_data): + if self.request and not self.request.session.test_cookie_worked(): + raise validators.ValidationError, "Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in." + + def isValidUser(self, field_data, all_data): + try: + self.user_cache = users.get_object(username__exact=field_data) + except users.UserDoesNotExist: + raise validators.ValidationError, "Please enter a correct username and password. Note that both fields are case-sensitive." + + def isValidPasswordForUser(self, field_data, all_data): + if self.user_cache is not None and not self.user_cache.check_password(field_data): + self.user_cache = None + raise validators.ValidationError, "Please enter a correct username and password. Note that both fields are case-sensitive." + + def get_user_id(self): + if self.user_cache: + return self.user_cache.id + return None + + def get_user(self): + return self.user_cache diff --git a/pool/shard001/Python/0014415_test_conversion.py b/pool/shard001/Python/0014415_test_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef0238871c6fb0960e5f947dc222c79b53d7542 --- /dev/null +++ b/pool/shard001/Python/0014415_test_conversion.py @@ -0,0 +1,108 @@ +# Python 2/3 compatibility +# pylint: disable=wildcard-import,unused-wildcard-import,wrong-import-order,wrong-import-position +from __future__ import (absolute_import, division, print_function, unicode_literals) +from future.builtins import * +from future.builtins.disabled import * +from future.standard_library import install_aliases +install_aliases() +# pylint: enable=wildcard-import,unused-wildcard-import,wrong-import-order,wrong-import-position + +import os +import shutil + +import arcpy +import pytest + +import arcpyext + +from pathlib2 import Path + +OUTPUT_DIR = Path(__file__).parent.joinpath("output") +TEST_INPUT_GDB_PATH = Path(__file__).parent.joinpath("input/conversion.gdb") +TEST_INPUT_COPY_GDB_PATH = Path(__file__).parent.joinpath("input/conversion.copy.gdb") +TEST_OUTPUT_PATH = Path(__file__).parent.joinpath("output") + + +def setup_module(module): + """ setup any state specific to the execution of the given module.""" + + if OUTPUT_DIR.exists(): + shutil.rmtree(str(OUTPUT_DIR)) + + os.makedirs(str(OUTPUT_DIR)) + + +@pytest.yield_fixture(scope="function") +def in_workspace(): + # copy, yield, and delete in order to test for Arc locking files + shutil.copytree(str(TEST_INPUT_GDB_PATH), str(TEST_INPUT_COPY_GDB_PATH)) + yield TEST_INPUT_COPY_GDB_PATH + shutil.rmtree(str(TEST_INPUT_COPY_GDB_PATH)) + + +@pytest.mark.parametrize(("output_path"), [(TEST_OUTPUT_PATH.joinpath("csv"))]) +def test_convert_csv(in_workspace, output_path): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_csv.workspace(in_workspace_str, output_path_str) + assert output_path.exists() + + # check KML/KMZ exists + assert any(child.suffix.lower() in [".csv"] for child in output_path.iterdir()) + + +@pytest.mark.parametrize(("output_path", "version"), [(TEST_OUTPUT_PATH.joinpath("gpkg_default\\output.gpkg"), None), + (TEST_OUTPUT_PATH.joinpath("gpkg_1.0\\output.gpkg"), 1.0), + (TEST_OUTPUT_PATH.joinpath("gpkg_1.1\\output.gpkg"), 1.1), + (TEST_OUTPUT_PATH.joinpath("gpkg_1.2\\output.gpkg"), 1.2)]) +def test_convert_geopackage(in_workspace, output_path, version): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_geopackage.workspace(in_workspace_str, output_path_str, version=version) + assert output_path.exists() + output_path.unlink() + assert not output_path.exists() + + +@pytest.mark.parametrize(("output_path"), [(TEST_OUTPUT_PATH.joinpath("kml"))]) +def test_convert_kml(in_workspace, output_path): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_kml.workspace(in_workspace_str, output_path_str) + assert output_path.exists() + + # check KML/KMZ exists + assert any(child.suffix.lower() in [".kml", ".kmz"] for child in output_path.iterdir()) + + +@pytest.mark.parametrize(("output_path"), [(TEST_OUTPUT_PATH.joinpath("mapinfo"))]) +def test_convert_mapinfo_tab(in_workspace, output_path): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_mapinfo_tab.workspace(in_workspace_str, output_path_str) + assert output_path.exists() + + # check MapInfo tab file exists + assert any(child.suffix.lower() in [".tab"] for child in output_path.iterdir()) + + +@pytest.mark.parametrize(("output_path"), [(TEST_OUTPUT_PATH.joinpath("shp"))]) +def test_convert_shapefile(in_workspace, output_path): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_shapefile.workspace(in_workspace_str, output_path_str) + assert output_path.exists() + + # check Shapefile exists + assert any(child.suffix.lower() in [".shp"] for child in output_path.iterdir()) + + +@pytest.mark.parametrize(("output_path"), [(TEST_OUTPUT_PATH.joinpath("xlsx\\output.xlsx"))]) +def test_convert_ooxml_workbook(in_workspace, output_path): + in_workspace_str = str(in_workspace) + output_path_str = str(output_path) + arcpyext.conversion.to_ooxml_workbook.workspace(in_workspace_str, output_path_str) + assert output_path.exists() + + # check OOXML Workbook exists + assert any(child.suffix.lower() in [".xlsx"] for child in output_path.parent.iterdir()) \ No newline at end of file diff --git a/pool/shard001/Python/0014416_grep.py b/pool/shard001/Python/0014416_grep.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc8f9f61890249530c131abb48be2bf37b6a3ad --- /dev/null +++ b/pool/shard001/Python/0014416_grep.py @@ -0,0 +1,242 @@ +# +# Copyright (C) 2009 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +from color import Coloring +from command import PagedCommand +from git_command import git_require, GitCommand + +class GrepColoring(Coloring): + def __init__(self, config): + Coloring.__init__(self, config, 'grep') + self.project = self.printer('project', attr='bold') + +class Grep(PagedCommand): + common = True + helpSummary = "Print lines matching a pattern" + helpUsage = """ +%prog {pattern | -e pattern} [...] +""" + helpDescription = """ +Search for the specified patterns in all project files. + +Boolean Options +--------------- + +The following options can appear as often as necessary to express +the pattern to locate: + + -e PATTERN + --and, --or, --not, -(, -) + +Further, the -r/--revision option may be specified multiple times +in order to scan multiple trees. If the same file matches in more +than one tree, only the first result is reported, prefixed by the +revision name it was found under. + +Examples +------- + +Look for a line that has '#define' and either 'MAX_PATH or 'PATH_MAX': + + repo grep -e '#define' --and -\( -e MAX_PATH -e PATH_MAX \) + +Look for a line that has 'NODE' or 'Unexpected' in files that +contain a line that matches both expressions: + + repo grep --all-match -e NODE -e Unexpected + +""" + + def _Options(self, p): + def carry(option, + opt_str, + value, + parser): + pt = getattr(parser.values, 'cmd_argv', None) + if pt is None: + pt = [] + setattr(parser.values, 'cmd_argv', pt) + + if opt_str == '-(': + pt.append('(') + elif opt_str == '-)': + pt.append(')') + else: + pt.append(opt_str) + + if value is not None: + pt.append(value) + + g = p.add_option_group('Sources') + g.add_option('--cached', + action='callback', callback=carry, + help='Search the index, instead of the work tree') + g.add_option('-r','--revision', + dest='revision', action='append', metavar='TREEish', + help='Search TREEish, instead of the work tree') + + g = p.add_option_group('Pattern') + g.add_option('-e', + action='callback', callback=carry, + metavar='PATTERN', type='str', + help='Pattern to search for') + g.add_option('-i', '--ignore-case', + action='callback', callback=carry, + help='Ignore case differences') + g.add_option('-a','--text', + action='callback', callback=carry, + help="Process binary files as if they were text") + g.add_option('-I', + action='callback', callback=carry, + help="Don't match the pattern in binary files") + g.add_option('-w', '--word-regexp', + action='callback', callback=carry, + help='Match the pattern only at word boundaries') + g.add_option('-v', '--invert-match', + action='callback', callback=carry, + help='Select non-matching lines') + g.add_option('-G', '--basic-regexp', + action='callback', callback=carry, + help='Use POSIX basic regexp for patterns (default)') + g.add_option('-E', '--extended-regexp', + action='callback', callback=carry, + help='Use POSIX extended regexp for patterns') + g.add_option('-F', '--fixed-strings', + action='callback', callback=carry, + help='Use fixed strings (not regexp) for pattern') + + g = p.add_option_group('Pattern Grouping') + g.add_option('--all-match', + action='callback', callback=carry, + help='Limit match to lines that have all patterns') + g.add_option('--and', '--or', '--not', + action='callback', callback=carry, + help='Boolean operators to combine patterns') + g.add_option('-(','-)', + action='callback', callback=carry, + help='Boolean operator grouping') + + g = p.add_option_group('Output') + g.add_option('-n', + action='callback', callback=carry, + help='Prefix the line number to matching lines') + g.add_option('-C', + action='callback', callback=carry, + metavar='CONTEXT', type='str', + help='Show CONTEXT lines around match') + g.add_option('-B', + action='callback', callback=carry, + metavar='CONTEXT', type='str', + help='Show CONTEXT lines before match') + g.add_option('-A', + action='callback', callback=carry, + metavar='CONTEXT', type='str', + help='Show CONTEXT lines after match') + g.add_option('-l','--name-only','--files-with-matches', + action='callback', callback=carry, + help='Show only file names containing matching lines') + g.add_option('-L','--files-without-match', + action='callback', callback=carry, + help='Show only file names not containing matching lines') + + + def Execute(self, opt, args): + out = GrepColoring(self.manifest.manifestProject.config) + + cmd_argv = ['grep'] + if out.is_on and git_require((1,6,3)): + cmd_argv.append('--color') + cmd_argv.extend(getattr(opt,'cmd_argv',[])) + + if '-e' not in cmd_argv: + if not args: + self.Usage() + cmd_argv.append('-e') + cmd_argv.append(args[0]) + args = args[1:] + + projects = self.GetProjects(args) + + full_name = False + if len(projects) > 1: + cmd_argv.append('--full-name') + full_name = True + + have_rev = False + if opt.revision: + if '--cached' in cmd_argv: + print >>sys.stderr,\ + 'fatal: cannot combine --cached and --revision' + sys.exit(1) + have_rev = True + cmd_argv.extend(opt.revision) + cmd_argv.append('--') + + bad_rev = False + have_match = False + + for project in projects: + p = GitCommand(project, + cmd_argv, + bare = False, + capture_stdout = True, + capture_stderr = True) + if p.Wait() != 0: + # no results + # + if p.stderr: + if have_rev and 'fatal: ambiguous argument' in p.stderr: + bad_rev = True + else: + out.project('--- project %s ---' % project.relpath) + out.nl() + out.write("%s", p.stderr) + out.nl() + continue + have_match = True + + # We cut the last element, to avoid a blank line. + # + r = p.stdout.split('\n') + r = r[0:-1] + + if have_rev and full_name: + for line in r: + rev, line = line.split(':', 1) + out.write("%s", rev) + out.write(':') + out.project(project.relpath) + out.write('/') + out.write("%s", line) + out.nl() + elif full_name: + for line in r: + out.project(project.relpath) + out.write('/') + out.write("%s", line) + out.nl() + else: + for line in r: + print line + + if have_match: + sys.exit(0) + elif have_rev and bad_rev: + for r in opt.revision: + print >>sys.stderr, "error: can't search revision %s" % r + sys.exit(1) + else: + sys.exit(1) diff --git a/pool/shard001/Python/0014417_proppatch.py b/pool/shard001/Python/0014417_proppatch.py new file mode 100644 index 0000000000000000000000000000000000000000..80e988d149d181150a82af33e649ea82b1b6ee4e --- /dev/null +++ b/pool/shard001/Python/0014417_proppatch.py @@ -0,0 +1,206 @@ +# -*- test-case-name: txweb2.dav.test.test_prop.PROP.test_PROPPATCH -*- +## +# Copyright (c) 2005-2017 Apple Inc. All rights reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# +# DRI: Wilfredo Sanchez, wsanchez@apple.com +## + +""" +WebDAV-aware static resources. +""" + +__all__ = ["http_PROPPATCH"] + +from twisted.python.failure import Failure +from twisted.internet.defer import deferredGenerator, waitForDeferred + +from twext.python.log import Logger +from txweb2 import responsecode +from txweb2.http import HTTPError, StatusResponse +from txdav.xml import element as davxml +from txweb2.dav.http import MultiStatusResponse, PropertyStatusResponseQueue +from txweb2.dav.util import davXMLFromStream + +log = Logger() + + +def http_PROPPATCH(self, request): + """ + Respond to a PROPPATCH request. (RFC 2518, section 8.2) + """ + if not self.exists(): + log.error("File not found: %s" % (self,)) + raise HTTPError(responsecode.NOT_FOUND) + + x = waitForDeferred(self.authorize(request, (davxml.WriteProperties(),))) + yield x + x.getResult() + + # + # Read request body + # + try: + doc = waitForDeferred(davXMLFromStream(request.stream)) + yield doc + doc = doc.getResult() + except ValueError, e: + log.error("Error while handling PROPPATCH body: %s" % (e,)) + raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e))) + + if doc is None: + error = "Request XML body is required." + log.error("Error: {err}", error) + raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, error)) + + # + # Parse request + # + update = doc.root_element + if not isinstance(update, davxml.PropertyUpdate): + error = ("Request XML body must be a propertyupdate element." + % (davxml.PropertyUpdate.sname(),)) + log.error("Error: {err}", error) + raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, error)) + + responses = PropertyStatusResponseQueue("PROPPATCH", request.uri, responsecode.NO_CONTENT) + undoActions = [] + gotError = False + + # Look for Prefer header + prefer = request.headers.getHeader("prefer", {}) + returnMinimal = any([key == "return" and value == "minimal" for key, value, _ignore_args in prefer]) + + try: + # + # Update properties + # + for setOrRemove in update.children: + assert len(setOrRemove.children) == 1 + + container = setOrRemove.children[0] + + assert isinstance(container, davxml.PropertyContainer) + + properties = container.children + + def do(action, property, removing=False): + """ + Perform action(property, request) while maintaining an + undo queue. + """ + has = waitForDeferred(self.hasProperty(property, request)) + yield has + has = has.getResult() + + if has: + oldProperty = waitForDeferred(self.readProperty(property, request)) + yield oldProperty + oldProperty = oldProperty.getResult() + + def undo(): + return self.writeProperty(oldProperty, request) + else: + def undo(): + return self.removeProperty(property, request) + + try: + x = waitForDeferred(action(property, request)) + yield x + x.getResult() + except KeyError, e: + # Removing a non-existent property is OK according to WebDAV + if removing: + responses.add(responsecode.OK, property) + yield True + return + else: + # Convert KeyError exception into HTTPError + responses.add( + Failure(exc_value=HTTPError(StatusResponse(responsecode.FORBIDDEN, str(e)))), + property + ) + yield False + return + except: + responses.add(Failure(), property) + yield False + return + else: + responses.add(responsecode.OK, property) + + # Only add undo action for those that succeed because those that fail will not have changed + undoActions.append(undo) + + yield True + return + + do = deferredGenerator(do) + + if isinstance(setOrRemove, davxml.Set): + for property in properties: + ok = waitForDeferred(do(self.writeProperty, property)) + yield ok + ok = ok.getResult() + if not ok: + gotError = True + elif isinstance(setOrRemove, davxml.Remove): + for property in properties: + ok = waitForDeferred(do(self.removeProperty, property, True)) + yield ok + ok = ok.getResult() + if not ok: + gotError = True + else: + raise AssertionError("Unknown child of PropertyUpdate: %s" % (setOrRemove,)) + except: + # + # If there is an error, we have to back out whatever we have + # operations we have done because PROPPATCH is an + # all-or-nothing request. + # We handle the first one here, and then re-raise to handle the + # rest in the containing scope. + # + for action in undoActions: + x = waitForDeferred(action()) + yield x + x.getResult() + raise + + # + # If we had an error we need to undo any changes that did succeed and change status of + # those to 424 Failed Dependency. + # + if gotError: + for action in undoActions: + x = waitForDeferred(action()) + yield x + x.getResult() + responses.error() + + # + # Return response - use 200 if Prefer:return=minimal set and no errors + # + if returnMinimal and not gotError: + yield responsecode.OK + else: + yield MultiStatusResponse([responses.response()]) + +http_PROPPATCH = deferredGenerator(http_PROPPATCH) diff --git a/pool/shard001/Python/0014419_addressbook_pb2.py b/pool/shard001/Python/0014419_addressbook_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c602b84805daa14cc5566ca08756f621bc5753df --- /dev/null +++ b/pool/shard001/Python/0014419_addressbook_pb2.py @@ -0,0 +1,149 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! + +from google.protobuf import descriptor +from google.protobuf import message +from google.protobuf import reflection +from google.protobuf import service +from google.protobuf import service_reflection +from google.protobuf import descriptor_pb2 + + +_PERSON_PHONETYPE = descriptor.EnumDescriptor( + name='PhoneType', + full_name='tutorial.Person.PhoneType', + filename='PhoneType', + values=[ + descriptor.EnumValueDescriptor( + name='MOBILE', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='HOME', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='WORK', index=2, number=2, + options=None, + type=None), + ], + options=None, +) + + +_PERSON_PHONENUMBER = descriptor.Descriptor( + name='PhoneNumber', + full_name='tutorial.Person.PhoneNumber', + filename='addressbook.proto', + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='number', full_name='tutorial.Person.PhoneNumber.number', index=0, + number=1, type=9, cpp_type=9, label=2, + default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='type', full_name='tutorial.Person.PhoneNumber.type', index=1, + number=2, type=14, cpp_type=8, label=1, + default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], # TODO(robinson): Implement. + enum_types=[ + ], + options=None) + +_PERSON = descriptor.Descriptor( + name='Person', + full_name='tutorial.Person', + filename='addressbook.proto', + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='name', full_name='tutorial.Person.name', index=0, + number=1, type=9, cpp_type=9, label=2, + default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='id', full_name='tutorial.Person.id', index=1, + number=2, type=5, cpp_type=1, label=2, + default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='email', full_name='tutorial.Person.email', index=2, + number=3, type=9, cpp_type=9, label=1, + default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='phone', full_name='tutorial.Person.phone', index=3, + number=4, type=11, cpp_type=10, label=3, + default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='awesome', full_name='tutorial.Person.awesome', index=4, + number=5, type=8, cpp_type=7, label=2, + default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], # TODO(robinson): Implement. + enum_types=[ + _PERSON_PHONETYPE, + ], + options=None) + + +_ADDRESSBOOK = descriptor.Descriptor( + name='AddressBook', + full_name='tutorial.AddressBook', + filename='addressbook.proto', + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='person', full_name='tutorial.AddressBook.person', index=0, + number=1, type=11, cpp_type=10, label=3, + default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], # TODO(robinson): Implement. + enum_types=[ + ], + options=None) + + +_PERSON_PHONENUMBER.fields_by_name['type'].enum_type = _PERSON_PHONETYPE +_PERSON.fields_by_name['phone'].message_type = _PERSON_PHONENUMBER +_ADDRESSBOOK.fields_by_name['person'].message_type = _PERSON + +class Person(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + + class PhoneNumber(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PERSON_PHONENUMBER + DESCRIPTOR = _PERSON + +class AddressBook(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ADDRESSBOOK + diff --git a/pool/shard001/Python/0014425_package.py b/pool/shard001/Python/0014425_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0312b874f06d33f3f468cc6225570e191dc60059 --- /dev/null +++ b/pool/shard001/Python/0014425_package.py @@ -0,0 +1,43 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License (as +# published by the Free Software Foundation) version 2.1, February 1999. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and +# conditions of the GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class MsgpackC(CMakePackage): + """A small, fast binary interchange format convertible to/from JSON""" + homepage = "http://www.msgpack.org" + url = "https://github.com/msgpack/msgpack-c/archive/cpp-3.0.1.tar.gz" + + version('3.0.1', 'a79f05f0dc5637c161805d6c0e9bfbe7') + version('1.4.1', 'e2fd3a7419b9bc49e5017fdbefab87e0') + + depends_on('cmake@2.8.12:', type='build') + + def cmake_args(self): + args = [ + "-DCMAKE_CXX_FLAGS=-Wno-implicit-fallthrough", + "-DCMAKE_C_FLAGS=-Wno-implicit-fallthrough" + ] + return args diff --git a/pool/shard001/Python/0014426_WhenElement.py b/pool/shard001/Python/0014426_WhenElement.py new file mode 100644 index 0000000000000000000000000000000000000000..d69f32386498ee642a9c495772cdd42e64fd26fd --- /dev/null +++ b/pool/shard001/Python/0014426_WhenElement.py @@ -0,0 +1,71 @@ +######################################################################## +# +# File Name: WhenElement.py +# +# +""" +Implementation of the XSLT Spec if instruction +WWW: http://4suite.com/4XSLT e-mail: support@4suite.com + +Copyright (c) 1999-2000 Fourthought Inc, USA. All Rights Reserved. +See http://4suite.com/COPYRIGHT for license and copyright information +""" + +from xml.dom import EMPTY_NAMESPACE +import xml.dom.ext +import xml.dom.Element +import xml.xslt +from xml.xslt import XsltElement, XsltException, Error +from xml.xpath import CoreFunctions, Conversions +from xml.xpath import XPathParser + +class WhenElement(XsltElement): + legalAttrs = ('test',) + + def __init__(self, doc, uri=xml.xslt.XSL_NAMESPACE, localName='when', prefix='xsl', baseUri=''): + XsltElement.__init__(self, doc, uri, localName, prefix, baseUri) + + def setup(self): + self.__dict__['_test'] = self.getAttributeNS(EMPTY_NAMESPACE, 'test') + if not self._test: + raise XsltException(Error.WHEN_MISSING_TEST) + self.__dict__['_nss'] = xml.dom.ext.GetAllNs(self) + parser = XPathParser.XPathParser() + self.__dict__['_expr'] = parser.parseExpression(self._test) + return + + def instantiate(self, context, processor, new_level=1): + + origState = context.copyNamespaces() + context.setNamespaces(self._nss) + + rec_tpl_params = None + result = self._expr.evaluate(context) + test = Conversions.BooleanValue(result) + if int(test): + for child in self.childNodes: + if child.namespaceURI == xml.xslt.XSL_NAMESPACE and child.localName in ['call-template', 'if', 'choose']: + context, rec_tpl_params = child.instantiate(context, processor, new_level) + else: + context = child.instantiate(context, processor)[0] + + context.setNamespaces(origState) + + return (context, int(test), rec_tpl_params) + + def __getinitargs__(self): + return (None, self.namespaceURI, self.localName, self.prefix, + self.baseUri) + + def __getstate__(self): + base_state = XsltElement.__getstate__(self) + new_state = (base_state, self._nss, self._test, self._expr) + return new_state + + def __setstate__(self, state): + XsltElement.__setstate__(self, state[0]) + self._nss = state[1] + self._test = state[2] + self._expr = state[3] + return + diff --git a/pool/shard001/Python/0014427_ipmanagertest.py b/pool/shard001/Python/0014427_ipmanagertest.py new file mode 100644 index 0000000000000000000000000000000000000000..6032c15c54a2108b26870db0f5f903300a7d098a --- /dev/null +++ b/pool/shard001/Python/0014427_ipmanagertest.py @@ -0,0 +1,85 @@ + +import clusto +from clusto.test import testbase + +from clusto.drivers import IPManager, BasicServer, ResourceTypeException, ResourceException + +import IPy + +class IPManagerTest(testbase.ClustoTestBase): + + def data(self): + + ip1 = IPManager('a1', gateway='192.168.1.1', netmask='255.255.255.0', + baseip='192.168.1.0') + + ip2 = IPManager('b1', gateway='10.0.128.1', netmask='255.255.252.0', + baseip='10.0.128.0') + + ip3 = IPManager('c1', gateway='172.16.40.0', netmask='255.255.255.0', + baseip='172.16.40.0') + + ip4 = IPManager('c2', gateway='172.16.0.0', netmask='255.255.0.0', + baseip='172.16.0.0') + + s = BasicServer('s1') + + def testBadIPAllocation(self): + + ip1, ip2, s1 = map(clusto.get_by_name, ['a1', 'b1', 's1']) + + self.assertRaises(ResourceTypeException, ip1.allocate, s1, '10.2.3.4') + + def testNewIP(self): + + ip1, ip2, s1 = map(clusto.get_by_name, ['a1', 'b1', 's1']) + + num = 50 + for i in range(num): + ip1.allocate(s1) + + + self.assertEqual(ip1.count, num) + self.assertEqual(len(ip1.resources(s1)), num) + + self.assertEqual(ip1.owners('192.168.1.' + str(num+1)), [s1]) + + def testGetIPManager(self): + + ip1, ip2 = map(clusto.get_by_name, ['a1', 'b1']) + + self.assertEqual(ip1, IPManager.get_ip_manager('192.168.1.23')) + self.assertEqual(ip2, IPManager.get_ip_manager('10.0.129.22')) + + def testGetIPManagers(self): + ip3, ip4 = map(clusto.get_by_name, ['c1', 'c2']) + + self.assertEqual([ip3, ip4], IPManager.get_ip_managers('172.16.40.2')) + self.assertEqual([ip4], IPManager.get_ip_managers('172.16.0.2')) + self.assertEqual([], IPManager.get_ip_managers('192.168.40.1')) + + def testGetIP(self): + + ip1, ip2, s1 = map(clusto.get_by_name, ['a1', 'b1', 's1']) + + ip1.allocate(s1) + ip2.allocate(s1) + + self.assertEqual(sorted(IPManager.get_ips(s1)), + sorted(['192.168.1.2', '10.0.128.2'])) + + def testReserveIP(self): + + ip1, ip2, s1 = map(clusto.get_by_name, ['a1', 'b1', 's1']) + + ip2.allocate(ip2, '10.0.128.4') + + self.assertRaises(ResourceException, ip2.allocate, s1, '10.0.128.4') + + def testAdditionalAttrs(self): + ip1, ip2, s1 = map(clusto.get_by_name, ['a1', 'b1', 's1']) + + ip1.allocate(s1, '192.168.1.20') + + self.assertEqual(str(s1.attr_value(key='ip', subkey='ipstring')), '192.168.1.20') + self.assertEqual(str(s1.attr_value(key='ip', subkey='cidr')), '192.168.1.20/24') diff --git a/pool/shard001/Python/0014428_user.py b/pool/shard001/Python/0014428_user.py new file mode 100644 index 0000000000000000000000000000000000000000..9ad3e879301bfbbf60fe86322e988da3f7189ea3 --- /dev/null +++ b/pool/shard001/Python/0014428_user.py @@ -0,0 +1,97 @@ +'''Report CKAN user statistics''' + +import ckan.model as model + +import sqlalchemy as sa + +import json as json +import os as os +from datetime import datetime + +import logging +log = logging.getLogger('ckanext.statreports.user') + +def _table(name): + return sa.Table(name, model.meta.metadata, autoload=True) + + +class UserStats(object): + '''User statistics''' + + @staticmethod + def total_users(): + ''' + Return total user count + + :return: count + ''' + return model.Session.query(model.User.id).count() + + @classmethod + def users_by_month(cls): + ''' + New users by month + + :return: count + ''' + user = _table('user') + q = sa.select([sa.func.count('id'), sa.extract('year', user.c.created), + sa.extract('month', user.c.created)], + from_obj=[user]).\ + group_by('anon_1', 'anon_2').\ + order_by('anon_1', 'anon_2') + res = model.Session.execute(q).fetchall() + ret = {} + for count, anon_1, anon_2 in res: + # key = unicode(int(anon_1)) + "/" + unicode(int(anon_2)) + key = '%s-%02d' % (int(anon_1), int(anon_2)) + ret[key] = int(count) + + return ret + + @staticmethod + def total_visitors(engine, year_month=None): + ''' + Return total unique visitor count + + :param engine: + :return: visitor count + ''' + if year_month: + sql = '''SELECT count(DISTINCT user_key) FROM tracking_raw + WHERE to_char(access_timestamp, 'YYYY-MM') LIKE %(year_month)s''' + else: + sql = 'SELECT count(DISTINCT user_key) FROM tracking_raw' + + return engine.execute(sql, year_month=year_month).fetchone()[0] + + @staticmethod + def total_logged_in(year_month=None): + ''' + Return logged in visitors. Data accessed here is generated by script. + Reads /opt/data/ckan/pyenv/logins.json. File contents aren't trusted. + + :param year_month: yyyy-mm or None + :return: logged in visitor count + ''' + + fh = '/opt/data/ckan/pyenv/logins.json' + + ret = 0 + if not (os.path.isfile(fh) and os.access(fh, os.R_OK)): + return None + try: + json_data = open(fh).read() + data = json.loads(json_data) + if year_month: + return data.get('items').get(year_month, None) + + for key, value in data.get('items').iteritems(): + if isinstance(value, int): + ret += value + + except (ValueError, TypeError) as e: + ret = None + log.error('Statreports total_logged_in failed. Faulty json {filename}: {err}' + .format(filename=fh, err=e)) + return ret diff --git a/pool/shard001/Python/0014432_alarm_receiver.py b/pool/shard001/Python/0014432_alarm_receiver.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c9de6bf3ac68a122bcf8f61b2ba2fc39cc2be4 --- /dev/null +++ b/pool/shard001/Python/0014432_alarm_receiver.py @@ -0,0 +1,92 @@ +# Copyright 2012 OpenStack Foundation +# +# 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 oslo_config import cfg +from oslo_log import log as logging +from oslo_serialization import jsonutils +from six.moves.urllib import parse as urlparse +from tacker.vnfm.monitor_drivers.token import Token +from tacker import wsgi +# check alarm url with db --> move to plugin + +LOG = logging.getLogger(__name__) + +OPTS = [ + cfg.StrOpt('username', default='tacker', + help=_('User name for alarm monitoring')), + cfg.StrOpt('password', default='nomoresecret', + help=_('password for alarm monitoring')), + cfg.StrOpt('project_name', default='service', + help=_('project name for alarm monitoring')), + cfg.StrOpt('url', default='http://localhost:35357/v3', + help=_('url for alarm monitoring')), +] + +cfg.CONF.register_opts(OPTS, 'alarm_auth') + + +def config_opts(): + return [('alarm_auth', OPTS)] + + +class AlarmReceiver(wsgi.Middleware): + def process_request(self, req): + LOG.debug(_('Process request: %s'), req) + if req.method != 'POST': + return + url = req.url + if not self.handle_url(url): + return + prefix, info, params = self.handle_url(req.url) + token = Token(username=cfg.CONF.alarm_auth.username, + password=cfg.CONF.alarm_auth.password, + project_name=cfg.CONF.alarm_auth.project_name, + auth_url=cfg.CONF.alarm_auth.url, + user_domain_name='default', + project_domain_name='default') + + token_identity = token.create_token() + req.headers['X_AUTH_TOKEN'] = token_identity + # Change the body request + if req.body: + body_dict = dict() + body_dict['trigger'] = {} + body_dict['trigger'].setdefault('params', {}) + # Update params in the body request + body_info = jsonutils.loads(req.body) + body_dict['trigger']['params']['data'] = body_info + body_dict['trigger']['params']['credential'] = info[6] + # Update policy and action + body_dict['trigger']['policy_name'] = info[4] + body_dict['trigger']['action_name'] = info[5] + req.body = jsonutils.dumps(body_dict) + LOG.debug('Body alarm: %s', req.body) + # Need to change url because of mandatory + req.environ['PATH_INFO'] = prefix + 'triggers' + req.environ['QUERY_STRING'] = '' + LOG.debug('alarm url in receiver: %s', req.url) + + def handle_url(self, url): + # alarm_url = 'http://host:port/v1.0/vnfs/vnf-uuid/mon-policy-name/action-name/8ef785' # noqa + parts = urlparse.urlparse(url) + p = parts.path.split('/') + if len(p) != 7: + return None + + if any((p[0] != '', p[2] != 'vnfs')): + return None + qs = urlparse.parse_qs(parts.query) + params = dict((k, v[0]) for k, v in qs.items()) + prefix_url = '/%(collec)s/%(vnf_uuid)s/' % {'collec': p[2], + 'vnf_uuid': p[3]} + return prefix_url, p, params diff --git a/pool/shard001/Python/0014436_localstorage_test.py b/pool/shard001/Python/0014436_localstorage_test.py new file mode 100644 index 0000000000000000000000000000000000000000..dddd23dfc0c08b482ab2464d90f06487a4ba46f1 --- /dev/null +++ b/pool/shard001/Python/0014436_localstorage_test.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +import unittest +import pbtest +import json +from time import sleep + +# time to wait for loading privacy policy from eff.org +POLICY_DOWNLOAD_TIMEOUT = 20 +PB_POLICY_HASH_LEN = 40 # https://www.eff.org/files/dnt-policies.json +PB_POLICY_KEY = "Preliminary DNT Policy" + + +class LocalStorageTest(pbtest.PBSeleniumTest): + """Make sure the following localStorage items are initialized correctly. + + - enabled + - whitelistUrl + - badgerHashes + + Also make sure that "disabledSites" is not initialized. + """ + def check_policy_download(self): + timeout = POLICY_DOWNLOAD_TIMEOUT + # give updatePrivacyPolicyHashes() sometime to download the policy hash + while (timeout > 0 and + not self.js("return ('badgerHashes' in localStorage)")): + sleep(1) + timeout -= 1 + + # make sure we didn't time-out + self.assertGreater(timeout, 0, + "Timed out while waiting for the localStorage.badgerHashes") + # now check the downloaded policy hash + policy_hash = self.js("return localStorage.badgerHashes") + print "Downloaded policy hash in %s seconds: %s" %\ + (POLICY_DOWNLOAD_TIMEOUT - timeout, policy_hash) + try: + policy_json = json.loads(policy_hash) + except: + self.fail("localStorage.badgerHashes is not valid JSON") + self.assertEqual(PB_POLICY_HASH_LEN, + len(policy_json[PB_POLICY_KEY])) + + def test_should_init_local_storage_entries(self): + self.driver.get(pbtest.PB_CHROME_BG_URL) + assertTrue = self.assertTrue + js = self.js + self.check_policy_download() + assertTrue(js("return localStorage.enabled")) + self.assertEqual(js("return localStorage.whitelistUrl"), + "https://www.eff.org/files/cookieblocklist.txt") + + disabled_sites = js("return ('disabledSites' in localStorage && " + "JSON.parse(localStorage.disabledSites).length > 0)") + self.assertFalse(disabled_sites, + "Shouldn't have any disabledSites after installation") + # TODO: do we expect currentVersion to be present after the first run? + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard001/Python/0014437_init__.py b/pool/shard001/Python/0014437_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..98d0fefb8f3d38875db579cb10c9d34f07a183dc --- /dev/null +++ b/pool/shard001/Python/0014437_init__.py @@ -0,0 +1,63 @@ +# +# Copyright 2008 Benedikt Sauer +# +# This file is part of Wobsiter. +# +# Wobsiter is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Wobsiter is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Wobsiter. If not, see . +# +from contextlib import contextmanager +from .. import util + +class Source(object): + __metaclass__ = util.InternedMeta + + _is_built = False + + @staticmethod + def __id_args__(path, dir='', handler=None, *args, **kwargs): + return (util.normalize(path), util.normalize(dir)) + + def __init__(self, path, dir='', handler=None, *args, **kwargs): + self._dir = util.normalize(dir) + self._path = util.normalize(path) + if not handler: + handler = _handlers[util.ext(self._path)] + self.handler = handler(self._path, *args, **kwargs) + + def __call__(self, output): + if not self._is_built: + if hasattr(self.handler, 'deps'): + for source in self.handler.deps: + source(output) + print 'Building %s using %s' \ + % (self._path, self.handler.__class__.__name__) + output.set_directory(self._dir) + self.result = self.handler.build(output) + self._is_built = True + + def __repr__(self): + return "" \ + % (self._path, self.handler.__class__.__name__) + + +from rst import RstHandler +from template import TemplateHandler +from menu import MenuHandler + +_handlers = { + 'tmpl' : TemplateHandler, + 'txt' : RstHandler, + 'menu' : MenuHandler, + } + diff --git a/pool/shard001/Python/0014441_pipeline_main.py b/pool/shard001/Python/0014441_pipeline_main.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce4af21d86b358c2d412fe366dc68f3adc6408d --- /dev/null +++ b/pool/shard001/Python/0014441_pipeline_main.py @@ -0,0 +1,112 @@ +''' +Created on 25/09/2013 + +@author: Lenneke Jong +''' + +from sxri_data_exchange.dataexchange import SXRIDataExchange +from pipeline.pre_processing import run_preprocessing +from pipeline.fresnel_reconstruction import fresnel_whitefield_reco2, fresnel_ptyco_reco +import logging +import traceback +import argparse + + + +class Pipeline(object): + ''' + Main class of the data processing pipeline for the SXR-Imaging beamline at + the Australian Synchrotron. + ''' + + + def __init__(self, filepath): + '''Constructor + Get the pipeline variables from the hdf5 file itself, but for now + lets just do some hardcoded setup + ''' + self.data_exchange = SXRIDataExchange(filepath) + logging.basicConfig(filename='sxri_pipeline_testing.log', + level=logging.DEBUG) + logging.debug('a debug message') + + + def setup_h5py(self): + '''This function checks that we have the correct data present and will + report back errors that will mean the pipeline cannot run. + ''' + self.check_exchange_data() + self.check_geometry() + + + + def check_exchange_data(self): + ''' + Check that there exists an exchange group which contains one dataset + called data and at least one of each data_dark and data_white. + ''' + + if 'exchange' in self.data_exchange.keys(): + datasets = ['data', 'data_dark', 'data_white'] + if all(x in self.data_exchange.keys() for x in datasets): + return + else: + raise Exception("raw data exchange group for raw data requires \ + at least datasets named data, data_dark and data_white") + else: + raise Exception('no raw data exchange group found') + + + + def check_geometry(self): + ''' + Checks that there are attributes that describe the geometry of the experiment. Not yet implemented + ''' + pass + + def run(self, *args, **kwargs): + ''' Run the pipeline, This is the main method in the pipeline class where the separate pipeline modules + and put together. Some methods here have been commented out for ease with testing, so that steps don't need + to be rerun. The self.data_exchange argument for each of the methods is required + ''' + try: + #self.setup_h5py() + #run_preprocessing(self.data_exchange) + # next_input_group_name="/exchange_1" + #fresnel_whitefield_reco(self.data_exchange, next_input_group_name) + #fresnel_whitefield_reco2(self.data_exchange) + #self.data_exchange.print_groups() + fresnel_ptyco_reco(self.data_exchange) + self.data_exchange.print_groups() + except Exception as ex: + print ex.message + tb = traceback.format_exc() + print tb + finally: + self.cleanup() + + + def cleanup(self): + ''' + Close the hdf5 file and other cleaning up. + ''' + self.data_exchange.flush() + self.data_exchange.close() + + +def main(): + ''' + Run the pipeline from the command line. pass a hdf as the argument + ''' + parser = argparse.ArgumentParser(description="Run the SXRI processing pipeline.") + parser.add_argument('filename', metavar='filename', help='full path of the hdf5 file') + args = parser.parse_args() + if args.filename: + p = Pipeline(args.filename) + p.run() + else: + parser.print_help() + + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0014442_oggvorbis.py b/pool/shard001/Python/0014442_oggvorbis.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1d8fb0b86c32302b1a542c65a2e9a3e743077e --- /dev/null +++ b/pool/shard001/Python/0014442_oggvorbis.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2006 Joe Wreschnig +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. + +"""Read and write Ogg Vorbis comments. + +This module handles Vorbis files wrapped in an Ogg bitstream. The +first Vorbis stream found is used. + +Read more about Ogg Vorbis at http://vorbis.com/. This module is based +on the specification at http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html. +""" + +__all__ = ["OggVorbis", "Open", "delete"] + +import struct + +from mutagen import StreamInfo +from mutagen._vorbis import VCommentDict +from mutagen._util import get_size, loadfile, convert_error +from mutagen._tags import PaddingInfo +from mutagen.ogg import OggPage, OggFileType, error as OggError + + +class error(OggError): + pass + + +class OggVorbisHeaderError(error): + pass + + +class OggVorbisInfo(StreamInfo): + """OggVorbisInfo() + + Ogg Vorbis stream information. + + Attributes: + length (`float`): File length in seconds, as a float + channels (`int`): Number of channels + bitrate (`int`): Nominal ('average') bitrate in bits per second + sample_Rate (`int`): Sample rate in Hz + + """ + + length = 0.0 + channels = 0 + bitrate = 0 + sample_rate = 0 + + def __init__(self, fileobj): + """Raises ogg.error, IOError""" + + page = OggPage(fileobj) + while not page.packets[0].startswith(b"\x01vorbis"): + page = OggPage(fileobj) + if not page.first: + raise OggVorbisHeaderError( + "page has ID header, but doesn't start a stream") + (self.channels, self.sample_rate, max_bitrate, nominal_bitrate, + min_bitrate) = struct.unpack(" nominal_bitrate: + self.bitrate = min_bitrate + else: + self.bitrate = nominal_bitrate + + def _post_tags(self, fileobj): + """Raises ogg.error""" + + page = OggPage.find_last(fileobj, self.serial) + if page is None: + raise OggVorbisHeaderError + self.length = page.position / float(self.sample_rate) + + def pprint(self): + return u"Ogg Vorbis, %.2f seconds, %d bps" % ( + self.length, self.bitrate) + + +class OggVCommentDict(VCommentDict): + """Vorbis comments embedded in an Ogg bitstream.""" + + def __init__(self, fileobj, info): + pages = [] + complete = False + while not complete: + page = OggPage(fileobj) + if page.serial == info.serial: + pages.append(page) + complete = page.complete or (len(page.packets) > 1) + data = OggPage.to_packets(pages)[0][7:] # Strip off "\x03vorbis". + super(OggVCommentDict, self).__init__(data) + self._padding = len(data) - self._size + + def _inject(self, fileobj, padding_func): + """Write tag data into the Vorbis comment packet/page.""" + + # Find the old pages in the file; we'll need to remove them, + # plus grab any stray setup packet data out of them. + fileobj.seek(0) + page = OggPage(fileobj) + while not page.packets[0].startswith(b"\x03vorbis"): + page = OggPage(fileobj) + + old_pages = [page] + while not (old_pages[-1].complete or len(old_pages[-1].packets) > 1): + page = OggPage(fileobj) + if page.serial == old_pages[0].serial: + old_pages.append(page) + + packets = OggPage.to_packets(old_pages, strict=False) + + content_size = get_size(fileobj) - len(packets[0]) # approx + vcomment_data = b"\x03vorbis" + self.write() + padding_left = len(packets[0]) - len(vcomment_data) + + info = PaddingInfo(padding_left, content_size) + new_padding = info._get_padding(padding_func) + + # Set the new comment packet. + packets[0] = vcomment_data + b"\x00" * new_padding + + new_pages = OggPage._from_packets_try_preserve(packets, old_pages) + OggPage.replace(fileobj, old_pages, new_pages) + + +class OggVorbis(OggFileType): + """OggVorbis(filething) + + Arguments: + filething (filething) + + An Ogg Vorbis file. + + Attributes: + info (`OggVorbisInfo`) + tags (`mutagen._vorbis.VCommentDict`) + """ + + _Info = OggVorbisInfo + _Tags = OggVCommentDict + _Error = OggVorbisHeaderError + _mimes = ["audio/vorbis", "audio/x-vorbis"] + + info = None + tags = None + + @staticmethod + def score(filename, fileobj, header): + return (header.startswith(b"OggS") * (b"\x01vorbis" in header)) + + +Open = OggVorbis + + +@convert_error(IOError, error) +@loadfile(method=False, writable=True) +def delete(filething): + """ delete(filething) + + Arguments: + filething (filething) + Raises: + mutagen.MutagenError + + Remove tags from a file. + """ + + t = OggVorbis(filething) + filething.fileobj.seek(0) + t.delete(filething) diff --git a/pool/shard001/Python/0014443_watermarkUtils.py b/pool/shard001/Python/0014443_watermarkUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..5eeb3270435e2803a5e7be1434fbb2f46f2efd1c --- /dev/null +++ b/pool/shard001/Python/0014443_watermarkUtils.py @@ -0,0 +1,51 @@ +from PIL import Image, ImageEnhance + +def reduce_opacity(im, opacity): + """Returns an image with reduced opacity.""" + assert opacity >= 0 and opacity <= 1 + if im.mode != 'RGBA': + im = im.convert('RGBA') + else: + im = im.copy() + alpha = im.split()[3] + alpha = ImageEnhance.Brightness(alpha).enhance(opacity) + im.putalpha(alpha) + return im + +def watermark(im, mark, position, opacity=1): + """Adds a watermark to an image.""" + if opacity < 1: + mark = reduce_opacity(mark, opacity) + if im.mode != 'RGBA': + im = im.convert('RGBA') + # create a transparent layer the size of the image and draw the + # watermark in that layer. + layer = Image.new('RGBA', im.size, (0,0,0,0)) + if position == 'tile': + for y in range(0, im.size[1], mark.size[1]): + for x in range(0, im.size[0], mark.size[0]): + layer.paste(mark, (x, y)) + elif position == 'scale': + # scale, but preserve the aspect ratio + ratio = min( + float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) + ratioW = float(im.size[0]) / mark.size[0] + ratioH = float(im.size[1]) / mark.size[1] + w = int(mark.size[0] * ratioW) + h = int(mark.size[1] * ratioH) + mark = mark.resize((w, h)) + layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2)) + else: + layer.paste(mark, position) + # composite the watermark with the layer + return Image.composite(layer, im, layer) + +def test(): + im = Image.open('test.png') + mark = Image.open('overlay2.jpg') + #watermark(im, mark, 'tile', 0.3).show() + watermark(im, mark, 'scale', 0.4).show() + #watermark(im, mark, (100, 100), 0.5).show() + +if __name__ == '__main__': + test() diff --git a/pool/shard001/Python/0014445_analyse_dataset.py b/pool/shard001/Python/0014445_analyse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..53a2501d13b8298011e1b6d129f99dfab65454c6 --- /dev/null +++ b/pool/shard001/Python/0014445_analyse_dataset.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +import associate +import numpy as np +import matplotlib.pyplot as plt +import yaml + +def loadDataset(filename): + file = open(filename) + data = file.read() + lines = data.replace(","," ").replace("\t"," ").split("\n") + D = np.array([[v.strip() for v in line.split(" ") if v.strip()!=""] for line in lines if len(line)>0 and line[0]!="#"], dtype=np.float64) + return D + +dataset_dir = '/home/cforster/Datasets/SlamBenchmark/px4_r2' +trajectory_data = dataset_dir+'/groundtruth.txt' +stepsize = 10 + +# load dataset +data = loadDataset(trajectory_data) +n = data.shape[0] +steps = np.arange(0,n,stepsize) + +# compute trajectory length +last_pos = data[0,1:4] +trajectory_length = 0 + +for i in steps[1:]: + new_pos = data[i,1:4] + trajectory_length += np.linalg.norm(new_pos-last_pos) + last_pos = new_pos + + +print 'trajectory lenght = ' + str(trajectory_length) + 'm' +print 'height mean = ' + str(np.mean(data[:,3])) + 'm' +print 'height median = ' + str(np.median(data[:,3])) + 'm' +print 'height std = ' + str(np.std(data[:,3])) + 'm' +print 'duration = ' + str(data[-1,0]-data[0,0]) + 's' +print 'speed = ' + str(trajectory_length/(data[-1,0]-data[0,0])) + 'm/s' + + diff --git a/pool/shard001/Python/0014447_const.py b/pool/shard001/Python/0014447_const.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b60769e45de701fa8ab4e47bcfc7c90763dbe3 --- /dev/null +++ b/pool/shard001/Python/0014447_const.py @@ -0,0 +1,127 @@ +"""Constants used by vizio component.""" +from pyvizio import VizioAsync +from pyvizio.const import ( + DEVICE_CLASS_SPEAKER as VIZIO_DEVICE_CLASS_SPEAKER, + DEVICE_CLASS_TV as VIZIO_DEVICE_CLASS_TV, +) +import voluptuous as vol + +from homeassistant.components.media_player import DEVICE_CLASS_SPEAKER, DEVICE_CLASS_TV +from homeassistant.components.media_player.const import ( + SUPPORT_NEXT_TRACK, + SUPPORT_PREVIOUS_TRACK, + SUPPORT_SELECT_SOURCE, + SUPPORT_TURN_OFF, + SUPPORT_TURN_ON, + SUPPORT_VOLUME_MUTE, + SUPPORT_VOLUME_SET, + SUPPORT_VOLUME_STEP, +) +from homeassistant.const import ( + CONF_ACCESS_TOKEN, + CONF_DEVICE_CLASS, + CONF_EXCLUDE, + CONF_HOST, + CONF_INCLUDE, + CONF_NAME, +) +import homeassistant.helpers.config_validation as cv + +SERVICE_UPDATE_SETTING = "update_setting" + +ATTR_SETTING_TYPE = "setting_type" +ATTR_SETTING_NAME = "setting_name" +ATTR_NEW_VALUE = "new_value" + +UPDATE_SETTING_SCHEMA = { + vol.Required(ATTR_SETTING_TYPE): vol.All(cv.string, vol.Lower, cv.slugify), + vol.Required(ATTR_SETTING_NAME): vol.All(cv.string, vol.Lower, cv.slugify), + vol.Required(ATTR_NEW_VALUE): vol.Any(vol.Coerce(int), cv.string), +} + +CONF_ADDITIONAL_CONFIGS = "additional_configs" +CONF_APP_ID = "APP_ID" +CONF_APPS = "apps" +CONF_APPS_TO_INCLUDE_OR_EXCLUDE = "apps_to_include_or_exclude" +CONF_CONFIG = "config" +CONF_INCLUDE_OR_EXCLUDE = "include_or_exclude" +CONF_NAME_SPACE = "NAME_SPACE" +CONF_MESSAGE = "MESSAGE" +CONF_VOLUME_STEP = "volume_step" + +DEFAULT_DEVICE_CLASS = DEVICE_CLASS_TV +DEFAULT_NAME = "Vizio SmartCast" +DEFAULT_TIMEOUT = 8 +DEFAULT_VOLUME_STEP = 1 + +DEVICE_ID = "pyvizio" + +DOMAIN = "vizio" +ICON = {DEVICE_CLASS_TV: "mdi:television", DEVICE_CLASS_SPEAKER: "mdi:speaker"} + +COMMON_SUPPORTED_COMMANDS = ( + SUPPORT_SELECT_SOURCE + | SUPPORT_TURN_ON + | SUPPORT_TURN_OFF + | SUPPORT_VOLUME_MUTE + | SUPPORT_VOLUME_SET + | SUPPORT_VOLUME_STEP +) + +SUPPORTED_COMMANDS = { + DEVICE_CLASS_SPEAKER: COMMON_SUPPORTED_COMMANDS, + DEVICE_CLASS_TV: ( + COMMON_SUPPORTED_COMMANDS | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK + ), +} + +VIZIO_SOUND_MODE = "eq" +VIZIO_AUDIO_SETTINGS = "audio" +VIZIO_MUTE_ON = "on" +VIZIO_VOLUME = "volume" +VIZIO_MUTE = "mute" + +# Since Vizio component relies on device class, this dict will ensure that changes to +# the values of DEVICE_CLASS_SPEAKER or DEVICE_CLASS_TV don't require changes to pyvizio. +VIZIO_DEVICE_CLASSES = { + DEVICE_CLASS_SPEAKER: VIZIO_DEVICE_CLASS_SPEAKER, + DEVICE_CLASS_TV: VIZIO_DEVICE_CLASS_TV, +} + +VIZIO_SCHEMA = { + vol.Required(CONF_HOST): cv.string, + vol.Optional(CONF_ACCESS_TOKEN): cv.string, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_DEVICE_CLASS, default=DEFAULT_DEVICE_CLASS): vol.All( + cv.string, vol.Lower, vol.In([DEVICE_CLASS_TV, DEVICE_CLASS_SPEAKER]) + ), + vol.Optional(CONF_VOLUME_STEP, default=DEFAULT_VOLUME_STEP): vol.All( + vol.Coerce(int), vol.Range(min=1, max=10) + ), + vol.Optional(CONF_APPS): vol.All( + { + vol.Exclusive(CONF_INCLUDE, "apps_filter"): vol.All( + cv.ensure_list, [vol.All(cv.string, vol.In(VizioAsync.get_apps_list()))] + ), + vol.Exclusive(CONF_EXCLUDE, "apps_filter"): vol.All( + cv.ensure_list, [vol.All(cv.string, vol.In(VizioAsync.get_apps_list()))] + ), + vol.Optional(CONF_ADDITIONAL_CONFIGS): vol.All( + cv.ensure_list, + [ + { + vol.Required(CONF_NAME): cv.string, + vol.Required(CONF_CONFIG): { + vol.Required(CONF_APP_ID): cv.string, + vol.Required(CONF_NAME_SPACE): vol.Coerce(int), + vol.Optional(CONF_MESSAGE, default=None): vol.Or( + cv.string, None + ), + }, + }, + ], + ), + }, + cv.has_at_least_one_key(CONF_INCLUDE, CONF_EXCLUDE, CONF_ADDITIONAL_CONFIGS), + ), +} diff --git a/pool/shard001/Python/0014451_search_indexes.py b/pool/shard001/Python/0014451_search_indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..d987a8775a7108f20e74b10bad9782d649eaa5f6 --- /dev/null +++ b/pool/shard001/Python/0014451_search_indexes.py @@ -0,0 +1,20 @@ +from haystack import indexes +from .models import Event +from django.utils.translation import get_language +from django.utils.html import strip_tags + +class EventIndex(indexes.SearchIndex, indexes.Indexable): + text = indexes.CharField(document=True, use_template=True) + autosuggest = indexes.EdgeNgramField(model_attr='name') + end_time = indexes.DateField(model_attr='end_time') + + def get_updated_field(self): + return 'last_modified_time' + + def get_model(self): + return Event + + def prepare(self, obj): + #obj.lang_keywords = obj.keywords.filter(language=get_language()) + obj.description = strip_tags(obj.description) + return super(EventIndex, self).prepare(obj) diff --git a/pool/shard001/Python/0014452_0030_auto_20160404_1021.py b/pool/shard001/Python/0014452_0030_auto_20160404_1021.py new file mode 100644 index 0000000000000000000000000000000000000000..f00fd5ff9dbeed7709a8fe5226ab8c64ec1c8c5e --- /dev/null +++ b/pool/shard001/Python/0014452_0030_auto_20160404_1021.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('tablemanager', '0029_auto_20160302_0750'), + ] + + operations = [ + migrations.RemoveField( + model_name='publish', + name='applications', + ), + migrations.AddField( + model_name='publishchannel', + name='gwc_endpoint', + field=models.CharField(max_length=256, null=True, blank=True), + preserve_default=True, + ), + migrations.AddField( + model_name='publishchannel', + name='wfs_endpoint', + field=models.CharField(max_length=256, null=True, blank=True), + preserve_default=True, + ), + migrations.AddField( + model_name='publishchannel', + name='wfs_version', + field=models.CharField(max_length=32, null=True, blank=True), + preserve_default=True, + ), + migrations.AddField( + model_name='publishchannel', + name='wms_endpoint', + field=models.CharField(max_length=256, null=True, blank=True), + preserve_default=True, + ), + migrations.AddField( + model_name='publishchannel', + name='wms_version', + field=models.CharField(max_length=32, null=True, blank=True), + preserve_default=True, + ), + ] diff --git a/pool/shard001/Python/0014454_ioloop.py b/pool/shard001/Python/0014454_ioloop.py new file mode 100644 index 0000000000000000000000000000000000000000..b523fb2543f0d5bb9b37e88c6295766e87ed2952 --- /dev/null +++ b/pool/shard001/Python/0014454_ioloop.py @@ -0,0 +1,27 @@ +import threading +import tornado.ioloop + +from pubsub import * + +_pubsub = PubSub() + +class IOLoop(tornado.ioloop.IOLoop): + pass + +def run_async(run, callback): + 'Note: callback runs in the main loop, run in another thread' + def actual_cb(*args, **kwargs): + IOLoop.instance().add_callback(callback, *args, **kwargs) + thread = threading.Thread(target=run, args=(actual_cb,)) + thread.daemon = True + thread.start() + +def start(): + try: + IOLoop.current().start() + except KeyboardInterrupt: + IOLoop.current().stop() + _pubsub.publish(True, 'stop') + print + +subscribe = _pubsub.subscribe diff --git a/pool/shard001/Python/0014456_switchStatement.py b/pool/shard001/Python/0014456_switchStatement.py new file mode 100644 index 0000000000000000000000000000000000000000..59849f2794583191e39414b5d734f3edc07f0fa5 --- /dev/null +++ b/pool/shard001/Python/0014456_switchStatement.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from hwt.code import Switch +from hwt.hdl.types.bits import Bits +from hwt.synthesizer.rtlLevel.netlist import RtlNetlist +from hwtLib.examples.rtlLvl.netlistToRtl import netlistToVhdlStr +from ipCorePackager.constants import DIRECTION + + +def SwitchStatement(): + t = Bits(8) + n = RtlNetlist() + + In = n.sig("input", t, def_val=8) + Out = n.sig("output", t) + + Switch(In).add_cases( + [(i, Out(i + 1)) for i in range(8)] + ) + + interf = {In: DIRECTION.IN, Out: DIRECTION.OUT} + return n, interf + + +if __name__ == "__main__": + netlist, interfaces = SwitchStatement() + print(netlistToVhdlStr("SwitchStatement", netlist, interfaces)) diff --git a/pool/shard001/Python/0014457_admin_queue.py b/pool/shard001/Python/0014457_admin_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa626af89f604306736523f6b2c573d253876e7 --- /dev/null +++ b/pool/shard001/Python/0014457_admin_queue.py @@ -0,0 +1,16 @@ +from __future__ import absolute_import + +from sentry.celery import app +from sentry.web.frontend.base import BaseView + + +class AdminQueueView(BaseView): + def has_permission(self, request): + return request.user.is_superuser + + def handle(self, request): + context = { + 'task_list': sorted(app.tasks.keys()), + } + + return self.respond('sentry/admin-queue.html', context) diff --git a/pool/shard001/Python/0014459_36mh.py b/pool/shard001/Python/0014459_36mh.py new file mode 100644 index 0000000000000000000000000000000000000000..8450f92b8395ca3abd70b06ea52b62eab45b6d21 --- /dev/null +++ b/pool/shard001/Python/0014459_36mh.py @@ -0,0 +1,168 @@ +import glob +import os +import re +import threading +import urllib +import execjs +from concurrent.futures import ThreadPoolExecutor +from queue import Queue, Empty + +from core.login import Login +from util.utils import HttpUtils + + +class Crawler(Login): + task_pool = Queue() + process_thread = None + book_id = 0 + comic_id = "0" + comic_name = "" + + root_url = "http://www.36mh.com" + + headers = { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6,ja;q=0.5", + "Cache-Control": "max-age=0", + "Connection": "keep-alive", + "DNT": "1", + "Host": "www.36mh.com", + "If-Modified-Since": "Sun, 30 Aug 2020 07:32:53 GMT", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36" + } + + mobile_headers = { + "Host": "img001.shmkks.com:443", + "User-Agent": "Mozilla/5.0 (Linux; Android 10; MI 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.127 Mobile Safari/537.36""" + } + + @classmethod + def start(cls, book_id): + cls.book_id = book_id + cls.parse_lvl_one() + + @classmethod + def init_thread(cls): + if cls.process_thread is None: + cls.process_thread = threading.Thread(target=cls.process) + cls.process_thread.start() + + @classmethod + def parse_lvl_one(cls): + if cls.book_id is None: + return + + url = "http://www.36mh.com/manhua/%s/" % cls.book_id + retry = 0 + while True: + resp = HttpUtils.get(url, headers=cls.headers) + if resp is not None: + break + else: + retry += 1 + + assert retry < 5, "fail to query %s" % url + + cls.comic_name = HttpUtils.get_content(resp, "title").strip() + links = HttpUtils.get_attrs(resp, "#chapter-list-4 li a", "href") + + titles = HttpUtils.get_contents(resp, "#chapter-list-4 li a span") + + assert len(titles) == len(links) + + cls.init_thread() + + for index in range(len(titles)): + link = links[index] + title = titles[index].strip() + cls.parse_lvl_two((link, title)) + break + cls.process_thread.join() + + # code below should be useless if everything goes well + while not cls.task_pool.empty(): + print("pool size = " + str(cls.task_pool.qsize())) + cls.init_thread() + cls.process_thread.join() + + @classmethod + def parse_lvl_two(cls, info): + chapter_url = info[0] + title = info[1] + + # create folder once + folder_name = "output/" + cls.comic_name + "/" + title + if not os.path.exists(folder_name): + os.makedirs(folder_name, exist_ok=True) + + # + # path_file_number = len(glob.glob(pathname=folder_name + '/*')) + # if path_file_number == image_number: + # print("下载完毕:" + title) + # # already downloaded all + # return + + print("开始下载: " + title) + + query_url = cls.root_url + chapter_url + + retry = 0 + while True: + content = HttpUtils.get(query_url, headers=cls.headers) + if content is not None: + break + else: + retry += 1 + + assert retry < 5, "fail to query %s" % query_url + + script_content = HttpUtils.get_contents(content, "script") + # print(script_content[2][1:].replace(";;", ";").replace(";", ";\n")) + + image_url_list = re.search("chapterImages.*=.*\[(.*)\];", script_content[2]).group(1).replace("\"", "").split( + ",") + + path = re.search("chapterPath.*?=.*?\"(.*?)\";", script_content[2]).group(1) + + assert len(image_url_list) > 0 + + index = 1 + for image_url in image_url_list: + full_image_url = "https://img001.shmkks.com/" + path + image_url + file_path = "%s/%03d_%s" % (folder_name, index, image_url) + cls.task_pool.put([file_path, full_image_url, 0]) + index += 1 + + @classmethod + def process(cls): + print("#### process thread started") + with ThreadPoolExecutor(max_workers=50) as executor: + while True: + try: + # queue timeout should be greater than the download timeout + item = cls.task_pool.get(timeout=60) + executor.submit(cls.do_process, item) + except Empty as e: + print("#### queue timeout") + break + cls.process_thread = None + print("#### process thread stopped") + + @classmethod + def do_process(cls, item): + path = item[0] + url = item[1] + retry = item[2] + if retry <= 5: + if not HttpUtils.download_file(url=url, dest_path=path, headers=cls.mobile_headers): + item[2] += 1 + cls.task_pool.put(item) + cls.init_thread() + else: + print("Exceed max retry time: " + path) + + +if __name__ == "__main__": + Crawler.start("wunengdenainai") diff --git a/pool/shard001/Python/0014464_test_sand.py b/pool/shard001/Python/0014464_test_sand.py new file mode 100644 index 0000000000000000000000000000000000000000..858621463e519b3a08b9b0cf3f1b31e05ace01b7 --- /dev/null +++ b/pool/shard001/Python/0014464_test_sand.py @@ -0,0 +1,79 @@ +import unittest + +from ziphmm import ZipSequence +from ziphmm import compute_lle +from _internal import create_hmm +from _internal import create_seq + + +class TestSand(unittest.TestCase): + + def test0(self): + self.__test('test0', 'test0', -12.4766) + + def test1(self): + self.__test('test1', 'test1', -12.5671) + + def test2(self): + self.__test('test2', 'test2', -27.5310) + + def test3(self): + self.__test('test3', 'test3', 0.0) + + def test4(self): + self.__test('test4', 'test4', -24.0953) + + def test5(self): + self.__test('test5', 'test5', -5.7827) + + def test6(self): + self.__test('test6', 'test6', -18.8829) + + def test_8_states(self): + self.__test('test8States', 'test8States', 0.0) + + def test_off_by_one_em(self): + self.__test('testOffByOneEm', 'testOffByOneEm', -16.6355) + + def test_off_by_one_trans(self): + self.__test('TestOffByOneTrans', 'TestOffByOneTrans', -0.0000) + + def test_one_state(self): + self.__test('testOneState', 'testOneState', -12.4766) + + def test_zero_add(self): + self.__test('testZeroAdd', 'testZeroAdd', None) + + def test_no_solution(self): + self.__test('testNoSolution', 'testNoSolution', None) + + def __test(self, hmm_name, seq_name, expected_value): + def fix(n, digits=4): + if n is None: + return None + fmt = '{0:.' + str(digits) + 'f}' + return fmt.format(round(n, digits)) + + hmm = create_hmm('inputs/' + hmm_name + '.hmm') + seq = create_seq('inputs/' + seq_name + '.seq') + xseq = ZipSequence.from_sequence(seq, hmm.state_count) + actual_value = compute_lle(hmm, xseq) + self.assertEqual(fix(expected_value), fix(actual_value)) + + # + # These also work, and execute quickly, but compressing the long sequences + # takes significant time so ignore these test sequences. + # + # def test4_10000(self): + # self.__test('test4', 'test4_10000', -44239.7313) + # + # def test6_10000(self): + # self.__test('test6', 'test6_10000', -10457.5211) + # + # def test6_100000(self): + # self.__test('test6', 'test6_100000', -104126.2411) + # + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0014470_run_dmn.py b/pool/shard001/Python/0014470_run_dmn.py new file mode 100644 index 0000000000000000000000000000000000000000..52a481e28e572e064087539a6f83ba252bb8a24c --- /dev/null +++ b/pool/shard001/Python/0014470_run_dmn.py @@ -0,0 +1,138 @@ +import theano +import theano.tensor as T +import numpy as np +import cPickle + +import config +from reader import get_embedding_matrix_from_param_file +from reader import gkhmc_qla_iterator +from config import options +from models import DMN + +def pred_check(p_ds, ys): + right_num = 0 + total_num = 0 + for i in xrange(len(p_ds) / 4): + y_local = ys[4 * i: 4 * (i + 1)] + p_local = p_ds[4 * i: 4 * (i + 1)] + total_num += 1 + right_index = y_local.index(1) + if right_index == p_local.index(max(p_local)): + right_num += 1 + return right_num, total_num + +def run_epoch(): + # define symbolic variables + q = T.imatrix('q') + q_mask = T.matrix('q_mask', dtype=theano.config.floatX) + l = T.imatrix('l') + l_mask = T.matrix('l_mask', dtype=theano.config.floatX) + a = T.imatrix('a') + a_mask = T.matrix('a_mask', dtype=theano.config.floatX) + y = T.ivector('y') + lr = T.scalar(name='lr') + + np_emb = get_embedding_matrix_from_param_file(config.embedding_param_file) + + # build model + print '...building model' + model = DMN(q, q_mask, l, l_mask, a, a_mask, y, np_emb, options['word_size'], options['hidden_size'], + options['use_dropout'], options['drop_p']) + + cost = model.loss + grads = T.grad(cost, wrt=list(model.params.values())) + optimizer = options['optimizer'] + f_grad_shared, f_update = optimizer(lr, model.params, grads, [q, q_mask, l, l_mask, a, a_mask, y], cost) + + detector = theano.function( + inputs=[q, q_mask, l, l_mask, a, a_mask, y], + outputs=model.error, + on_unused_input='ignore' + ) + p_predictor = theano.function( + inputs=[q, q_mask, l, l_mask, a, a_mask], + outputs=model.p_d, + on_unused_input='ignore' + ) + + # load parameters from specified file + if not options['loaded_params'] is None: + print '...loading parameters from ' + options['loaded_params'] + file_name = options['loaded_params'] + with open(file_name, 'rb') as f: + param_dict = cPickle.load(f) + for k, v in model.params.items(): + v.set_value(param_dict[k]) + + # test the performance of initialized parameters + print '...testing the performance of initialized parameters' + p_ds = [] + ys = [] + for q_, q_mask_, l_, l_mask_, a_, a_mask_, y_ in gkhmc_qla_iterator( + path=config.dataset, batch_size=options['valid_batch_size'], is_train=False): + p_d = p_predictor(q_, q_mask_, l_, l_mask_, a_, a_mask_) + p_ds.extend(p_d) + ys.extend(y_) + right_num, total_num = pred_check(p_ds, ys) + print right_num, '/', total_num + + best_perform = -np.inf + + print '...training model' + for i in xrange(options['max_epochs']): + total_loss = 0. + idx = 0 + for q_, q_mask_, l_, l_mask_, a_, a_mask_, y_ in gkhmc_qla_iterator( + path=config.dataset, batch_size=options['batch_size'], is_train=True): + model.emb_set_value_zero() + this_cost = f_grad_shared(q_, q_mask_, l_, l_mask_, a_, a_mask_, y_) + f_update(options['lrate']) + total_loss += this_cost + print '\r', 'epoch:', i, ', idx:', idx, ', this_loss:', this_cost, + idx += 1 + print ', total loss:', total_loss + + # validate model performance when necessary + if (i + 1) % options['valid_freq'] == 0: + # test performance on train set + errors = [] + for q_, q_mask_, l_, l_mask_, a_, a_mask_, y_ in gkhmc_qla_iterator( + path=config.dataset, batch_size=options['valid_batch_size'], is_train=True): + error = detector(q_, q_mask_, l_, l_mask_, a_, a_mask_, y_) + errors.append(error) + print '\ttrain error of epoch ' + str(i) + ': ' + str(np.mean(errors) * 100) + '%' + + # test performance on test set + p_ds = [] + ys = [] + for q_, q_mask_, l_, l_mask_, a_, a_mask_, y_ in gkhmc_qla_iterator( + path=config.dataset, batch_size=options['valid_batch_size'], is_train=False): + p_d = p_predictor(q_, q_mask_, l_, l_mask_, a_, a_mask_) + p_ds.extend(p_d) + ys.extend(y_) + right_num, total_num = pred_check(p_ds, ys) + + # judge whether it's necessary to save the parameters + save = False + if float(right_num) / float(total_num) > best_perform: + best_perform = float(right_num) / float(total_num) + save = True + + print '\ttest performance of epoch', i, ':', right_num, '/', total_num, '\t', \ + float(right_num * 10000 / total_num) / 100., '%', '\tbest through:', float(int(best_perform * 10000)) / 100. + + # save parameters if need + if save: + print '\t...saving parameters' + file_name = options['param_path'] + model.name + '_hidden' + str(options['hidden_size']) + '_lrate' + \ + str(options['lrate']) + '_batch' + str(options['batch_size']) + '_epoch' + str(i+1) + \ + '_perform' + str(float(int(best_perform * 10000)) / 100.) + '.pickle' + with open(file_name, 'wb') as f: + new_dict = {} + for k, v in model.params.items(): + new_dict[k] = v.get_value() + cPickle.dump(new_dict, f) + + +if __name__ == '__main__': + run_epoch() diff --git a/pool/shard001/Python/0014474_qmls.py b/pool/shard001/Python/0014474_qmls.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1d8ab287b1e3e61f48aaf372ab648824765b59 --- /dev/null +++ b/pool/shard001/Python/0014474_qmls.py @@ -0,0 +1,53 @@ +############################################################################ +# +# Copyright (C) 2016 The Qt Company Ltd. +# Contact: https://www.qt.io/licensing/ +# +# This file is part of Qt Creator. +# +# Commercial License Usage +# Licensees holding valid commercial Qt licenses may use this file in +# accordance with the commercial license agreement provided with the +# Software or, alternatively, in accordance with the terms contained in +# a written agreement between you and The Qt Company. For licensing terms +# and conditions see https://www.qt.io/terms-conditions. For further +# information use the contact form at https://www.qt.io/contact-us. +# +# GNU General Public License Usage +# Alternatively, this file may be used under the terms of the GNU +# General Public License version 3 as published by the Free Software +# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +# included in the packaging of this file. Please review the following +# information to ensure the GNU General Public License requirements will +# be met: https://www.gnu.org/licenses/gpl-3.0.html. +# +############################################################################ + +source("../../shared/qtcreator.py") + +def startQtCreatorWithNewAppAtQMLEditor(projectDir, projectName, line = None): + startApplication("qtcreator" + SettingsPath) + if not startedWithoutPluginError(): + return None + # create qt quick application + createNewQtQuickApplication(projectDir, projectName) + # open qml file + qmlFile = projectName + ".Resources.qml\.qrc./.main\\.qml" + if not openDocument(qmlFile): + test.fatal("Could not open %s" % qmlFile) + invokeMenuItem("File", "Exit") + return None + # get editor + editorArea = waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget") + # place to line if needed + if line: + # place cursor to component + if not placeCursorToLine(editorArea, line): + invokeMenuItem("File", "Exit") + return None + return editorArea + +def verifyCurrentLine(editorArea, currentLineExpectedText, verifyMessage): + currentLineText = str(lineUnderCursor(editorArea)).strip(); + return test.compare(currentLineText, currentLineExpectedText, verifyMessage) + diff --git a/pool/shard001/Python/0014477_GetBall.py b/pool/shard001/Python/0014477_GetBall.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7833b81a21685bbfdd6fde03982844e643e9ee --- /dev/null +++ b/pool/shard001/Python/0014477_GetBall.py @@ -0,0 +1,39 @@ +# Under MIT licence, see LICENCE.txt +from .Action import Action +#from ...Util.types import AICommand +from RULEngine.Util.Pose import Pose +from RULEngine.Util.geometry import get_angle +from RULEngine.Util.constant import PLAYER_PER_TEAM +from ai.Util.ai_command import AICommand, AICommandType + + +__author__ = 'Robocup ULaval' + + +class GetBall(Action): + """ + Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle + Méthodes : + exec(self): Retourne la pose où se rendre + Attributs (en plus de ceux de Action): + player_id : L'identifiant du joueur + """ + def __init__(self, p_game_state, p_player_id): + """ + :param p_game_state: L'état courant du jeu. + :param p_player_id: Identifiant du joueur qui prend le contrôle de la balle + """ + Action.__init__(self, p_game_state) + assert(isinstance(p_player_id, int)) + assert PLAYER_PER_TEAM >= p_player_id >= 0 + self.player_id = p_player_id + + def exec(self): + """ + Place le robot afin qu'il prenne le contrôle de la balle + :return: Un tuple (Pose, kick) où Pose est la destination du joueur et kick est nul (on ne botte pas) + """ + ball_position = self.game_state.get_ball_position() + destination_orientation = get_angle(self.game_state.get_player_pose(self.player_id).position, ball_position) + destination_pose = {"pose_goal": Pose(ball_position, destination_orientation)} + return AICommand(self.player_id, AICommandType.MOVE, **destination_pose) diff --git a/pool/shard001/Python/0014478_custom_logging.py b/pool/shard001/Python/0014478_custom_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..9a6b45f4910b3c4d842142e9b389c8cee44ddc01 --- /dev/null +++ b/pool/shard001/Python/0014478_custom_logging.py @@ -0,0 +1,177 @@ +# coding=utf-8 +""" +InaSAFE Disaster risk assessment tool developed by AusAid - + **Logging related code.** + +Contact : ole.moller.nielsen@gmail.com + +.. note:: This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + +""" + +__author__ = 'tim@kartoza.com' +__revision__ = '$Format:%H$' +__date__ = '29/01/2011' +__copyright__ = 'Copyright 2012, Australia Indonesia Facility for ' +__copyright__ += 'Disaster Reduction' + +import os +import sys +import logging + +from qgis.core import QgsMessageLog +from PyQt4.QtCore import QSettings + +safe_extras_dir = os.path.abspath( + os.path.join(os.path.dirname(__file__), '..', '..', 'safe_extras')) +if safe_extras_dir not in sys.path: + sys.path.append(safe_extras_dir) +# pylint: disable=F0401 +# noinspection PyUnresolvedReferences,PyPackageRequirements +from raven.handlers.logging import SentryHandler +# noinspection PyUnresolvedReferences,PyPackageRequirements +from raven import Client +# pylint: enable=F0401 + +from safe.common.utilities import log_file_path +from safe.utilities.i18n import tr + +LOGGER = logging.getLogger('InaSAFE') + + +class QgsLogHandler(logging.Handler): + """A logging handler that will log messages to the QGIS logging console.""" + + def __init__(self, level=logging.NOTSET): + logging.Handler.__init__(self) + + def emit(self, record): + """Try to log the message to QGIS if available, otherwise do nothing. + + :param record: logging record containing whatever info needs to be + logged. + """ + try: + # Check logging.LogRecord properties for lots of other goodies + # like line number etc. you can get from the log message. + QgsMessageLog.logMessage(record.getMessage(), 'InaSAFE', 0) + except MemoryError: + message = tr( + 'Due to memory limitations on this machine, InaSAFE can not ' + 'handle the full log') + print message + QgsMessageLog.logMessage(message, 'InaSAFE', 0) + + +def add_logging_handler_once(logger, handler): + """A helper to add a handler to a logger, ensuring there are no duplicates. + + :param logger: Logger that should have a handler added. + :type logger: logging.logger + + :param handler: Handler instance to be added. It will not be added if an + instance of that Handler subclass already exists. + :type handler: logging.Handler + + :returns: True if the logging handler was added, otherwise False. + :rtype: bool + """ + class_name = handler.__class__.__name__ + for logger_handler in logger.handlers: + if logger_handler.__class__.__name__ == class_name: + return False + + logger.addHandler(handler) + return True + + +def setup_logger(logger_name, log_file=None, sentry_url=None): + """Run once when the module is loaded and enable logging. + + :param logger_name: The logger name that we want to set up. + :type logger_name: str + + :param log_file: Optional full path to a file to write logs to. + :type log_file: str + + :param sentry_url: Optional url to sentry api for remote + logging. Defaults to http://c64a83978732474ea751d432ab943a6b: + d9d8e08786174227b9dcd8a4c3f6e9da@sentry.linfiniti.com/5 which is the + sentry project for InaSAFE desktop. + :type sentry_url: str + + Borrowed heavily from this: + http://docs.python.org/howto/logging-cookbook.html + + Now to log a message do:: + + LOGGER.debug('Some debug message') + + .. note:: The file logs are written to the inasafe user tmp dir e.g.: + /tmp/inasafe/23-08-2012/timlinux/logs/inasafe.log + + """ + logger = logging.getLogger(logger_name) + logger.setLevel(logging.DEBUG) + default_handler_level = logging.DEBUG + + # create formatter that will be added to the handlers + formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + + # create syslog handler which logs even debug messages + # (ariel): Make this log to /var/log/safe.log instead of + # /var/log/syslog + # (Tim) Ole and I discussed this - we prefer to log into the + # user's temporary working directory. + inasafe_log_path = log_file_path() + if log_file is None: + file_handler = logging.FileHandler(inasafe_log_path) + else: + file_handler = logging.FileHandler(log_file) + file_handler.setLevel(default_handler_level) + + # create console handler with a higher log level + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.INFO) + + # create a QGIS handler + qgis_handler = QgsLogHandler() + + # Set formatters + file_handler.setFormatter(formatter) + console_handler.setFormatter(formatter) + qgis_handler.setFormatter(formatter) + + # add the handlers to the logger + add_logging_handler_once(logger, file_handler) + add_logging_handler_once(logger, console_handler) + add_logging_handler_once(logger, qgis_handler) + + # Sentry handler - this is optional hence the localised import + # It will only log if pip install raven. If raven is available + # logging messages will be sent to http://sentry.linfiniti.com + # We will log exceptions only there. You need to either: + # * Set env var 'INASAFE_SENTRY=1' present (value can be anything) + # before this will be enabled or sentry is enabled in QSettings + settings = QSettings() + flag = settings.value('inasafe/useSentry', False, type=bool) + env_inasafe_sentry = 'INASAFE_SENTRY' in os.environ + + if env_inasafe_sentry or flag: + if sentry_url is None: + client = Client( + 'http://11b7c9cb73874f97807ebc1934575e92' + ':920cd274632443ccaa868246de202531@sentry.kartoza.com/5') + else: + client = Client(sentry_url) + sentry_handler = SentryHandler(client) + sentry_handler.setFormatter(formatter) + sentry_handler.setLevel(logging.ERROR) + if add_logging_handler_once(logger, sentry_handler): + logger.debug('Sentry logging enabled in safe') + else: + logger.debug('Sentry logging disabled in safe') diff --git a/pool/shard001/Python/0014479_cf_ts_repository.py b/pool/shard001/Python/0014479_cf_ts_repository.py new file mode 100644 index 0000000000000000000000000000000000000000..a60fc9995110af0e4fdfbeffc7d615c20b7d95fe --- /dev/null +++ b/pool/shard001/Python/0014479_cf_ts_repository.py @@ -0,0 +1,101 @@ +from __future__ import absolute_import +from __future__ import print_function +from six import iteritems +from builtins import range + + +from os import path +import numpy as np +from netCDF4 import Dataset +from pyproj import Proj +from pyproj import transform +from shyft import api +from shyft import shyftdata_dir +from .. import interfaces +from shyft.repository.service.ssa_geo_ts_repository import TsRepository +from .time_conversion import convert_netcdf_time + +class CFTsRepositoryError(Exception): + pass + + +class CFTsRepository(TsRepository): + """ + Repository for geo located timeseries stored in netCDF files. + + """ + + def __init__(self, file, var_type): + """ + Construct the netCDF4 dataset reader for data from Arome NWP model, + and initialize data retrieval. + """ + #directory = params['data_dir'] + filename = path.expandvars(file) + self.var_name = var_type + + #if not path.isdir(directory): + # raise CFDataRepositoryError("No such directory '{}'".format(directory)) + if not path.isabs(filename): + # Relative paths will be prepended the data_dir + filename = path.join(shyftdata_dir, filename) + if not path.isfile(filename): + raise CFTsRepositoryError("No such file '{}'".format(filename)) + + self._filename = filename # path.join(directory, filename) + + + def read(self,list_of_ts_id,period): + if not period.valid(): + raise CFTsRepositoryError("period should be valid() of type api.UtcPeriod") + + filename = self._filename + + if not path.isfile(filename): + raise CFTsRepositoryError("File '{}' not found".format(filename)) + with Dataset(filename) as dataset: + return self._get_data_from_dataset(dataset, period, list_of_ts_id) + + def _convert_to_timeseries(self, data, t, ts_id): + ta = api.TimeAxisFixedDeltaT(int(t[0]), int(t[1]) - int(t[0]), len(t)) + tsc = api.TsFactory().create_point_ts + def construct(d): + return tsc(ta.size(), ta.start, ta.delta_t, + api.DoubleVector.FromNdArray(d)) + ts = [construct(data[:,j]) for j in range(data.shape[-1])] + return {k:v for k, v in zip(ts_id,ts)} + + def _get_data_from_dataset(self, dataset, utc_period, ts_id_to_extract): + ts_id_key = [k for (k,v) in dataset.variables.items() if getattr(v,'cf_role',None)=='timeseries_id'][0] + ts_id_in_file = dataset.variables[ts_id_key][:] + + time = dataset.variables.get("time", None) + data = dataset.variables.get(self.var_name, None) + dim_nb_series = [dim.name for dim in dataset.dimensions.values() if dim.name != 'time'][0] + if not all([data, time]): + raise CFTsRepositoryError("Something is wrong with the dataset." + " hydroclim variable or time not found.") + time = convert_netcdf_time(time.units,time) + idx_min = np.searchsorted(time, utc_period.start, side='left') + if time[idx_min] > utc_period.start and idx_min > 0: # important ! ensure data *cover* the requested period, Shyft ts do take care of resolution etc. + idx_min -= 1 # extend range downward so we cover the entire requested period + + idx_max = np.searchsorted(time, utc_period.end, side='right') + + if time[idx_max] < utc_period.end and idx_max +1 < len(time): + idx_max += 1 # extend range upward so that we cover the requested period + + issubset = True if idx_max < len(time) - 1 else False + time_slice = slice(idx_min, idx_max) + + mask = np.array([id in ts_id_to_extract for id in ts_id_in_file]) + + dims = data.dimensions + data_slice = len(data.dimensions)*[slice(None)] + data_slice[dims.index(dim_nb_series)] = mask + data_slice[dims.index("time")] = time_slice + extracted_data = data[data_slice] + if isinstance(extracted_data, np.ma.core.MaskedArray): + extracted_data = extracted_data.filled(np.nan) + + return self._convert_to_timeseries(extracted_data, time[time_slice], ts_id_in_file[mask]) \ No newline at end of file diff --git a/pool/shard001/Python/0014484_views.py b/pool/shard001/Python/0014484_views.py new file mode 100644 index 0000000000000000000000000000000000000000..bef904584db54feb6e4a530f1045b9905402eb21 --- /dev/null +++ b/pool/shard001/Python/0014484_views.py @@ -0,0 +1,30 @@ +import csv + +from django.core.exceptions import PermissionDenied +from django.http import HttpResponse +from openslides.agenda.models import Speaker +from openslides.utils.views import View + + +class CSVExportView(View): + """ + View to export the lists of speakers of all agenda items as csv. + """ + def get(self, request, *args, **kwargs): + if not request.user.has_perm('agenda.can_manage'): + raise PermissionDenied + response = HttpResponse() + response['Content-Disposition'] = 'attachment; filename=list_of_speakers.csv;' + csv_writer = csv.writer(response) + csv_writer.writerow(['Item', 'Person', 'Begin Time', 'End Time']) + for speaker in Speaker.objects.all().order_by('item', 'weight', 'begin_time'): + try: + begin_time = speaker.begin_time.strftime('%d.%m.%Y %H:%M:%S') + except AttributeError: + begin_time = None + try: + end_time = speaker.end_time.strftime('%d.%m.%Y %H:%M:%S') + except AttributeError: + end_time = None + csv_writer.writerow([str(speaker.item), str(speaker.user), begin_time, end_time]) + return response diff --git a/pool/shard001/Python/0014487_invoice_payment_method_specific_input.py b/pool/shard001/Python/0014487_invoice_payment_method_specific_input.py new file mode 100644 index 0000000000000000000000000000000000000000..f4861da575934941cc15e83108584898a3eb5698 --- /dev/null +++ b/pool/shard001/Python/0014487_invoice_payment_method_specific_input.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# +# This class was auto-generated from the API references found at +# https://epayments-api.developer-ingenico.com/s2sapi/v1/ +# +from ingenico.connect.sdk.domain.definitions.abstract_payment_method_specific_input import AbstractPaymentMethodSpecificInput + + +class InvoicePaymentMethodSpecificInput(AbstractPaymentMethodSpecificInput): + + __additional_reference = None + + @property + def additional_reference(self): + """ + | Your (additional) reference identifier for this transaction. Data supplied in this property will also be returned in our report files, allowing you to reconcile the incoming funds. + + Type: str + """ + return self.__additional_reference + + @additional_reference.setter + def additional_reference(self, value): + self.__additional_reference = value + + def to_dictionary(self): + dictionary = super(InvoicePaymentMethodSpecificInput, self).to_dictionary() + if self.additional_reference is not None: + dictionary['additionalReference'] = self.additional_reference + return dictionary + + def from_dictionary(self, dictionary): + super(InvoicePaymentMethodSpecificInput, self).from_dictionary(dictionary) + if 'additionalReference' in dictionary: + self.additional_reference = dictionary['additionalReference'] + return self diff --git a/pool/shard001/Python/0014490_test_fixtures.py b/pool/shard001/Python/0014490_test_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..da9f3c01e38c603256a21285ed1fc10b28011a09 --- /dev/null +++ b/pool/shard001/Python/0014490_test_fixtures.py @@ -0,0 +1,20 @@ +from django.core.management import call_command +from django.test import TestCase +try: + from django.utils.six import StringIO +except ImportError: + # Django < 1.5. No Python 3 support + from StringIO import StringIO + +from ..models import Size + + +class FixturesTestCase(TestCase): + "Ensure that provided fixtures load." + + def test_iab_sizes(self): + "Load IAB size fixture." + out = StringIO() + err = StringIO() + call_command('loaddata', 'iab_sizes.json', stdout=out, stderr=err) + self.assertEqual(Size.objects.all().count(), 27) \ No newline at end of file diff --git a/pool/shard001/Python/0014497_kNN.py b/pool/shard001/Python/0014497_kNN.py new file mode 100644 index 0000000000000000000000000000000000000000..c7299ce466e13cc3bf86eb5ac1e495178ed5f152 --- /dev/null +++ b/pool/shard001/Python/0014497_kNN.py @@ -0,0 +1,61 @@ +from sklearn.neighbors import KNeighborsClassifier +from mnist import load_mnist +import numpy as np +import pygame, random + +screen = pygame.display.set_mode((300,300)) + +draw_on = False +last_pos = (0, 0) +color = (255, 255, 255) +radius = 15 + +def roundline(srf, color, start, end, radius=1): + dx = end[0]-start[0] + dy = end[1]-start[1] + distance = max(abs(dx), abs(dy)) + for i in range(distance): + x = int( start[0]+float(i)/distance*dx) + y = int( start[1]+float(i)/distance*dy) + pygame.display.update(pygame.draw.circle(srf, color, (x, y), radius)) + +try: + while True: + e = pygame.event.wait() + if e.type == pygame.QUIT: + raise StopIteration + if e.type == pygame.MOUSEBUTTONDOWN: + pygame.draw.circle(screen, color, e.pos, radius) + draw_on = True + if e.type == pygame.MOUSEBUTTONUP: + draw_on = False + drawnDigit = pygame.surfarray.array2d(pygame.transform.scale(screen,(28,28))) + if e.type == pygame.MOUSEMOTION: + if draw_on: + pygame.display.update(pygame.draw.circle(screen, color, e.pos, radius)) + roundline(screen, color, e.pos, last_pos, radius) + last_pos = e.pos + #pygame.display.flip() + +except StopIteration: + pass + +pygame.quit() + +drawnDigit = (np.transpose(drawnDigit)/16777215) +print drawnDigit +drawnDigit = drawnDigit.flatten()*255 + +X, y = load_mnist() +tX, ty = load_mnist(dataset="testing") + +y = y[:,0] +ty = ty[:,0] +classif = KNeighborsClassifier(n_neighbors=10,weights='distance') +classif.fit(X,y) +print "Prediction: " + str(classif.predict(drawnDigit)) +wrong = 0; +for i in range(0,len(ty)-1): + if classif.predict(tX[i]) != ty[i]: + wrong = wrong + 1 +print "Test error: " + str((float(wrong)/(len(ty)-1)*100)) + "%" \ No newline at end of file diff --git a/pool/shard001/Python/0014504_cloudsuite_web_search_benchmark.py b/pool/shard001/Python/0014504_cloudsuite_web_search_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..9919cc6b65c4e166926afdc7f005a41c0a94ae1f --- /dev/null +++ b/pool/shard001/Python/0014504_cloudsuite_web_search_benchmark.py @@ -0,0 +1,175 @@ +# Copyright 2015 PerfKitBenchmarker Authors. 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. + +"""Runs the Web Search benchmark of Cloudsuite. + +More info: http://cloudsuite.ch/websearch/ +""" + +import re + +from perfkitbenchmarker import configs +from perfkitbenchmarker import flags +from perfkitbenchmarker import sample +from perfkitbenchmarker import vm_util +from perfkitbenchmarker.linux_packages import docker + +FLAGS = flags.FLAGS + +flags.DEFINE_string('cloudsuite_web_search_server_heap_size', + '3g', + 'Java heap size for Solr server in the usual java format.') +flags.DEFINE_integer('cloudsuite_web_search_ramp_up', + 90, + 'Benchmark ramp up time in seconds.', + lower_bound=1) +flags.DEFINE_integer('cloudsuite_web_search_ramp_down', + 60, + 'Benchmark ramp down time in seconds.', + lower_bound=1) +flags.DEFINE_integer('cloudsuite_web_search_steady_state', + 60, + 'Benchmark steady state time in seconds.', + lower_bound=1) +flags.DEFINE_integer('cloudsuite_web_search_scale', + 50, + 'Number of simulated web search users.', + lower_bound=1) + +BENCHMARK_NAME = 'cloudsuite_web_search' +BENCHMARK_CONFIG = """ +cloudsuite_web_search: + description: > + Run Cloudsuite Web Search benchmark. Specify the number of + clients with --num_vms. + vm_groups: + servers: + vm_spec: *default_single_core + disk_spec: *default_500_gb + clients: + vm_spec: *default_single_core + vm_count: 1 +""" + +DISK_PATH = '/scratch' + + +def GetConfig(user_config): + config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) + if FLAGS['num_vms'].present: + config['vm_groups']['clients']['vm_count'] = FLAGS.num_vms + return config + + +def Prepare(benchmark_spec): + """Install docker. Pull the required images from DockerHub. + + Start Solr index node and client. + + Args: + benchmark_spec: The benchmark specification. Contains all data that is + required to run the benchmark. + """ + servers = benchmark_spec.vm_groups['servers'][0] + clients = benchmark_spec.vm_groups['clients'] + + def PrepareCommon(vm): + if not docker.IsInstalled(vm): + vm.Install('docker') + + def PrepareServer(vm): + PrepareCommon(vm) + server_cmd = ('sudo echo \'DOCKER_OPTS="-g %s"\'' + '| sudo tee /etc/default/docker > /dev/null' % (DISK_PATH)) + stdout, _ = vm.RemoteCommand(server_cmd, should_log=True) + + server_cmd = 'sudo service docker restart' + stdout, _ = vm.RemoteCommand(server_cmd, should_log=True) + + vm.Install('cloudsuite/web-search:server') + + server_cmd = ('sudo docker run -d --net host ' + '--name server cloudsuite/web-search:server %s 1' % + (FLAGS.cloudsuite_web_search_server_heap_size)) + + stdout, _ = servers.RemoteCommand(server_cmd, should_log=True) + + def PrepareClient(vm): + PrepareCommon(vm) + vm.Install('cloudsuite/web-search:client') + + PrepareServer(servers) + + target_arg_tuples = ([(PrepareClient, [vm], {}) for vm in clients]) + vm_util.RunParallelThreads(target_arg_tuples, len(target_arg_tuples)) + + +def Run(benchmark_spec): + """Run the Web Search benchmark. + + Args: + benchmark_spec: The benchmark specification. Contains all data that is + required to run the benchmark. + + Returns: + A list of sample.Sample objects. + """ + clients = benchmark_spec.vm_groups['clients'][0] + servers = benchmark_spec.vm_groups['servers'][0] + + benchmark_cmd = ('sudo docker run --rm --net host --name client ' + 'cloudsuite/web-search:client %s %d %d %d %d ' % + (servers.internal_ip, + FLAGS.cloudsuite_web_search_scale, + FLAGS.cloudsuite_web_search_ramp_up, + FLAGS.cloudsuite_web_search_steady_state, + FLAGS.cloudsuite_web_search_ramp_down)) + stdout, _ = clients.RemoteCommand(benchmark_cmd, should_log=True) + + ops_per_sec = re.findall(r'\(\d+\.?\d*)', stdout) + num_ops_per_sec = float(ops_per_sec[0]) + p90 = re.findall(r'\(\d+\.?\d*)', stdout) + num_p90 = float(p90[0]) + p99 = re.findall(r'\(\d+\.?\d*)', stdout) + num_p99 = float(p99[0]) + + results = [] + results.append(sample.Sample('Operations per second', num_ops_per_sec, + 'ops/s')) + results.append(sample.Sample('90th percentile latency', num_p90, 's')) + results.append(sample.Sample('99th percentile latency', num_p99, 's')) + return results + + +def Cleanup(benchmark_spec): + """Stop and remove docker containers. Remove images. + + Args: + benchmark_spec: The benchmark specification. Contains all data that is + required to run the benchmark. + """ + servers = benchmark_spec.vm_groups['servers'][0] + clients = benchmark_spec.vm_groups['clients'] + + def CleanupClient(vm): + vm.RemoteCommand('sudo docker stop client') + vm.RemoteCommand('sudo docker rm client') + + def CleanupServer(vm): + vm.RemoteCommand('sudo docker stop server') + vm.RemoteCommand('sudo docker rm server') + + target_arg_tuples = ([(CleanupClient, [vm], {}) for vm in clients] + + [(CleanupServer, [servers], {})]) + vm_util.RunParallelThreads(target_arg_tuples, len(target_arg_tuples)) diff --git a/pool/shard001/Python/0014507_test_cmd.py b/pool/shard001/Python/0014507_test_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..eb55b668ebcbe7cb9413e77e83e36e2fa03c6bac --- /dev/null +++ b/pool/shard001/Python/0014507_test_cmd.py @@ -0,0 +1,41 @@ +import os + +from six.moves import configparser +from six.moves import StringIO +import testtools + +from jenkins_jobs import cmd +from tests.base import LoggingFixture +from tests.base import mock + + +class CmdTestsBase(LoggingFixture, testtools.TestCase): + + fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures') + parser = cmd.create_parser() + + def setUp(self): + super(CmdTestsBase, self).setUp() + + # Testing the cmd module can sometimes result in the CacheStorage class + # attempting to create the cache directory multiple times as the tests + # are run in parallel. Stub out the CacheStorage to ensure that each + # test can safely create the cache directory without risk of + # interference. + cache_patch = mock.patch('jenkins_jobs.builder.CacheStorage', + autospec=True) + self.cache_mock = cache_patch.start() + self.addCleanup(cache_patch.stop) + + self.config = configparser.ConfigParser() + self.config.readfp(StringIO(cmd.DEFAULT_CONF)) + + +class CmdTests(CmdTestsBase): + + def test_with_empty_args(self): + """ + User passes no args, should fail with SystemExit + """ + with mock.patch('sys.stderr'): + self.assertRaises(SystemExit, cmd.main, []) diff --git a/pool/shard001/Python/0014513_pass2_bias.py b/pool/shard001/Python/0014513_pass2_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..07a32512b8c881df3fd94484bcd1ae2e65e7ca60 --- /dev/null +++ b/pool/shard001/Python/0014513_pass2_bias.py @@ -0,0 +1,79 @@ +""" + Call bias merge for pass2 + 2016-06-18 +""" + +import os +import MySQLdb + + +def bias_flat(run, mjd, cur) : + """ Generate bias and flat command and call IDL. """ + + if run[6] == "_" : + run_path = run[0:6] + else : + run_path = run[0:7] + + out_bias_path = "/data/red/bok/@/pass2/%s/J%d/" % (run_path, mjd) + out_bias = out_bias_path + "bias.fits" + + if True: #not os.path.isfile(out_bias): + os.system("mkdir -p %s" % out_bias_path) + + sql = ("select FileName from FileBasic where MJD = %d and Telescope = 'B' and Type = 'B'" + % mjd) + print (sql) + cur.execute(sql) + dr_file = cur.fetchall() + fn_lst = "lst2/bias_%d.lst" % mjd + f_lst = open(fn_lst, "w") + for f in dr_file: + f_lst.write(f[0] + "\n") + f_lst.close() + + cmd = "idl bias_shell2.pro -args %s %s" % (fn_lst, out_bias) + print (cmd) + os.system(cmd) + + for fil in ['u', 'v']: + out_flat_path = "/data/red/bok/%s/pass2/%s/J%d/" % (fil, run_path, mjd) + out_flat = out_flat_path + "flat.fits" + #if not os.path.isfile(out_flat): + if True : + os.system("mkdir -p %s" % out_flat_path) + + sql = ("select FileName from FileBasic where MJD = %d and FilterCode = '%s' and Telescope = 'B' and Type = 'F'" + % (mjd, fil)) + print (sql) + cur.execute(sql) + dr_file = cur.fetchall() + fn_lst = "lst2/flat_%s_%d.lst" % (fil, mjd) + f_lst = open(fn_lst, "w") + for f in dr_file: + f_lst.write(f[0] + "\n") + f_lst.close() + + cmd = "idl flat_shell2.pro -args %s %s %s" % (fn_lst, out_bias, out_flat) + print (cmd) + os.system(cmd) + + + +if __name__ == "__main__" : + conn = MySQLdb.connect('localhost', 'uvbys', 'uvbySurvey', 'surveylog') + cur = conn.cursor() + + sql = "select RunID, MJD from ObsNight where substr(NightID, 5, 1)='B' and MJD >= 7331" + cur.execute(sql) + dr_night = cur.fetchall() + + for one_night in dr_night: + run = one_night[0] + mjd = one_night[1] + bias_flat(run, mjd, cur) + + + cur.close() + conn.close() + print ("DONE") diff --git a/pool/shard001/Python/0014518_time_secondary.py b/pool/shard001/Python/0014518_time_secondary.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8e41069d118bee0fe38d6d2713b4fe168c4df7 --- /dev/null +++ b/pool/shard001/Python/0014518_time_secondary.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Licensed under a 3-clause BSD style license - see LICENSE.rst + +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +import sys +if sys.version_info[0] == 3: + xrange = range + + +class TimeSecondary: + def time_factorial(self): + x = 1 + for i in xrange(100): + x *= i + # This is to generate invalid output + sys.stdout.write("X") + + def time_exception(self): + raise RuntimeError() + + +def track_value(): + return 42.0 diff --git a/pool/shard001/Python/0014520_cisco_credentials_v2.py b/pool/shard001/Python/0014520_cisco_credentials_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..3afe965861ab3ff2391bdd060d58a53171acf771 --- /dev/null +++ b/pool/shard001/Python/0014520_cisco_credentials_v2.py @@ -0,0 +1,78 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# +# Copyright 2012 Cisco Systems, 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. +# +# @author: Sumit Naiksatam, Cisco Systems, Inc. + +import logging as LOG + +from neutron.plugins.cisco.common import cisco_constants as const +from neutron.plugins.cisco.common import cisco_exceptions as cexc +from neutron.plugins.cisco.common import config +from neutron.plugins.cisco.db import network_db_v2 as cdb + +LOG.basicConfig(level=LOG.WARN) +LOG.getLogger(const.LOGGER_COMPONENT_NAME) + + +class Store(object): + """Credential Store.""" + + @staticmethod + def initialize(): + dev_dict = config.get_device_dictionary() + for key in dev_dict: + dev_id, dev_ip, dev_key = key + if dev_key == const.USERNAME: + try: + cdb.add_credential( + dev_ip, + dev_dict[dev_id, dev_ip, const.USERNAME], + dev_dict[dev_id, dev_ip, const.PASSWORD], + dev_id) + except cexc.CredentialAlreadyExists: + # We are quietly ignoring this, since it only happens + # if this class module is loaded more than once, in + # which case, the credentials are already populated + pass + + @staticmethod + def put_credential(cred_name, username, password): + """Set the username and password.""" + cdb.add_credential(cred_name, username, password) + + @staticmethod + def get_username(cred_name): + """Get the username.""" + credential = cdb.get_credential_name(cred_name) + return credential[const.CREDENTIAL_USERNAME] + + @staticmethod + def get_password(cred_name): + """Get the password.""" + credential = cdb.get_credential_name(cred_name) + return credential[const.CREDENTIAL_PASSWORD] + + @staticmethod + def get_credential(cred_name): + """Get the username and password.""" + cdb.get_credential_name(cred_name) + return {const.USERNAME: const.CREDENTIAL_USERNAME, + const.PASSWORD: const.CREDENTIAL_PASSWORD} + + @staticmethod + def delete_credential(cred_name): + """Delete a credential.""" + cdb.remove_credential(cred_name) diff --git a/pool/shard001/Python/0014522_flavors.py b/pool/shard001/Python/0014522_flavors.py new file mode 100644 index 0000000000000000000000000000000000000000..f5ef3b4f432ff18625fb798bd44b209f43dfd0d2 --- /dev/null +++ b/pool/shard001/Python/0014522_flavors.py @@ -0,0 +1,32 @@ +from openstackx.api import base + + +class Flavor(base.Resource): + """ + A flavor is an available hardware configuration for a server. + """ + def __repr__(self): + return "" % self.name + +class FlavorManager(base.ManagerWithFind): + """ + Manage :class:`Flavor` resources. + """ + resource_class = Flavor + + def list(self): + """ + Get a list of all flavors. + + :rtype: list of :class:`Flavor`. + """ + return self._list("/extras/flavors", "flavors") + + def get(self, flavor): + """ + Get a specific flavor. + + :param flavor: The ID of the :class:`Flavor` to get. + :rtype: :class:`Flavor` + """ + return self._get("/extras/flavors/%s" % base.getid(flavor), "flavor") diff --git a/pool/shard001/Python/0014523_bz_backend.py b/pool/shard001/Python/0014523_bz_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..0a458f81c94443c9da5c381b9e3a3fcc6ce91d02 --- /dev/null +++ b/pool/shard001/Python/0014523_bz_backend.py @@ -0,0 +1,24 @@ +#!/usr/bin/python + +import sys +sys.path.insert(0,"../src") +import logging + +import protocol.backend as backend + +def main(): + logging.basicConfig(level=logging.DEBUG) + + bb = backend.BluetoothBackend() + bb.login() + + contacts = bb.get_contacts() + for address, deviceclass, name in contacts: + print address, name + major, minor, services = backend.parse_device_class(deviceclass) + print str(major), ":", str(minor), [str(service) for service in services] + + bb.logout() + +if __name__ == "__main__": + main() diff --git a/pool/shard001/Python/0014526_iscsi.py b/pool/shard001/Python/0014526_iscsi.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cf80059d9148925c541b3cc0c4f9815f5a5b20 --- /dev/null +++ b/pool/shard001/Python/0014526_iscsi.py @@ -0,0 +1,65 @@ +""" +Copyright (c) 2012-2013 RockStor, Inc. +This file is part of RockStor. + +RockStor is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +RockStor is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + +TGTADM_BIN = '/usr/sbin/tgtadm' +DD_BIN = '/bin/dd' + +from osi import run_command + + +def create_target_device(tid, tname): + cmd = [TGTADM_BIN, '--lld', 'iscsi', '--mode', 'target', '--op', 'new', + '--tid', tid, '--targetname', tname] + return run_command(cmd) + +def add_logical_unit(tid, lun, dev_name): + cmd = [TGTADM_BIN, '--lld', 'iscsi', '--mode', 'logicalunit', '--op', + 'new', '--tid', tid, '--lun', lun, '-b', dev_name] + return run_command(cmd) + +def ip_restrict(tid): + """ + no restrictions at all + """ + cmd = [TGTADM_BIN, '--lld', 'iscsi', '--mode', 'target', '--op', 'bind', + '--tid', tid, '-I', 'ALL'] + return run_command(cmd) + +def create_lun_file(dev_name, size): + """ + size in MB + """ + of = ('of=%s' % dev_name) + count = ('count=%d' % size) + cmd = [DD_BIN, 'if=/dev/zero', of, 'bs=1M', count] + return run_command(cmd) + +def export_iscsi(tid, tname, lun, dev_name, size): + """ + main method that does everything to a share to make it available as a iscsi + device. this should be called from the api view + + 1. create the dev_name file with the given size using dd + 2. create target device + 3. add logical unit + 4. authentication?? + """ + create_lun_file(dev_name, size) + create_target_device(tid, tname) + add_logical_unit(tid, lun, dev_name) + ip_restrict(tid) diff --git a/pool/shard001/Python/0014527_config.py b/pool/shard001/Python/0014527_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a2194898963d3d4bd05634d5888a69e8052658b4 --- /dev/null +++ b/pool/shard001/Python/0014527_config.py @@ -0,0 +1,225 @@ +# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ +# Copyright (c) 2011 Chris Moyer http://coredumped.org/ +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, dis- +# tribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the fol- +# lowing conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- +# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +import os +import re +import warnings + +import boto + +from boto.compat import expanduser, ConfigParser, StringIO + + +# By default we use two locations for the boto configurations, +# /etc/boto.cfg and ~/.boto (which works on Windows and Unix). +BotoConfigPath = '/etc/boto.cfg' +BotoConfigLocations = [BotoConfigPath] +UserConfigPath = os.path.join(expanduser('~'), '.boto') +BotoConfigLocations.append(UserConfigPath) + +# If there's a BOTO_CONFIG variable set, we load ONLY +# that variable +if 'BOTO_CONFIG' in os.environ: + BotoConfigLocations = [expanduser(os.environ['BOTO_CONFIG'])] + +# If there's a BOTO_PATH variable set, we use anything there +# as the current configuration locations, split with os.pathsep. +elif 'BOTO_PATH' in os.environ: + BotoConfigLocations = [] + for path in os.environ['BOTO_PATH'].split(os.pathsep): + BotoConfigLocations.append(expanduser(path)) + + +class Config(ConfigParser): + + def __init__(self, path=None, fp=None, do_load=True): + # We don't use ``super`` here, because ``ConfigParser`` still uses + # old-style classes. + ConfigParser.__init__(self, {'working_dir': '/mnt/pyami', + 'debug': '0'}) + if do_load: + if path: + self.load_from_path(path) + elif fp: + self.readfp(fp) + else: + self.read(BotoConfigLocations) + if "AWS_CREDENTIAL_FILE" in os.environ: + full_path = expanduser(os.environ['AWS_CREDENTIAL_FILE']) + try: + self.load_credential_file(full_path) + except IOError: + warnings.warn('Unable to load AWS_CREDENTIAL_FILE (%s)' % full_path) + + def load_credential_file(self, path): + """Load a credential file as is setup like the Java utilities""" + c_data = StringIO() + c_data.write("[Credentials]\n") + for line in open(path, "r").readlines(): + c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replace("AWSSecretKey", "aws_secret_access_key")) + c_data.seek(0) + self.readfp(c_data) + + def load_from_path(self, path): + file = open(path) + for line in file.readlines(): + match = re.match("^#import[\s\t]*([^\s^\t]*)[\s\t]*$", line) + if match: + extended_file = match.group(1) + (dir, file) = os.path.split(path) + self.load_from_path(os.path.join(dir, extended_file)) + self.read(path) + + def save_option(self, path, section, option, value): + """ + Write the specified Section.Option to the config file specified by path. + Replace any previous value. If the path doesn't exist, create it. + Also add the option the the in-memory config. + """ + config = ConfigParser() + config.read(path) + if not config.has_section(section): + config.add_section(section) + config.set(section, option, value) + fp = open(path, 'w') + config.write(fp) + fp.close() + if not self.has_section(section): + self.add_section(section) + self.set(section, option, value) + + def save_user_option(self, section, option, value): + self.save_option(UserConfigPath, section, option, value) + + def save_system_option(self, section, option, value): + self.save_option(BotoConfigPath, section, option, value) + + def get_instance(self, name, default=None): + try: + val = self.get('Instance', name) + except: + val = default + return val + + def get_user(self, name, default=None): + try: + val = self.get('User', name) + except: + val = default + return val + + def getint_user(self, name, default=0): + try: + val = self.getint('User', name) + except: + val = default + return val + + def get_value(self, section, name, default=None): + return self.get(section, name, default) + + def get(self, section, name, default=None): + try: + val = ConfigParser.get(self, section, name) + except: + val = default + return val + + def getint(self, section, name, default=0): + try: + val = ConfigParser.getint(self, section, name) + except: + val = int(default) + return val + + def getfloat(self, section, name, default=0.0): + try: + val = ConfigParser.getfloat(self, section, name) + except: + val = float(default) + return val + + def getbool(self, section, name, default=False): + if self.has_option(section, name): + val = self.get(section, name) + if val.lower() == 'true': + val = True + else: + val = False + else: + val = default + return val + + def setbool(self, section, name, value): + if value: + self.set(section, name, 'true') + else: + self.set(section, name, 'false') + + def dump(self): + s = StringIO() + self.write(s) + print(s.getvalue()) + + def dump_safe(self, fp=None): + if not fp: + fp = StringIO() + for section in self.sections(): + fp.write('[%s]\n' % section) + for option in self.options(section): + if option == 'aws_secret_access_key': + fp.write('%s = xxxxxxxxxxxxxxxxxx\n' % option) + else: + fp.write('%s = %s\n' % (option, self.get(section, option))) + + def dump_to_sdb(self, domain_name, item_name): + from boto.compat import json + sdb = boto.connect_sdb() + domain = sdb.lookup(domain_name) + if not domain: + domain = sdb.create_domain(domain_name) + item = domain.new_item(item_name) + item.active = False + for section in self.sections(): + d = {} + for option in self.options(section): + d[option] = self.get(section, option) + item[section] = json.dumps(d) + item.save() + + def load_from_sdb(self, domain_name, item_name): + from boto.compat import json + sdb = boto.connect_sdb() + domain = sdb.lookup(domain_name) + item = domain.get_item(item_name) + for section in item.keys(): + if not self.has_section(section): + self.add_section(section) + d = json.loads(item[section]) + for attr_name in d.keys(): + attr_value = d[attr_name] + if attr_value is None: + attr_value = 'None' + if isinstance(attr_value, bool): + self.setbool(section, attr_name, attr_value) + else: + self.set(section, attr_name, attr_value) diff --git a/pool/shard001/Python/0014536_test_api_REST.py b/pool/shard001/Python/0014536_test_api_REST.py new file mode 100644 index 0000000000000000000000000000000000000000..97a58d2569ca7e6fbaebdc90a21b885a89859bd2 --- /dev/null +++ b/pool/shard001/Python/0014536_test_api_REST.py @@ -0,0 +1,84 @@ +""" +Use ``py.test -m apirest`` to run this test +""" +import pytest +import json +import urllib2 + + +@pytest.fixture() +def hostname(): + hostname = 'http://api.meezio.eu:5000/' + return hostname + + +@pytest.mark.apirest +@pytest.mark.all +def test_add_new_rooms(hostname): + url = "{}{}".format(hostname, "room/") + + request = urllib2.Request(url, json.dumps({'batiment': 1, 'numero': 1, 'nom': 'My Room'}), {'Content-Type': 'application/json'}) + response = urllib2.urlopen(request) + assert response.getcode() == 201 + response.close() + + try: + request = urllib2.Request(url, json.dumps({'batiment': 1, 'numero': 2, 'name': 'My Failed Room'}), {'Content-Type': 'application/json'}) + response = urllib2.urlopen(request) + except urllib2.HTTPError, error: + assert error.getcode() == 400 + assert error.read() == """{\n "msg": "Bad attribute : 'name'"\n}""" + response.close() + + with open("tests/room.bin") as f: + data = f.read() + request3 = urllib2.Request(url, data, {'Content-Type': 'multipart/form-data; boundary=01ead4a5-7a67-4703-ad02-589886e00923'}) + response3 = urllib2.urlopen(request3) + assert response3.getcode() == 201 + response3.close() + + +@pytest.mark.apirest +@pytest.mark.all +def test_update_a_room(hostname): + url = "{}{}".format(hostname, "room/1/1/") + + request = urllib2.Request(url, json.dumps({'nom': 'My updated Room'}), {'Content-Type': 'application/json'}) + request.get_method = lambda: 'PATCH' + response = urllib2.urlopen(request) + assert response.getcode() == 204 + response.close() + + +@pytest.mark.apirest +@pytest.mark.all +def test_get_a_room(hostname): + url = "{}{}".format(hostname, "room/1/1/") + + request = urllib2.Request(url) + response = urllib2.urlopen(request) + assert response.read() == """{"batiment": 1, "contrat": null, "minibar": false, "nom": "My updated Room", "numero": 1, "ready": "14:45", "score": 3.14}""" + assert response.getcode() == 200 + response.close() + + +@pytest.mark.apirest +@pytest.mark.all +def test_delete_a_room(hostname): + url = "{}{}".format(hostname, "room/1/1/") + + request = urllib2.Request(url) + request.get_method = lambda: 'DELETE' + response = urllib2.urlopen(request) + assert response.getcode() == 204 + response.close() + + +""" + with open("tests/france.bin") as f: + data = f.read() + content_type = 'multipart/form-data; boundary=01ead4a5-7a67-4703-ad02-589886e00923' + rv = app.post('/monplug/country', data=data, content_type=content_type, base_url=hostname) + assert rv.status_code == 201 + +""" diff --git a/pool/shard001/Python/0014541_eagle_gateway.py b/pool/shard001/Python/0014541_eagle_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..2a529ffc849ba5adcf791ecab306a57b0f69f6ce --- /dev/null +++ b/pool/shard001/Python/0014541_eagle_gateway.py @@ -0,0 +1,74 @@ +''' +Copyright (c) 2016, Emmanuel Levijarvi +All rights reserved. +License BSD 2-Clause +''' +import logging +import datetime +from iotrelay import Reading +from meter_reader import Gateway, GatewayError + +logger = logging.getLogger(__name__) +__version__ = "1.0.2" + +POLL_FREQUENCY = 9 +SUMM_POLL_FREQUENCY = 600 + + +class Poll(object): + def __init__(self, config): + self.config = config + self.series_key = config['series key'] + self.gateway = Gateway(config['address']) + self.gateway.timeout = float(config['timeout']) + # poll_frequency: seconds between readings + poll_frequency = int(config.get('poll frequency', POLL_FREQUENCY)) + summ_poll_frequency = int(config.get('summation poll frequency', + SUMM_POLL_FREQUENCY)) + self.summ_delta = datetime.timedelta(seconds=summ_poll_frequency) + self.delta = datetime.timedelta(seconds=poll_frequency) + self.next_reading_time = datetime.datetime.now() + self.summ_next_reading_time = datetime.datetime.now() + self.last_timestamp = None + self.last_summation = None + + def get_readings(self): + summation = self.get_summation() + power = self.get_power() + if summation is None: + return power + summation.append(power) + return summation + + def get_power(self): + if datetime.datetime.now() < self.next_reading_time: + return + try: + timestamp, demand = self.gateway.get_instantaneous_demand() + logger.debug(timestamp, demand) + except GatewayError as e: + logger.error(e) + self.next_reading_time = datetime.datetime.now() + self.delta / 2 + return + if self.last_timestamp is None or timestamp != self.last_timestamp: + logger.info("{0!s}, {1!s}".format(timestamp, demand)) + self.last_timestamp = timestamp + self.next_reading_time = datetime.datetime.now() + self.delta + return Reading('power', demand, timestamp, self.series_key) + else: + logger.warning('duplicate reading') + self.next_reading_time = datetime.datetime.now() + self.delta / 2 + + def get_summation(self): + if datetime.datetime.now() < self.summ_next_reading_time: + return + try: + summations = self.gateway.run_command(name='get_summation_values') + except GatewayError as e: + logger.error(e) + self.sum_next_reading_time = datetime.datetime.now() + self.summ_delta + return [Reading('power', s['Value'], s['TimeStamp'], 'summation') + for s in summations] + + def __str__(self): + return 'eagle gateway. next reading {}.'.format(self.next_reading_time) diff --git a/pool/shard001/Python/0014547_edit_structural_analysis_model.py b/pool/shard001/Python/0014547_edit_structural_analysis_model.py new file mode 100644 index 0000000000000000000000000000000000000000..59cb03c1b204b8adecf71594f300258748221b35 --- /dev/null +++ b/pool/shard001/Python/0014547_edit_structural_analysis_model.py @@ -0,0 +1,30 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IfcOpenShell is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with IfcOpenShell. If not, see . + + +class Usecase: + def __init__(self, file, **settings): + self.file = file + self.settings = {"structural_analysis_model": None, "attributes": {}} + for key, value in settings.items(): + self.settings[key] = value + + def execute(self): + for name, value in self.settings["attributes"].items(): + setattr(self.settings["structural_analysis_model"], name, value) + return self.settings["structural_analysis_model"] diff --git a/pool/shard001/Python/0014557_release_branch_pull_request_handler.py b/pool/shard001/Python/0014557_release_branch_pull_request_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..76c503b9e685867ed05efeae1f5dc0cbbbdbd7a4 --- /dev/null +++ b/pool/shard001/Python/0014557_release_branch_pull_request_handler.py @@ -0,0 +1,49 @@ +from .handler import Handler +from .pull_request_event import GetBaseBranch, GetPullRequest, GetTitle, GetRepo +from gh import ReleaseBranchFor, ParseCommitMessage + +format_message = ('Features cannot be merged into release branches. The following commits ' + + 'are not tagged as one of "{}":\n\n{}\n\n' + + 'Read more about [commit conventions](https://www.spinnaker.io/community/contributing/submitting/#commit-message-conventions) ' + + 'and [patch releases](https://www.spinnaker.io/community/releases/release-cadence/#patching-the-release-candidate) here.') + +class ReleaseBranchPullRequestHandler(Handler): + def __init__(self): + super().__init__() + self.omit_repos = self.config.get('omit_repos', []) + self.allowed_types = self.config.get( + 'allowed_types', + ['fix', 'chore', 'docs', 'test'] + ) + + def handles(self, event): + return (event.type == 'PullRequestEvent' + and event.payload.get('action') == 'opened' + and ReleaseBranchFor(GetBaseBranch(event)) != None) + + def handle(self, g, event): + repo = GetRepo(event) + if repo in self.omit_repos: + self.logging.info('Skipping {} because it\'s in omitted repo {}'.format(event, repo)) + return + + pull_request = GetPullRequest(g, event) + if pull_request is None: + self.logging.warn('Unable to determine PR that created {}'.format(event)) + return + + commits = pull_request.get_commits() + bad_commits = [] + + for commit in commits: + message = ParseCommitMessage(commit.commit.message) + if message is None or message.get('type') not in self.allowed_types: + bad_commits.append(commit.commit) + + if len(bad_commits) > 0: + pull_request.create_issue_comment(format_message.format( + ', '.join(self.allowed_types), + '\n\n'.join(map(lambda c: '{}: {}'.format(c.sha, c.message), bad_commits)) + )) + +ReleaseBranchPullRequestHandler() diff --git a/pool/shard001/Python/0014565_vtep.py b/pool/shard001/Python/0014565_vtep.py new file mode 100644 index 0000000000000000000000000000000000000000..748a911d0b0ec29b9d5f314402aec0e82e260412 --- /dev/null +++ b/pool/shard001/Python/0014565_vtep.py @@ -0,0 +1,84 @@ +# Copyright (c) 2014 Midokura SARL, All Rights Reserved. +# 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 midonetclient.resource_base import ResourceBase +from midonetclient import vendor_media_type +from midonetclient.vtep_binding import VtepBinding + +class Vtep(ResourceBase): + + media_type = vendor_media_type.APPLICATION_VTEP_JSON + + def __init__(self, uri, dto, auth): + super(Vtep, self).__init__(uri, dto, auth) + + def get_name(self): + return self.dto['name'] + + def get_description(self): + return self.dto['description'] + + def get_management_ip(self): + return self.dto['managementIp'] + + def get_management_port(self): + return self.dto['managementPort'] + + def get_tunnel_ip_addresses(self): + return self.dto['tunnelIpAddrs'] + + def get_connection_state(self): + return self.dto['connectionState'] + + def get_tunnel_zone_id(self): + return self.dto['tunnelZoneId'] + + def description(self, desc): + self.dto['description'] = desc + return self + + def management_ip(self, ip_addr): + self.dto['managementIp'] = ip_addr + return self + + def management_port(self, port): + self.dto['managementPort'] = port + return self + + def tunnel_ip_addresses(self, addresses): + self.dto['tunnelIpAddrs'] = addresses + return self + + def connection_state(self, conn_state): + self.dto['connectionState'] = conn_state + return self + + def tunnel_zone_id(self, tunnel_zone_id): + self.dto['tunnelZoneId'] = tunnel_zone_id + return self + + def get_bindings(self): + query = {} + headers = {'Accept': + vendor_media_type.APPLICATION_VTEP_BINDING_COLLECTION_JSON} + return self.get_children(self.dto['bindings'], + query, + headers, + VtepBinding) + + def add_binding(self): + return VtepBinding(self.dto['bindings'], + {'mgmtIp': self.get_management_ip()}, + self.auth) diff --git a/pool/shard001/Python/0014572_manage.py b/pool/shard001/Python/0014572_manage.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e6c26a1b46777b8378ef2c7a17892330038704 --- /dev/null +++ b/pool/shard001/Python/0014572_manage.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import os +from flask_script import Manager, Shell, Server +from flask_script.commands import Clean, ShowUrls + +from flasktaggingtest.app import create_app +from flasktaggingtest.settings import DevConfig, ProdConfig + +if os.environ.get("FLASKTAGGINGTEST_ENV") == 'prod': + app = create_app(ProdConfig) +else: + app = create_app(DevConfig) + +HERE = os.path.abspath(os.path.dirname(__file__)) +TEST_PATH = os.path.join(HERE, 'tests') + +manager = Manager(app) + + +def _make_context(): + """Return context dict for a shell session so you can access + app by default. + """ + return {'app': app} + + +@manager.command +def test(): + """Run the tests.""" + import pytest + exit_code = pytest.main([TEST_PATH, '--verbose']) + return exit_code + + +manager.add_command('server', Server()) +manager.add_command('shell', Shell(make_context=_make_context)) +manager.add_command("urls", ShowUrls()) +manager.add_command("clean", Clean()) + +if __name__ == '__main__': + manager.run() diff --git a/pool/shard001/Python/0014575_winsrv.py b/pool/shard001/Python/0014575_winsrv.py new file mode 100644 index 0000000000000000000000000000000000000000..5c300ae44813023c802bea5e91e2f38fb4a744eb --- /dev/null +++ b/pool/shard001/Python/0014575_winsrv.py @@ -0,0 +1,42 @@ +import io +import os +import sys +import socket + +# redirecting stdout to send it through the socket +old_stdout = sys.stdout +sys.stdout = mystdout = io.StringIO() + +# some constants +HOST = '' # Symbolic name meaning all available interfaces +PORT = 50007 # Arbitrary non-privileged port +BUFFER = 2048 +BIGBUFFER = 8192 + +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +s.bind((HOST, PORT)) + +print("Started on localhost", PORT, file=old_stdout) + +while True: + # receiving + data, addr = s.recvfrom(BUFFER) + print("Received {", data.decode(), "} from L-o-W", file=old_stdout) + # executing request on windows + ret = os.popen(data.decode()).read() + ret = mystdout.getvalue() + "\n" + str(ret) + # sending process + try: + s.sendto(ret.encode()[:BIGBUFFER], addr) + while len(ret.encode()) > BIGBUFFER: # if len(ret) <= 8192, we skip and send 0 ___ + s.sendto(str(1).encode(), addr) # return code "it is not finished" | + ret = ret[BIGBUFFER:] # truncate the message | + s.sendto(ret.encode[:BIGBUFFER], addr) # send the next part of it | + s.sendto(str(0).encode(), addr) # return code "okay" /___________________| + except ConnectionAbortedError: + print("Connection was reset") + # exit(1) + + mystdout.truncate(0) + +sys.stdout = old_stdout diff --git a/pool/shard001/Python/0014576_test_agreement.py b/pool/shard001/Python/0014576_test_agreement.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a397ab235c2ea3022ed31358bc0a60272972cb --- /dev/null +++ b/pool/shard001/Python/0014576_test_agreement.py @@ -0,0 +1,43 @@ +# +# Copyright © 2012–2022 Michal Čihař +# +# This file is part of Weblate +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +"""Test for contributor agreement management.""" + +from weblate.trans.models import ContributorAgreement +from weblate.trans.tests.test_views import FixtureTestCase + + +class AgreementTest(FixtureTestCase): + def test_basic(self): + self.assertFalse( + ContributorAgreement.objects.has_agreed(self.user, self.component) + ) + ContributorAgreement.objects.create(self.user, self.component) + self.assertTrue( + ContributorAgreement.objects.has_agreed(self.user, self.component) + ) + + def test_perms(self): + self.assertTrue(self.user.has_perm("unit.edit", self.component)) + self.component.agreement = "CLA" + self.user.clear_cache() + self.assertFalse(self.user.has_perm("unit.edit", self.component)) + ContributorAgreement.objects.create(self.user, self.component) + self.user.clear_cache() + self.assertTrue(self.user.has_perm("unit.edit", self.component)) diff --git a/pool/shard001/Python/0014581_timer.py b/pool/shard001/Python/0014581_timer.py new file mode 100644 index 0000000000000000000000000000000000000000..d5807fe12cf7ea9d3c9a61746b36a65e347a5a8e --- /dev/null +++ b/pool/shard001/Python/0014581_timer.py @@ -0,0 +1,52 @@ +# Miro - an RSS based video player application +# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 +# Participatory Culture Foundation +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# +# In addition, as a special exception, the copyright holders give +# permission to link the code of portions of this program with the OpenSSL +# library. +# +# You must obey the GNU General Public License in all respects for all of +# the code used other than OpenSSL. If you modify file(s) with this +# exception, you may extend this exception to your version of the file(s), +# but you are not obligated to do so. If you do not wish to do so, delete +# this exception statement from your version. If you delete this exception +# statement from all source files in the program, then also delete it here. + +"""miro.plat.frontends.widgets.timer -- Handle timeouts on OS X""" + +from Foundation import * +from objc import nil, YES, NO + +from miro import trapcall + +class Timeout(NSObject): + def initWithFunc_args_kwargs_(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + return self + + def run_(self, info): + trapcall.trap_call('Timeout', self.func, *self.args, **self.kwargs) + +def add(timeout, func, *args, **kwargs): + timeout_obj = Timeout.alloc().initWithFunc_args_kwargs_(func, args, kwargs) + return NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(timeout, timeout_obj, timeout_obj.run_, nil, NO) + +def cancel(timeout): + timeout.invalidate() diff --git a/pool/shard001/Python/0014586_default_webserver_config.py b/pool/shard001/Python/0014586_default_webserver_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8a6bb1fb613186e8ff6a5043e2ca18f42c81bd --- /dev/null +++ b/pool/shard001/Python/0014586_default_webserver_config.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +"""Default configuration for the Airflow webserver""" +import os +from flask_appbuilder.security.manager import AUTH_DB +# from flask_appbuilder.security.manager import AUTH_LDAP +# from flask_appbuilder.security.manager import AUTH_OAUTH +# from flask_appbuilder.security.manager import AUTH_OID +# from flask_appbuilder.security.manager import AUTH_REMOTE_USER + +from airflow.configuration import conf + +basedir = os.path.abspath(os.path.dirname(__file__)) + +# The SQLAlchemy connection string. +SQLALCHEMY_DATABASE_URI = conf.get('core', 'SQL_ALCHEMY_CONN') + +# Flask-WTF flag for CSRF +CSRF_ENABLED = True + +# ---------------------------------------------------- +# AUTHENTICATION CONFIG +# ---------------------------------------------------- +# For details on how to set up each of the following authentication, see +# http://flask-appbuilder.readthedocs.io/en/latest/security.html# authentication-methods +# for details. + +# The authentication type +# AUTH_OID : Is for OpenID +# AUTH_DB : Is for database +# AUTH_LDAP : Is for LDAP +# AUTH_REMOTE_USER : Is for using REMOTE_USER from web server +# AUTH_OAUTH : Is for OAuth +AUTH_TYPE = AUTH_DB + +# Uncomment to setup Full admin role name +# AUTH_ROLE_ADMIN = 'Admin' + +# Uncomment to setup Public role name, no authentication needed +# AUTH_ROLE_PUBLIC = 'Public' + +# Will allow user self registration +# AUTH_USER_REGISTRATION = True + +# The default user self registration role +# AUTH_USER_REGISTRATION_ROLE = "Public" + +# When using OAuth Auth, uncomment to setup provider(s) info +# Google OAuth example: +# OAUTH_PROVIDERS = [{ +# 'name':'google', +# 'whitelist': ['@YOU_COMPANY_DOMAIN'], # optional +# 'token_key':'access_token', +# 'icon':'fa-google', +# 'remote_app': { +# 'base_url':'https://www.googleapis.com/oauth2/v2/', +# 'request_token_params':{ +# 'scope': 'email profile' +# }, +# 'access_token_url':'https://accounts.google.com/o/oauth2/token', +# 'authorize_url':'https://accounts.google.com/o/oauth2/auth', +# 'request_token_url': None, +# 'consumer_key': CONSUMER_KEY, +# 'consumer_secret': SECRET_KEY, +# } +# }] + +# When using LDAP Auth, setup the ldap server +# AUTH_LDAP_SERVER = "ldap://ldapserver.new" + +# When using OpenID Auth, uncomment to setup OpenID providers. +# example for OpenID authentication +# OPENID_PROVIDERS = [ +# { 'name': 'Yahoo', 'url': 'https://me.yahoo.com' }, +# { 'name': 'AOL', 'url': 'http://openid.aol.com/' }, +# { 'name': 'Flickr', 'url': 'http://www.flickr.com/' }, +# { 'name': 'MyOpenID', 'url': 'https://www.myopenid.com' }] + +# ---------------------------------------------------- +# Theme CONFIG +# ---------------------------------------------------- +# Flask App Builder comes up with a number of predefined themes +# that you can use for Apache Airflow. +# http://flask-appbuilder.readthedocs.io/en/latest/customizing.html#changing-themes +# Please make sure to remove "navbar_color" configuration from airflow.cfg +# in order to fully utilize the theme. (or use that property in conjunction with theme) +# APP_THEME = "bootstrap-theme.css" # default bootstrap +# APP_THEME = "amelia.css" +# APP_THEME = "cerulean.css" +# APP_THEME = "cosmo.css" +# APP_THEME = "cyborg.css" +# APP_THEME = "darkly.css" +# APP_THEME = "flatly.css" +# APP_THEME = "journal.css" +# APP_THEME = "lumen.css" +# APP_THEME = "paper.css" +# APP_THEME = "readable.css" +# APP_THEME = "sandstone.css" +# APP_THEME = "simplex.css" +# APP_THEME = "slate.css" +# APP_THEME = "solar.css" +# APP_THEME = "spacelab.css" +# APP_THEME = "superhero.css" +# APP_THEME = "united.css" +# APP_THEME = "yeti.css" diff --git a/pool/shard001/Python/0014587_Arduino.py b/pool/shard001/Python/0014587_Arduino.py new file mode 100644 index 0000000000000000000000000000000000000000..f775b997b3475935390c99168c02ac6d888ce4b2 --- /dev/null +++ b/pool/shard001/Python/0014587_Arduino.py @@ -0,0 +1,176 @@ +import socket + +import demistomock as demisto # noqa: F401 +from CommonServerPython import * # noqa: F401 + +''' CONSTANTS ''' + +''' CLIENT CLASS ''' + + +class Server(): + def __init__(self, host, port): + self.host = host + self.port = port + self.validate() + + def validate(self): + is_ip = False + try: + socket.inet_aton(self.host) + is_ip = True + except socket.error: + is_ip = False + if not is_ip: + try: + self.host = socket.gethostbyname(self.host) + except Exception as err: + return_error(f"{self.host} is not a valid IP nor does not resolve to an IP - {err}") + + def test_connect(self): + try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((self.host, self.port)) + s.sendall(b"test") + data = s.recv(1024) + if data.decode().startswith("Response"): + return 'ok' + else: + return "There was an issue. Please check your Arduino code" + except Exception as err: + return_error(err) + + def send_data(self, value): + data = None + try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((self.host, self.port)) + s.sendall(value.encode()) + data = s.recv(1024) + except Exception as err: + return_error(err) + return data + + +''' HELPER FUNCTIONS ''' + +''' COMMAND FUNCTIONS ''' + + +def test_module(server: Server) -> str: + return server.test_connect() + + +def arduino_set_pin_command(server: Server, args: dict) -> CommandResults: + pin_type = args.get('pin_type') + prefix = "Arduino.DigitalPins" if pin_type == "digital" else "Arduino.AnalogPins" + pin_number = args.get('pin_number') + try: + pin_number = int(pin_number) # type: ignore + except Exception as err: + return_error(f"'Pin number' must be a number - {err}") + value = args.get('value') + try: + value = int(value) # type: ignore + except Exception as err: + return_error(f"'Value' must be a number - {err}") + result = int(server.send_data(f"set:{pin_type}:{pin_number},{value}")) + results = [{ + "PinType": "Digital" if pin_type == "digital" else "Analog", + "PinNumber": pin_number, + "PinValue": result + }] + command_results = CommandResults( + outputs_prefix=prefix, + outputs_key_field=['PinNumber', 'PinType'], + outputs=results, + readable_output=tableToMarkdown(f"Set pin {pin_number} on {server.host}({server.port}):", results) + ) + return command_results + + +def arduino_get_pin_command(server: Server, args: dict) -> CommandResults: + pin_type = args.get('pin_type') + prefix = "Arduino.DigitalPins" if pin_type == "digital" else "Arduino.AnalogPins" + pin_number = args.get('pin_number') + try: + pin_number = int(pin_number) # type: ignore + except Exception as err: + return_error(f"'Pin number' must be a number - {err}") + result: int = int(server.send_data(f"get:{pin_type}:{pin_number}")) + results = [{ + "PinType": "Digital" if pin_type == "digital" else "Analog", + "PinNumber": pin_number, + "PinValue": result + }] + command_results = CommandResults( + outputs_prefix=prefix, + outputs_key_field=['PinNumber', 'PinType'], + outputs=results, + readable_output=tableToMarkdown(f"Get pin {pin_number} on {server.host}({server.port}):", results) + ) + return command_results + + +def arduino_send_data_command(server: Server, args: dict) -> CommandResults: + data = args.get('data') + result = server.send_data(data) + results = [{ + "Sent": data, + "Received": result.decode() + }] + command_results = CommandResults( + outputs_prefix="Arduino.DataSend", + outputs_key_field='Sent', + outputs=results, + readable_output=tableToMarkdown(f"Data sent to {server.host}({server.port}):", results) + ) + return command_results + + +''' MAIN FUNCTION ''' + + +def main(): + params = demisto.params() + host = params.get('host') + port = params.get('port') + args = demisto.args() + if "host" in args and "port" in args: + host = args.get('host') + port = args.get('port') + try: + port = int(port) + except Exception as err: + return_error(f"'Port' must be a number - {err}") + command: str = demisto.command() + demisto.debug(f'Command being called is {command}') + + commands = { + 'arduino-set-pin': arduino_set_pin_command, + 'arduino-get-pin': arduino_get_pin_command, + 'arduino-send-data': arduino_send_data_command + } + + # try: + server: Server = Server(host, port) + + if demisto.command() == 'test-module': + return_results(test_module(server)) + + elif command in commands: + return_results(commands[command](server, args)) + + else: + return_error(f"{command} command not recognised") + + # Log exceptions and return errors + # except Exception as e: + # demisto.error(traceback.format_exc()) # print the traceback + # return_error(f'Failed to execute {command} command.\nError:\n{str(e)}') + + +''' ENTRY POINT ''' + +if __name__ in ('__main__', '__builtin__', 'builtins'): + main() diff --git a/pool/shard001/Python/0014588_notification.py b/pool/shard001/Python/0014588_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..1d64467f9ced5bcdde667d6be897314e329c533d --- /dev/null +++ b/pool/shard001/Python/0014588_notification.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- + +# Copyright 2013 Mirantis, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from datetime import datetime + +from nailgun import consts +from nailgun.db.sqlalchemy import models + +from nailgun.errors import errors +from nailgun.logger import logger + +from nailgun.objects import NailgunCollection +from nailgun.objects import NailgunObject + +from nailgun.objects import Task + +from nailgun.objects.serializers.notification import NotificationSerializer + + +class Notification(NailgunObject): + + model = models.Notification + serializer = NotificationSerializer + + schema = { + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Notification", + "description": "Serialized Notification object", + "type": "object", + "properties": { + "id": {"type": "number"}, + "cluster_id": {"type": "number"}, + "node_id": {"type": "number"}, + "task_id": {"type": "number"}, + "time": {"type": "string"}, + "date": {"type": "string"}, + "topic": { + "type": "string", + "enum": list(consts.NOTIFICATION_TOPICS) + }, + "message": {"type": "string"}, + "status": { + "type": "string", + "enum": list(consts.NOTIFICATION_STATUSES) + } + } + } + + @classmethod + def create(cls, data): + """Creates and returns a notification instance. + + :param data: a dict with notification data + :returns: a notification instance in case of notification + doesn't exist; otherwise - None + """ + topic = data.get("topic") + node_id = data.get("node_id") + task_uuid = data.pop("task_uuid", None) + message = data.get("message") + + if topic == 'discover' and node_id is None: + raise errors.CannotFindNodeIDForDiscovering( + "No node id in discover notification" + ) + + if "datetime" not in data: + data["datetime"] = datetime.now() + + exist = None + if task_uuid: + task = Task.get_by_uuid(task_uuid) + if task and node_id: + exist = NotificationCollection.count( + NotificationCollection.filter_by( + None, + node_id=node_id, + message=message, + task_id=task.id + ) + ) + + if not exist: + notification = super(Notification, cls).create(data) + logger.info( + u"Notification: topic: {0} message: {1}".format( + data.get("topic"), + data.get("message") + ) + ) + return notification + return None + + @classmethod + def to_dict(cls, instance, fields=None): + notif_dict = cls.serializer.serialize(instance, fields=fields) + notif_dict['time'] = instance.datetime.strftime('%H:%M:%S') + notif_dict['date'] = instance.datetime.strftime('%d-%m-%Y') + return notif_dict + + +class NotificationCollection(NailgunCollection): + + single = Notification diff --git a/pool/shard001/Python/0014596_l2-019-bridge_fdb_team_vlan1d.py b/pool/shard001/Python/0014596_l2-019-bridge_fdb_team_vlan1d.py new file mode 100644 index 0000000000000000000000000000000000000000..08adc83544ae303f9c1e7e22ea20126d5fceddcb --- /dev/null +++ b/pool/shard001/Python/0014596_l2-019-bridge_fdb_team_vlan1d.py @@ -0,0 +1,114 @@ +""" +Copyright 2016 Mellanox Technologies. All rights reserved. +Licensed under the GNU General Public License, version 2 as +published by the Free Software Foundation; see COPYING for details. +""" + +__author__ = """ +jiri@mellanox.com (Jiri Pirko) +idosch@mellanox.com (Ido Schimmel) +""" + +from lnst.Controller.Task import ctl +from TestLib import TestLib +from time import sleep + +def test_ip(major, minor): + return ["192.168.10%d.%d/24" % (major, minor), + "2002:%d::%d/64" % (major, minor)] + +def do_task(ctl, hosts, ifaces, aliases): + m1, m2, sw = hosts + m1_if1, m1_if2, m2_if1, m2_if2, sw_if1, sw_if2, sw_if3, sw_if4 = ifaces + + team_config = '{"runner" : {"name" : "lacp"}}' + m1_lag1 = m1.create_team(slaves=[m1_if1, m1_if2], config=team_config) + + m2_lag1 = m2.create_team(slaves=[m2_if1, m2_if2], config=team_config) + + sw_lag1 = sw.create_team(slaves=[sw_if1, sw_if2], config=team_config) + + sw_lag2 = sw.create_team(slaves=[sw_if3, sw_if4], config=team_config) + + m1_lag1_10 = m1.create_vlan(m1_lag1, 10, ip=test_ip(1,1)) + m2_lag1_20 = m2.create_vlan(m2_lag1, 20, ip=test_ip(1,2)) + sw_lag1_10 = sw.create_vlan(sw_lag1, 10) + sw_lag2_20 = sw.create_vlan(sw_lag2, 20) + + # Ageing time is 10 seconds. + br_options = {"vlan_filtering": 0, "ageing_time": 1000, "multicast_querier": 1} + sw_br = sw.create_bridge(slaves = [sw_lag1_10, sw_lag2_20], options=br_options) + + sleep(30) + + tl = TestLib(ctl, aliases) + tl.ping_simple(m1_lag1_10, m2_lag1_20) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, True) + sw_lag1_10.set_br_learning(on=False, master=True) + + sleep(30) + + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, True, False) + + # Make sure FDB is not populated when learning is disabled. + sw_lag1_10.set_br_learning(on=False, master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, True, False) + + # Disable flooding and make sure ping fails. + sw_lag1_10.set_br_flooding(on=False, master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20, fail_expected=True) + + # Set a static FDB entry and make sure ping works again. Also check + # its offloaded + sw_lag1_10.add_br_fdb(str(m1_lag1_10.get_hwaddr()), master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, False) + + # Remove static FDB entry. Ping should fail. + sw_lag1_10.del_br_fdb(str(m1_lag1_10.get_hwaddr()), master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20, fail_expected=True) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, False, False) + + # Enable learning and flooding and make sure ping works again. + sw_lag1_10.set_br_learning(on=True, master=True) + sw_lag1_10.set_br_flooding(on=True, master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, True) + sw_lag1_10.set_br_learning(on=False, master=True) + + sleep(30) + + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, True, False) + + # Insert a static FDB entry. Ping should work. + sw_lag1_10.add_br_fdb(str(m1_lag1_10.get_hwaddr()), master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20) + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, False) + + sleep(30) + + # Make sure static entry is not aged out. + tl.check_fdb(sw_lag1_10, m1_lag1_10.get_hwaddr(), 0, True, False) + + # Remove port from bridge and add it back. The static entry added + # before should be flushed. Disable flooding and learning and make + # sure ping doesn't work. + sw_br.slave_del(sw_lag1_10.get_id()) + sw_br.slave_add(sw_lag1_10.get_id()) + sw_lag1_10.set_br_learning(on=False, master=True) + sw_lag1_10.set_br_flooding(on=False, master=True) + tl.ping_simple(m1_lag1_10, m2_lag1_20, fail_expected=True) + +do_task(ctl, [ctl.get_host("machine1"), + ctl.get_host("machine2"), + ctl.get_host("switch")], + [ctl.get_host("machine1").get_interface("if1"), + ctl.get_host("machine1").get_interface("if2"), + ctl.get_host("machine2").get_interface("if1"), + ctl.get_host("machine2").get_interface("if2"), + ctl.get_host("switch").get_interface("if1"), + ctl.get_host("switch").get_interface("if2"), + ctl.get_host("switch").get_interface("if3"), + ctl.get_host("switch").get_interface("if4")], + ctl.get_aliases()) diff --git a/pool/shard001/Python/0014597_combo_box_tests.py b/pool/shard001/Python/0014597_combo_box_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..2388c2f944b02e0f21b94c083b04797c4e42ed64 --- /dev/null +++ b/pool/shard001/Python/0014597_combo_box_tests.py @@ -0,0 +1,62 @@ +from JDI.jdi_assert.testing.assertion import Assert +from Test.jdi_uitests_webtests.main.enums.entities import Metals +from Test.jdi_uitests_webtests.main.enums.preconditions import Preconditions +from Test.jdi_uitests_webtests.main.page_objects.epam_jdi_site import EpamJDISite +from Test.jdi_uitests_webtests.main.utils.common_action_data import CommonActionsData +from Test.jdi_uitests_webtests.test.init_tests import InitTests + + +class ComboBoxTests(InitTests): + + add_options = ["Col", "Gold", "Silver", "Bronze", "Selen"] + add_options_string = "Col, Gold, Silver, Bronze, Selen" + + combo_box = EpamJDISite.metals_colors_page.combo_box + + def setUp(self): + Preconditions.METALS_AND_COLORS_PAGE.is_in_state() + + def test_select_string(self): + self.combo_box.select("Gold") + CommonActionsData.check_action("Metals: value changed to Gold") + + def test_select_index(self): + self.combo_box.select(3) + CommonActionsData.check_action("Metals: value changed to Silver") + + def test_select_enum(self): + self.combo_box.select(Metals.GOLD) + CommonActionsData.check_action("Metals: value changed to Gold") + + def test_get_options(self): + Assert.assert_equal(self.combo_box.get_options(), self.add_options) + + def test_get_names(self): + Assert.assert_equal(self.combo_box.get_names(), self.add_options) + + def test_get_values(self): + Assert.assert_equal(self.combo_box.get_values(), self.add_options) + + def test_get_options_as_text(self): + Assert.assert_equal(self.combo_box.get_options_as_text(), self.add_options_string) + + def test_set_value_text(self): + self.combo_box.set_value("Blue") + CommonActionsData.loose_focus() + CommonActionsData.check_action("Metals: value changed to Blue") + + def test_get_selected(self): + self.combo_box.select("Gold") + Assert.assert_equal(self.combo_box.get_selected(), "Gold") + + def test_get_selected_index(self): + CommonActionsData.check_action_throw_error(lambda: self.combo_box.get_selected_index(), CommonActionsData.no_elements_message()) + + def test_is_selected(self): + Assert.assert_equal(self.combo_box.is_selected("Col"), True) + + def test_is_selected_enum(self): + Assert.assert_equal(self.combo_box.is_selected(Metals.COL), True) + + def test_get_value(self): + Assert.assert_equal(self.combo_box.get_value(), "Col") \ No newline at end of file diff --git a/pool/shard001/Python/0014600_stock_putaway_rule.py b/pool/shard001/Python/0014600_stock_putaway_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..357cb7b0d9a019cc591011f207c7b0cd03baff00 --- /dev/null +++ b/pool/shard001/Python/0014600_stock_putaway_rule.py @@ -0,0 +1,40 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +# Copyright 2020 Sergio Teruel - Tecnativa +# Copyright 2020 Víctor Martínez - Tecnativa + +from odoo import api, fields, models + + +class StockPutawayRule(models.Model): + _inherit = "stock.putaway.rule" + + product_tmpl_id = fields.Many2one( + comodel_name="product.template", + compute="_compute_product_tmpl_id", + store=True, + readonly=False, + ondelete="cascade", + ) + + @api.depends("product_id") + def _compute_product_tmpl_id(self): + for rec in self: + if rec.product_id: + rec.product_tmpl_id = rec.product_id.product_tmpl_id + else: + params = self.env.context.get("params", {}) + if params.get("model", "") == "product.template" and params.get("id"): + rec.product_tmpl_id = params.get("id") + + def filtered(self, func): + res = super().filtered(func) + if res or not self.env.context.get("filter_putaway_rule"): + return res + product = func.__closure__[0].cell_contents + if product._name != "product.product": + return res + return self.with_context(filter_putaway_rule=False).filtered( + lambda x: ( + x.product_tmpl_id == product.product_tmpl_id and not x.product_id + ) + ) diff --git a/pool/shard001/Python/0014602_ex26.py b/pool/shard001/Python/0014602_ex26.py new file mode 100644 index 0000000000000000000000000000000000000000..d199c5b9591207b9b378b7de29f193b325197301 --- /dev/null +++ b/pool/shard001/Python/0014602_ex26.py @@ -0,0 +1,90 @@ +def break_words(stuff): + """This function will break up words for us.""" + words = stuff.split(' ') + return words + +def sort_words(words): + """Sorts the words.""" + return sorted(words) + +def print_first_word(words): + """Prints the first word after popping it off.""" + word = words.pop(0) + print word + +def print_last_word(words): + """Prints the last word after popping it off.""" + word = words.pop(-1) + print word + +def sort_sentence(sentence): + """Takes in a full sentence and returns the sorted words.""" + words = break_words(sentence) + return sort_words(words) + +def print_first_and_last(sentence): + """Prints the first and last words of the sentence.""" + words = break_words(sentence) + print_first_word(words) + print_last_word(words) + +def print_first_and_last_sorted(sentence): + """Sorts the words then prints the first and last one.""" + words = sort_sentence(sentence) + print_first_word(words) + print_last_word(words) + + +print "Let's practice everything." +print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' + +poem = """ +\tThe lovely world +with logic so firmly planted +cannot discern \n the needs of love +nor comprehend passion from intuition +and requires an explantion +\n\t\twhere there is none. +""" + + +print "--------------" +print poem +print "--------------" + +five = 10 - 2 + 3 - 5 +print "This should be five: %s" % five + +def secret_formula(started): + jelly_beans = started * 500 + jars = jelly_beans / 1000 + crates = jars / 100 + return jelly_beans, jars, crates + +start_point = 10000 +beans, jars, crates = secret_formula(start_point) + +print "With a starting point of: %d" % start_point +print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates) + +start_point = start_point / 10 + +print "We can also do that this way:" +print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) + +sentence = "All good things come to those who wait." + +words = break_words(sentence) +sorted_words = sort_words(words) + +print_first_word(words) +print_last_word(words) +print_first_word(sorted_words) +print_last_word(sorted_words) +sorted_words = sort_sentence(sentence) +print sorted_words + +print_first_and_last(sentence) + +print_first_and_last_sorted(sentence) + diff --git a/pool/shard001/Python/0014605_parsers.py b/pool/shard001/Python/0014605_parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..d00d2c6bd58230c1cf2fb2677e0b8b5d926e08e9 --- /dev/null +++ b/pool/shard001/Python/0014605_parsers.py @@ -0,0 +1,78 @@ +__author__ = 'Kal Ahmed' + +from codecs import getreader + +from rdflib.plugins.parsers.ntriples import NTriplesParser +from rdflib.plugins.parsers.ntriples import ParseError +from rdflib.plugins.parsers.ntriples import r_tail +from rdflib.plugins.parsers.ntriples import r_wspace +from rdflib.util import guess_format + +# Extension to format mappings to use in addition to the default ones in rdflib +ext_map = { + 'ntriples': 'nt', + 'nquads': 'nquads' +} + + +def get_parser(file_path, sink): + fmt = guess_format(file_path) or guess_format(file_path, ext_map) + if fmt == 'nt': + return NTriplesParser(sink=sink) + if fmt == 'nquads': + return NQuadsParser(sink) + return None + + +class NQuadsParser(NTriplesParser): + + def __init__(self, sink): + super().__init__() + self.sink = sink + self.file = None + self.buffer = None + self.line = None + + def parse(self, source): + """Parse f as an N-Triples file.""" + + if not hasattr(source, 'read'): + raise ParseError("Item to parse must be a file-like object.") + + source = getreader('utf-8')(source) + + self.file = source + self.buffer = '' + while True: + self.line = __line = self.readline() + if self.line is None: + break + try: + self.parseline() + except ParseError as msg: + raise ParseError("Invalid line (%s):\n%r" % (msg, __line)) + + return self.sink + + def parseline(self): + self.eat(r_wspace) + if (not self.line) or self.line.startswith('#'): + return # The line is empty or a comment + + subject = self.subject() + self.eat(r_wspace) + + predicate = self.predicate() + self.eat(r_wspace) + + obj = self.object() + self.eat(r_wspace) + + context = self.uriref() or self.nodeid() + self.eat(r_tail) + + if self.line: + raise ParseError("Trailing garbage") + # Must have a context aware store - add on a normal Graph + # discards anything where the ctx != graph.identifier + self.sink.quad(subject, predicate, obj, context) diff --git a/pool/shard001/Python/0014615_jerkins-import.py b/pool/shard001/Python/0014615_jerkins-import.py new file mode 100644 index 0000000000000000000000000000000000000000..3431a297b3c3d61fc1165fea91726bd455e1fe1b --- /dev/null +++ b/pool/shard001/Python/0014615_jerkins-import.py @@ -0,0 +1,35 @@ +import jenkins +import configparser + + +class Jenkins(object): + def __init__(self): + pass + + def parseconfig(self): + config = configparser.ConfigParser() + config.read('config.ini') + username = config.get("jenkins", "username") + password = config.get("jenkins", "password") + jobitems = config.items('jobconfig') + return (username, password, jobitems) + + def create_job(self): + username, password, jobitems = self.parseconfig() + server = jenkins.Jenkins('http://jenkins.sit.blackfi.sh', username=username, password=password) + for (jobname, configxml) in jobitems: + with open(configxml, 'r') as f: + configxml = f.read() + try: + server.create_job(jobname, configxml) + print('JOB {}创建成功'.format(jobname)) + except jenkins.JenkinsException: + print('JOB名称{}已存在'.format(jobname)) + + def run(self): + self.create_job() + + +if __name__ == '__main__': + t = Jenkins() + t.run() diff --git a/pool/shard001/Python/0014621_wallpapers.py b/pool/shard001/Python/0014621_wallpapers.py new file mode 100644 index 0000000000000000000000000000000000000000..658b5ee6e587cf4f8680bb3a55ea97996c4ad402 --- /dev/null +++ b/pool/shard001/Python/0014621_wallpapers.py @@ -0,0 +1,167 @@ +import os + +from preferences import * + + +def get_wallpaper(): + picture = '' + # http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment + determine_platform() + desktop_session = determine_desktop_session() + + if desktop_session in ["mate", "mate-session"]: + picture = get_wallpaper_mate() + elif desktop_session in ["lubuntu", "lxsession", "lxde"]: + picture = get_wallpaper_lxde() + else: + sys.exit("Unknown desktop session: '{0}'".format(desktop_session)) + + picture = picture.rstrip('\n\r') + picture = picture.strip("'") + + # Checking existance of image + if not os.path.exists(picture): + verboseprint("Current wallpaper image '{0}' not found.".format(picture)) + picture = '' + + # If current wallpaper image contains suffix, then we will + suffix = config['MAIN']['suffix'] + if (picture.find(suffix) >= 0) or (picture in ['', None]): + picture = config['MAIN']['original_wallpaper_image'] + if config['MAIN']['original_wallpaper_image'] == '': + verboseprint('Can not find info about original wallpaper image.') + config['MAIN']['use_wallpaper_image'] = 'False' + return picture + + +def get_wallpaper_mate(): + picture = os.popen("gsettings get org.mate.background picture-filename").read() + return picture + + + +def get_lxde_profile_name(): + files = ["/etc/xdg/lxsession/Lubuntu/autostart", "/etc/xdg/lxsession/LXDE/autostart"] + for file in files: + if os.path.exists(file): + #result = os.popen("grep -i \"^@pcmanfm\" {0} | grep -oP \"\\-\\-profile[\\s=].*[\\s\\n\\r]*\"".format(file)).read() + result = os.popen("grep -i \"^@pcmanfm\" {0} | grep -oP \"\\-\\-profile[\\s=].*[\\s\\n\\r]*\" | cut \\-d\' \' \\-f2".format(file)).read() + return result.rstrip('\n\r') + + +def get_wallpaper_lxde(): + wallpaper = '' + profile_name = get_lxde_profile_name() + parser = configparser.ConfigParser() + verboseprint("Profile name: '{0}'".format(profile_name)) + if (profile_name is not None) and (profile_name <> ''): + config_path = os.path.join(os.path.expandvars('$HOME'), '.config/pcmanfm', profile_name, 'desktop-items-0.conf') + else: + config_path = os.path.join(os.path.expandvars('$HOME'), '.config/pcmanfm/lubuntu/desktop-items-0.conf') + verboseprint("Config path: '{0}'".format(config_path)) + config.read(config_path) + if '*' in config: + config_star = config['*'] + wallpaper = config_star.get('wallpaper', fallback = '') + return wallpaper + + +def set_wallpaper(out_img): + result = -1 + determine_platform() + desktop_session = determine_desktop_session() + + if desktop_session in ["mate", "mate-session"]: + result = set_wallpaper_mate(out_img) + elif desktop_session in ["lubuntu", "lxsession", "lxde"]: + result = set_wallpaper_lxde(out_img) + else: + sys.exit("Unsupported desktop session: '{0}'".format(desktop_session)) + + return result + +def set_wallpaper_mate(file): + verboseprint("Try to set wallpaper for mate: {0}".format(file)) + # 'none', 'wallpaper', 'centered', 'scaled', 'stretched', 'zoom', 'spanned' + os.popen("gsettings set org.mate.background picture-options stretched").read() + return os.popen("gsettings set org.mate.background picture-filename {0}".format(file)).read() + + +def set_wallpaper_lxde(file): + verboseprint("Try to set wallpaper for lxde: {0}".format(file)) + # --wallpaper-mode=(color|stretch|fit|crop|center|tile|screen) + return os.popen("pcmanfm --set-wallpaper={0} --wallpaper-mode=stretch".format(file)).read() + + +def determine_platform(): + verboseprint('Platform: {0}'.format(sys.platform)) + # Since we're writing linux-only for now... + if sys.platform.startswith('linux'): + return sys.platform + else: + sys.exit("Unsupported platform: '{0}'".format(sys.platform)) + + +def determine_desktop_session(): + desktop_session = os.environ.get("DESKTOP_SESSION") + + if desktop_session is not None: + desktop_session = desktop_session.lower() + else: + desktop_session = os.popen("ps -u $USER | grep -ioP '\S+session' | grep -v grep").read() + desktop_session = desktop_session.rstrip('\n') + + if desktop_session is not None: + verboseprint('Desktop session: {0}'.format(desktop_session)) + return desktop_session + else: + sys.exit("Desktop session is None") + + +def determine_screen_resolution(): + screen_resolution = "640x480" + output = os.popen('xrandr --display :0 | grep -oP "current\s\d+\sx\s\d+"').read() + output = output.rstrip('\n') + verboseprint("xrandr output current: '{0}'".format(output)) + if output <> '': + output = output.split() + output.pop(0) + output = "".join(output) + screen_resolution = output + verboseprint("Screen resolution: '{0}'".format(screen_resolution)) + return screen_resolution + + +def wallpaper_is_set(): + # type: () -> bool + desktop_session = determine_desktop_session() + + if desktop_session in ["mate", "mate-session"]: + if os.popen("gsettings get org.mate.background picture-filename").read() <> '': + return True + else: + return False + + elif desktop_session in ["lubuntu", "lxsession"]: + profile_name = get_lxde_profile_name() + + if (profile_name is not None) and (profile_name <> ''): + config_path = os.path.expandvars('$HOME') + '/.config/pcmanfm/{0}/desktop-items-0.conf'.format(profile_name) + else: + config_path = os.path.expandvars('$HOME') + '/.config/pcmanfm/lubuntu/desktop-items-0.conf' + # endif + + # Parse config for: + # [*] + # wallpaper_mode = color + # if 'color' => False | smth else => True + parser = configparser.ConfigParser() + parser.read(config_path) + + if parser['*']['wallpaper_mode'] <> 'color': + return True + else: + return False + + else: + sys.exit("Unknown desktop session: '{0}'".format(desktop_session)) diff --git a/pool/shard001/Python/0014622_style.py b/pool/shard001/Python/0014622_style.py new file mode 100644 index 0000000000000000000000000000000000000000..3c78950bed2737a736e51b7a7c9d5b6ee633ba7a --- /dev/null +++ b/pool/shard001/Python/0014622_style.py @@ -0,0 +1,121 @@ +#-------------------------------------------------------------------------- +# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas +# Copyright: (C) 2001 Centro de Pesquisas Renato Archer +# Homepage: http://www.softwarepublico.gov.br +# Contact: invesalius@cti.gov.br +# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) +#-------------------------------------------------------------------------- +# Este programa e software livre; voce pode redistribui-lo e/ou +# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme +# publicada pela Free Software Foundation; de acordo com a versao 2 +# da Licenca. +# +# Este programa eh distribuido na expectativa de ser util, mas SEM +# QUALQUER GARANTIA; sem mesmo a garantia implicita de +# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM +# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais +# detalhes. +#-------------------------------------------------------------------------- + +from wx.lib.pubsub import pub as Publisher + + +# mode.py +# to be instanced inside Controller (control.py) + + + +# IMPORTANT: When adding a new state, remember o insert it into LEVEL +# dictionary + + +# RULE: +# default is the only level 0 +# states controlled somehow by taskmenu are level 1 +# states controlled by toolbar are level 2 +#LEVEL = {SLICE_STATE_DEFAULT: 0, +# SLICE_STATE_EDITOR: 1, +# SLICE_STATE_WL: 2, +# SLICE_STATE_SPIN: 2, +# SLICE_STATE_ZOOM: 2, +# SLICE_STATE_ZOOM_SL: 2} +#---------------------- +# TODO: Add to viewer_slice.py: + +#ps.Publisher().subscribe(self.OnSetMode, 'Set slice mode') + +#def OnSetMode(self, pubsub_evt): +# mode = pubsub_evt.data + # according to mode, set cursor, interaction, etc +#---------------------- +# TODO: Add GUI classes (frame, tasks related to slice, toolbar): + +# always bind to this class (regarding slice mode) and not to +# viewer_slice directly + +# example - pseudo code +#def OnToggleButtonSpin(self, evt) +# if evt.toggle: # doesn't exist, just to illustrate +# ps.Publisher().sendMessage('Enable mode', const.SLICE_STATE_ZOOM) +# else: +# ps.Publisher().subscribe('Disable mode', const.SLICE_STATE_ZOOM) + + +#---------------------- + + +import constants as const + +class StyleStateManager(object): +# don't need to be singleton, only needs to be instantiated inside +# (Controller) self.slice_mode = SliceMode() + + def __init__(self): + self.stack = {} + + # push default value to stack + self.stack[const.STYLE_LEVEL[const.STATE_DEFAULT]] = \ + const.STATE_DEFAULT + + def AddState(self, state): + + level = const.STYLE_LEVEL[state] + max_level = max(self.stack.keys()) + + # Insert new state into stack + self.stack[level] = state + + + new_max_level = max(self.stack.keys()) + return self.stack[new_max_level] + + def RemoveState(self, state): + level = const.STYLE_LEVEL[state] + if level in self.stack.keys(): + max_level = max(self.stack.keys()) + + # Remove item from stack + self.stack.pop(level) + + # New max level + new_max_level = max(self.stack.keys()) + + # Only will affect InVesalius behaviour if the highest + # level in stack has been removed + if level == max_level: + new_state = self.stack[new_max_level] + + return self.stack[new_max_level] + + max_level = max(self.stack.keys()) + return self.stack[max_level] + + def GetActualState(self): + max_level = max(self.stack.keys()) + state = self.stack[max_level] + return state + + def Reset(self): + self.stack = {} + self.stack[const.STYLE_LEVEL[const.STATE_DEFAULT]] = \ + const.STATE_DEFAULT diff --git a/pool/shard001/Python/0014624_0006_itinerary_summary.py b/pool/shard001/Python/0014624_0006_itinerary_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee7e027db7fd1a961723612651bcae676f9371d --- /dev/null +++ b/pool/shard001/Python/0014624_0006_itinerary_summary.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.5 on 2016-04-27 07:21 +from __future__ import unicode_literals + +import datetime +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('product', '0003_sale_amount'), + ('activity', '0005_conclusion'), + ] + + operations = [ + migrations.CreateModel( + name='Itinerary', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('recorded_date', models.DateField(default=datetime.date.today)), + ('places', models.TextField(blank=True)), + ('rep', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.Rep')), + ], + ), + migrations.CreateModel( + name='Summary', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('start_date', models.DateField()), + ('end_date', models.DateField()), + ('outstanding', models.IntegerField(default=0)), + ('report', models.TextField(blank=True)), + ('rep', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.Rep')), + ], + ), + ] diff --git a/pool/shard001/Python/0014626_test_helpers.py b/pool/shard001/Python/0014626_test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fd5743f9a466cbedb4a9c1a85aab2e96a55149 --- /dev/null +++ b/pool/shard001/Python/0014626_test_helpers.py @@ -0,0 +1,172 @@ +#-*- coding: utf-8 -*- +import datetime +from flaskbb.utils.helpers import slugify, forum_is_unread, topic_is_unread, \ + crop_title, render_markup, is_online, format_date, format_quote, \ + get_image_info, check_image, time_utcnow +from flaskbb.utils.settings import flaskbb_config +from flaskbb.forum.models import Forum + + +def test_slugify(): + """Test the slugify helper method.""" + assert slugify(u'Hello world') == u'hello-world' + + assert slugify(u'¿Cómo está?') == u'como-esta' + + +def test_forum_is_unread(guest, user, forum, topic, forumsread): + """Test the forum is unread function.""" + + # for a guest + assert not forum_is_unread(None, None, guest) + + # for a logged in user without a forumsread + assert forum_is_unread(forum, None, user) + + # same, just with forumsread + assert forum_is_unread(forum, forumsread, user) + + # lets mark the forum as read + # but before we have to add an read entry in forumsread and topicsread + topic.update_read(user, topic.forum, forumsread) + + time_read = datetime.datetime.utcnow() - datetime.timedelta(hours=1) + forumsread.cleared = time_read # lets cheat here a bit :P + forumsread.last_read = datetime.datetime.utcnow() + forumsread.save() + assert not forum_is_unread(forum, forumsread, user) + + # read tracker is disabled + flaskbb_config["TRACKER_LENGTH"] = 0 + assert not forum_is_unread(forum, forumsread, user) + + # there haven't been a post since TRACKER_LENGTH and thus the forum is read + flaskbb_config["TRACKER_LENGTH"] = 1 + # this is cheating; don't do this. + forum.last_post_created = forum.last_post_created - datetime.timedelta(hours=48) + forum.save() + assert not forum_is_unread(forum, forumsread, user) + + # no topics in this forum + topic.delete() + forum = Forum.query.filter_by(id=forum.id).first() + flaskbb_config["TRACKER_LENGTH"] = 1 # activate the tracker again + assert forum.topic_count == 0 + assert not forum_is_unread(forum, None, user) + + +def test_topic_is_unread(guest, user, forum, topic, topicsread, forumsread): + # test guest + assert not topic_is_unread(None, None, guest) + + # compare topicsread.last_read with topic.last_post.date_created + assert topic_is_unread(topic, topicsread, user, forumsread) + + # TopicsRead is none and the forum has never been marked as read + assert topic_is_unread(topic, topicsread=None, user=user, forumsread=forumsread) + + # lets mark the forum as read + forumsread.cleared = time_utcnow() + forumsread.last_read = time_utcnow() + forumsread.save() + assert not topic_is_unread(topic, topicsread=None, user=user, forumsread=forumsread) + + # disabled tracker + flaskbb_config["TRACKER_LENGTH"] = 0 + assert not topic_is_unread(topic, None, user, None) + + # post is older than tracker length + time_posted = time_utcnow() - datetime.timedelta(days=2) + flaskbb_config["TRACKER_LENGTH"] = 1 + topic.last_post.date_created = time_posted + topic.save() + assert not topic_is_unread(topic, None, user, None) + + +def test_crop_title(default_settings): + short_title = "Short title" + long_title = "This is just a test title which is too long." + + assert crop_title(short_title) == short_title + assert crop_title(long_title) == "This is just a..." + + +def test_render_markup(default_settings): + markdown = "**Bold**" + assert render_markup(markdown) == "

Bold

\n" + + +def test_is_online(default_settings, user): + assert is_online(user) + + +def test_format_date(): + date = datetime.date(2015, 2, 15) + time = datetime.datetime.combine(date, datetime.datetime.min.time()) + assert format_date(time) == "2015-02-15" + + +def test_format_quote(topic): + expected_markdown = "**[test_normal](http://localhost:5000/user/test_normal) wrote:**\n> Test Content Normal\n" + actual = format_quote(topic.first_post.username, topic.first_post.content) + assert actual == expected_markdown + + +def test_get_image_info(): + # some random jpg/gif/png images from my imgur account + jpg = "http://i.imgur.com/NgVIeRG.jpg" + gif = "http://i.imgur.com/l3Vmp4m.gif" + png = "http://i.imgur.com/JXzKxNs.png" + + jpg_img = get_image_info(jpg) + assert jpg_img["content-type"] == "image/jpeg" + assert jpg_img["height"] == 1024 + assert jpg_img["width"] == 1280 + assert jpg_img["size"] == 209.06 + + gif_img = get_image_info(gif) + assert gif_img["content-type"] == "image/gif" + assert gif_img["height"] == 168 + assert gif_img["width"] == 400 + assert gif_img["size"] == 576.138 + + png_img = get_image_info(png) + assert png_img["content-type"] == "image/png" + assert png_img["height"] == 1080 + assert png_img["width"] == 1920 + assert png_img["size"] == 269.409 + + +def test_check_image(default_settings): + # test200x100.png + img_width = "http://i.imgur.com/4dAWAZI.png" + # test100x200.png + img_height = "http://i.imgur.com/I7GwF3D.png" + # test100x100.png + img_ok = "http://i.imgur.com/CYV6NzT.png" + # random too big image + img_size = "http://i.imgur.com/l3Vmp4m.gif" + # random image wrong type + img_type = "https://d11xdyzr0div58.cloudfront.net/static/logos/archlinux-logo-black-scalable.f931920e6cdb.svg" + + data = check_image(img_width) + assert "wide" in data[0] + assert not data[1] + + data = check_image(img_height) + assert "high" in data[0] + assert not data[1] + + data = check_image(img_type) + assert "type" in data[0] + assert not data[1] + + data = check_image(img_ok) + assert data[0] is None + assert data[1] + + flaskbb_config["AVATAR_WIDTH"] = 1000 + flaskbb_config["AVATAR_HEIGHT"] = 1000 + data = check_image(img_size) + assert "big" in data[0] + assert not data[1] diff --git a/pool/shard001/Python/0014627_test_windows.py b/pool/shard001/Python/0014627_test_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6a184489c15209105f07e97013469d11b24ba4 --- /dev/null +++ b/pool/shard001/Python/0014627_test_windows.py @@ -0,0 +1,67 @@ +from __future__ import division, print_function, absolute_import + + +from numpy import array, ones_like +from numpy.testing import assert_array_almost_equal, assert_array_equal +from scipy import signal + + +cheb_odd_true = array([0.200938, 0.107729, 0.134941, 0.165348, + 0.198891, 0.235450, 0.274846, 0.316836, + 0.361119, 0.407338, 0.455079, 0.503883, + 0.553248, 0.602637, 0.651489, 0.699227, + 0.745266, 0.789028, 0.829947, 0.867485, + 0.901138, 0.930448, 0.955010, 0.974482, + 0.988591, 0.997138, 1.000000, 0.997138, + 0.988591, 0.974482, 0.955010, 0.930448, + 0.901138, 0.867485, 0.829947, 0.789028, + 0.745266, 0.699227, 0.651489, 0.602637, + 0.553248, 0.503883, 0.455079, 0.407338, + 0.361119, 0.316836, 0.274846, 0.235450, + 0.198891, 0.165348, 0.134941, 0.107729, + 0.200938]) + +cheb_even_true = array([0.203894, 0.107279, 0.133904, + 0.163608, 0.196338, 0.231986, + 0.270385, 0.311313, 0.354493, + 0.399594, 0.446233, 0.493983, + 0.542378, 0.590916, 0.639071, + 0.686302, 0.732055, 0.775783, + 0.816944, 0.855021, 0.889525, + 0.920006, 0.946060, 0.967339, + 0.983557, 0.994494, 1.000000, + 1.000000, 0.994494, 0.983557, + 0.967339, 0.946060, 0.920006, + 0.889525, 0.855021, 0.816944, + 0.775783, 0.732055, 0.686302, + 0.639071, 0.590916, 0.542378, + 0.493983, 0.446233, 0.399594, + 0.354493, 0.311313, 0.270385, + 0.231986, 0.196338, 0.163608, + 0.133904, 0.107279, 0.203894]) + + +class TestChebWin(object): + + def test_cheb_odd(self): + cheb_odd = signal.chebwin(53, at=-40) + assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4) + + def test_cheb_even(self): + cheb_even = signal.chebwin(54, at=-40) + assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4) + + +class TestGetWindow(object): + + def test_boxcar(self): + w = signal.get_window('boxcar', 12) + assert_array_equal(w, ones_like(w)) + + def test_cheb_odd(self): + w = signal.get_window(('chebwin', -40), 53, fftbins=False) + assert_array_almost_equal(w, cheb_odd_true, decimal=4) + + def test_cheb_even(self): + w = signal.get_window(('chebwin', -40), 54, fftbins=False) + assert_array_almost_equal(w, cheb_even_true, decimal=4) diff --git a/pool/shard001/Python/0014633_session.py b/pool/shard001/Python/0014633_session.py new file mode 100644 index 0000000000000000000000000000000000000000..2d627e0837dcbe43116d013737dc3c1d4b1a9f09 --- /dev/null +++ b/pool/shard001/Python/0014633_session.py @@ -0,0 +1,154 @@ +# Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com) +# OpenDrop is released under the GNU GPL License. You are free to +# modify and distribute the code, but always under the same license +# (i.e. you cannot make commercial derivatives). +# +# If you use this software in your research, please cite the following +# journal articles: +# +# J. D. Berry, M. J. Neeson, R. R. Dagastine, D. Y. C. Chan and +# R. F. Tabor, Measurement of surface and interfacial tension using +# pendant drop tensiometry. Journal of Colloid and Interface Science 454 +# (2015) 226–237. https://doi.org/10.1016/j.jcis.2015.05.012 +# +# E. Huang, T. Denning, A. Skoufis, J. Qi, R. R. Dagastine, R. F. Tabor +# and J. D. Berry, OpenDrop: Open-source software for pendant drop +# tensiometry & contact angle measurements, submitted to the Journal of +# Open Source Software +# +# These citations help us not only to understand who is using and +# developing OpenDrop, and for what purpose, but also to justify +# continued development of this code and other open source resources. +# +# OpenDrop is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. You +# should have received a copy of the GNU General Public License along +# with this software. If not, see . + + +from typing import Sequence + +from gi.repository import GObject +from injector import Binder, Module, inject, singleton + +from opendrop.app.common.services.acquisition import ( + AcquirerType, + ImageAcquisitionService, +) + +from .params import ConanParamsFactory +from .features import ConanFeaturesService +from .conan import ConanFitService +from .analysis import ConanAnalysisJob, ConanAnalysisStatus, ConanAnalysisService +from .save import ConanSaveParamsFactory, ConanSaveService + + +READABLE = GObject.ParamFlags.READABLE +EXPLICIT_NOTIFY = GObject.ParamFlags.EXPLICIT_NOTIFY + + +class ConanSessionModule(Module): + def configure(self, binder: Binder): + binder.bind(ConanParamsFactory, scope=singleton) + binder.bind(ConanSaveParamsFactory, scope=singleton) + + binder.bind(ImageAcquisitionService, scope=singleton) + binder.bind(ConanFeaturesService, scope=singleton) + binder.bind(ConanFitService, scope=singleton) + binder.bind(ConanSaveService, scope=singleton) + + binder.bind(ConanSession, scope=singleton) + + +class ConanSession(GObject.Object): + @inject + def __init__( + self, + image_acquisition: ImageAcquisitionService, + features_service: ConanFeaturesService, + cafit_service: ConanFitService, + analysis_service: ConanAnalysisService, + save_service: ConanSaveService, + ) -> None: + self._analyses = () + self._analyses_saved = False + + self._image_acquisition = image_acquisition + self._image_acquisition.use_acquirer_type(AcquirerType.LOCAL_STORAGE) + + self._features_service = features_service + self._cafit_service = cafit_service + self._analysis_service = analysis_service + self._save_service = save_service + + super().__init__() + + @GObject.Property(flags=READABLE | EXPLICIT_NOTIFY) + def analyses(self) -> Sequence[ConanAnalysisJob]: + return self._analyses + + @GObject.Property(flags=READABLE | EXPLICIT_NOTIFY) + def analyses_saved(self) -> bool: + return self._analyses_saved + + def safe_to_discard(self) -> bool: + if self._analyses_saved: + return True + + if not self._analyses: + return True + + all_images_replicated = all( + analysis.image_replicated + for analysis in self._analyses + ) + if all_images_replicated: + return True + + return False + + def start_analyses(self) -> None: + assert not self._analyses + + sources = self._image_acquisition.acquire_images() + self._analyses = tuple( + self._analysis_service.analyse(s) + for s in sources + ) + self._analyses_saved = False + + self.notify('analyses') + self.notify('analyses_saved') + + def cancel_analyses(self) -> None: + keep_analyses = [] + for analysis in self._analyses: + if analysis.status == ConanAnalysisStatus.WAITING_FOR_IMAGE: + # If job is still waiting for image, then delete it + analysis.cancel() + else: + analysis.cancel() + keep_analyses.append(analysis) + + self._analyses = tuple(keep_analyses) + self.notify('analyses') + + def clear_analyses(self) -> None: + self.cancel_analyses() + self._analyses = () + self._analyses_saved = True + self.notify('analyses') + self.notify('analyses_saved') + + def save_analyses(self) -> None: + if not self._analyses: return + self._save_service.save(self._analyses) + self._analyses_saved = True + self.notify('analyses_saved') + + def quit(self) -> None: + self.clear_analyses() + self._image_acquisition.destroy() + self._features_service.destroy() + self._cafit_service.destroy() diff --git a/pool/shard001/Python/0014634_mailer.py b/pool/shard001/Python/0014634_mailer.py new file mode 100644 index 0000000000000000000000000000000000000000..767d81c23e8abe00ab69d018a741d8a4149eafc4 --- /dev/null +++ b/pool/shard001/Python/0014634_mailer.py @@ -0,0 +1,202 @@ +import hashlib +import hmac +import json +import logging +import time + +from google.appengine.api import app_identity +from google.appengine.api import mail +from google.appengine.ext import ndb +import webapp2 +from webapp2_extras import jinja2 + +import gatekeeper_mailer + + +class MailerSecret(ndb.Model): + """Model to represent the shared secret for the mail endpoint.""" + secret = ndb.StringProperty() + + +class BaseHandler(webapp2.RequestHandler): + """Provide a cached Jinja environment to each request.""" + @webapp2.cached_property + def jinja2(self): + # Returns a Jinja2 renderer cached in the app registry. + return jinja2.get_jinja2(app=self.app) + + def render_response(self, _template, **context): + # Renders a template and writes the result to the response. + rv = self.jinja2.render_template(_template, **context) + self.response.write(rv) + + +class MainPage(BaseHandler): + def get(self): + context = {'title': 'Chromium Gatekeeper Mailer'} + self.render_response('main_mailer.html', **context) + + +class Email(BaseHandler): + @staticmethod + def linear_compare(a, b): + """Scan through the entire string even if a mismatch is detected early. + + This thwarts timing attacks attempting to guess the key one byte at a + time. + """ + if len(a) != len(b): + return False + result = 0 + for x, y in zip(a, b): + result |= ord(x) ^ ord(y) + return result == 0 + + @staticmethod + def _validate_message(message, url, secret): + """Cryptographically validates the message.""" + mytime = time.time() + + if abs(mytime - message['time']) > 60: + logging.error('message was rejected due to time') + return False + + cleaned_url = url.rstrip('/') + '/' + cleaned_message_url = message['url'].rstrip('/') + '/' + + if cleaned_message_url != cleaned_url: + logging.error('message URL did not match: %s vs %s', cleaned_message_url, + cleaned_url) + return False + + hasher = hmac.new(str(secret), message['message'], hashlib.sha256) + hasher.update(str(message['time'])) + hasher.update(str(message['salt'])) + + client_hash = hasher.hexdigest() + + return Email.linear_compare(client_hash, message['hmac-sha256']) + + @staticmethod + def _verify_json(build_data): + """Verifies that the submitted JSON contains all the proper fields.""" + fields = ['waterfall_url', + 'build_url', + 'project_name', + 'builderName', + 'steps', + 'unsatisfied', + 'revisions', + 'blamelist', + 'result', + 'number', + 'changes', + 'reason', + 'recipients'] + + for field in fields: + if field not in build_data: + logging.error('build_data did not contain field %s' % field) + return False + + step_fields = ['started', + 'text', + 'results', + 'name', + 'logs', + 'urls'] + + if not build_data['steps']: + logging.error('build_data did not contain any steps') + return False + for step in build_data['steps']: + for field in step_fields: + if field not in step: + logging.error('build_step did not contain field %s' % field) + return False + + return True + + def post(self): + blob = self.request.get('json') + if not blob: + self.response.out.write('no json data sent') + logging.error('error no json sent') + self.error(400) + return + + message = {} + try: + message = json.loads(blob) + except ValueError as e: + self.response.out.write('couldn\'t decode json') + logging.error('error decoding incoming json: %s' % e) + self.error(400) + return + + secret = MailerSecret.get_or_insert('mailer_secret').secret + if not secret: + self.response.out.write('unauthorized') + logging.critical('mailer shared secret has not been set!') + self.error(500) + return + + if not self._validate_message(message, self.request.url, secret): + self.response.out.write('unauthorized') + logging.error('incoming message did not validate') + self.error(403) + return + + try: + build_data = json.loads(message['message']) + except ValueError as e: + self.response.out.write('couldn\'t decode payload json') + logging.error('error decoding incoming json: %s' % e) + self.error(400) + return + + if not self._verify_json(build_data): + logging.error('error verifying incoming json: %s' % build_data) + self.response.out.write('json build format is incorrect') + self.error(400) + return + + # Emails can only come from the app ID, so we split on '@' here just in + # case the user specified a full email address. + from_addr_prefix = build_data.get('from_addr', 'buildbot').split('@')[0] + from_addr = from_addr_prefix + '@%s.appspotmail.com' % ( + app_identity.get_application_id()) + + subject_template = build_data.get('subject_template') + status_header = build_data.get('status_header') + + template = gatekeeper_mailer.MailTemplate(build_data['waterfall_url'], + build_data['build_url'], + build_data['project_name'], + from_addr, + subject=subject_template, + status_header=status_header) + + + text_content, html_content, subject = template.genMessageContent(build_data) + + sentries = ['gatekeeper-ng@chromium-gatekeeper-sentry.appspotmail.com', + 'stip@chromium.org'] + + recipients = list(set(build_data['recipients'] + sentries)) + + message = mail.EmailMessage(sender=from_addr, + subject=subject, + to=recipients, + body=text_content, + html=html_content) + logging.info('sending email to %s', ', '.join(recipients)) + logging.info('sending from %s', from_addr) + logging.info('subject is %s', subject) + message.send() + self.response.out.write('email sent') + + +app = webapp2.WSGIApplication([('/mailer', MainPage), + ('/mailer/email', Email)], + debug=True) diff --git a/pool/shard001/Python/0014635_start.py b/pool/shard001/Python/0014635_start.py new file mode 100644 index 0000000000000000000000000000000000000000..0ced778121f33af3e073c9bce40efaad57d352e2 --- /dev/null +++ b/pool/shard001/Python/0014635_start.py @@ -0,0 +1,131 @@ +""" +Script: start.py + +Description: +This script is used to setup a new django-vagrant-box project. +Generates a `secrets.py` settings file and a `secrets.json` secret key. + +Important! Run in this Order: +1. `python start.py` +2. `vagrant up` +3. `vagrant ssh` +4. `./manage.py syncdb` +""" +from random import choice +import textwrap +import json +import os.path +import sys + + +################################################################ +# RENAME PROJECT SCRIPT +################################################################ +def substitute_text(filepath, old, new): + data = '' + with open(filepath, 'r') as fin: + data = fin.read() + with open(filepath, 'w') as fout: + fout.write(data.replace(old, new)) + +def rename_project(): + old_name = 'vanilla' + + # This script should only be run once. + if not os.path.exists(old_name): + sys.exit("Exit: You should only run this script once.") + + # Enter new project name from input. + new_name = raw_input('Enter your project name: ').lower().replace(' ', '') + new_name = new_name if new_name else old_name + filetypes = ('.py', 'bashrc') + + # Substite text in python source files. + for path, dirs, files in os.walk('.'): + + # Ignore hidden files. + if path.startswith('./.'): + continue + + # Match filenames in filetypes, but ignore 'start.py' + for filename in files: + if filename != __file__ and filename.endswith(filetypes): + filepath = '{0}/{1}'.format(path, filename) + substitute_text(filepath, old_name, new_name) + + # Rename project directory. + os.rename(old_name, new_name) + print("\nSuccessfully renamed project to: '{0}'".format(new_name)) + return new_name + + +################################################################ +# GENERATE SECRETS SCRIPT +################################################################ +def create_file(file_path, text): + if not os.path.exists(file_path): + with open(file_path, 'w') as fp: + fp.write(text) + print("File created: '{0}'".format(file_path)) + else: + print("File already exists: '{0}'".format(file_path)) + +def generate_secret_key(): + return ''.join([ + choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') + for i in xrange(50)]) + +def create_secrets_json(): + secrets = json.dumps({ + 'SECRET_KEY': generate_secret_key(), + }, indent=4, sort_keys=True) + create_file('secrets.json', secrets) + +def create_secrets_python(project): + secrets_boilerplate = textwrap.dedent( + ''' + """ + Django settings for sensitive information. + + Please include any Django settings which may contain sensitive + information here. This file is ignore by default, and should not + be added to source control. + + Database Configuration Documentation: + https://docs.djangoproject.com/en/1.7/ref/settings/#databases + """ + + ################################################################ + # SECERETS DATABASE SETTINGS + ################################################################ + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'vagrant', + 'USER': 'vagrant', + 'PASSWORD': '', + 'HOST': '', + 'PORT': '5432' + } + } + + ################################################################ + # SECERETS EMAIL SETTINGS + ################################################################ + DEFAULT_FROM_EMAIL = '' + EMAIL_HOST_USER = '' + EMAIL_HOST_PASSWORD = '' + EMAIL_HOST = 'smtp.gmail.com' + EMAIL_USE_TLS = True + EMAIL_PORT = 587 + ''') + create_file(project+'/settings/secrets.py', secrets_boilerplate) + + +def main(): + project = rename_project() + create_secrets_python(project) + create_secrets_json() + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014637_proc_class.py b/pool/shard001/Python/0014637_proc_class.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4e20df6846d9ff921d913d170edee72c62ba4b --- /dev/null +++ b/pool/shard001/Python/0014637_proc_class.py @@ -0,0 +1,30 @@ +class Processor: + def __init__(self): + pass + + + def initialize(self): + return 'initialize' + + def computeTile(self, x, y, array): + self.spend_some_time() + return 'computeTile-' + str(x) + ',' + str(y) + + def dispose(self): + return 'dispose' + + + def spend_some_time(self): + l = list(range(10000)) + for i in range(10000): + l.reverse() + + def setVal(self, val): + self._val = val + + def getVal(self): + return self._val + + def check1234(self): + return self._val == 1234 + \ No newline at end of file diff --git a/pool/shard001/Python/0014639_time-to-poke.py b/pool/shard001/Python/0014639_time-to-poke.py new file mode 100644 index 0000000000000000000000000000000000000000..6d001c0dc52c6a23381a095df06fd3811fad97da --- /dev/null +++ b/pool/shard001/Python/0014639_time-to-poke.py @@ -0,0 +1,27 @@ +import httplib +import sys +import time + +def poke_it(ip): + conn = httplib.HTTPConnection(ip) + conn.request("GET", "/A") + r1 = conn.getresponse() + return r1.read() + +def sequential_pokes(ip, number_of_pokes): + times = [] + for x in range(0, number_of_pokes): + t0 = time.time() * 1000 + poke_it(ip) + t1 = time.time() * 1000 + times.append(t1-t0) + return times + +if __name__ == "__main__": + ip = sys.argv[1] + num = int(sys.argv[2]) + times = sequential_pokes(ip,num) + for t in times: + print t + +# cProfile.run("sequential_pokes(%s,%s)" % (ip, num)) diff --git a/pool/shard001/Python/0014645_common.py b/pool/shard001/Python/0014645_common.py new file mode 100644 index 0000000000000000000000000000000000000000..aedd014868150fcee8ee417a61f1a59bf23cada7 --- /dev/null +++ b/pool/shard001/Python/0014645_common.py @@ -0,0 +1,63 @@ +""" +Common base elements. +""" +import warnings +import types +import enum +from functools import wraps + + +# rave is stylized, yo. +class raveError(Exception): + """ Base class for any exception that happens in the rave engine. """ + pass + + +# Deprecated stuff. +def deprecated(replacement=None): + """ Deprecate functionality. Calling this function or instantiating this class will issue a warning. """ + if not isinstance(replacement, str): + replacement = replacement.__qualname__ + + def inner(f): + # Format message. + message = '{f} is deprecated and may be removed in future releases.'.format(f=f.__qualname__) + if replacement: + message += ' Use {repl} instead.'.format(repl=replacement) + warn = DeprecationWarning(message) + + # Function? + if isinstance(f, types.FunctionType): + @wraps(f) + def wrapper(*args, **kwargs): + warnings.warn(warn, stacklevel=2) + return f(*args, **kwargs) + + return wrapper + # Class? + else: + initializer = f.__init__ + + @wraps(initializer) + def wrapper(*args, **kwargs): + warnings.warn(warn, stacklevel=2) + return initializer(*args, **kwargs) + + f.__init__ = wrapper + return f + + return inner + + +class IncrementingEnum(enum.Enum): + """ + Enum that automatically assigns an incrementing integer value to its members, + from https://docs.python.org/3/library/enum.html#autonumber. + """ + + def __new__(cls): + value = len(cls.__members__) + 1 + obj = object.__new__(cls) + obj._value_ = value + + return obj diff --git a/pool/shard001/Python/0014647_newround.py b/pool/shard001/Python/0014647_newround.py new file mode 100644 index 0000000000000000000000000000000000000000..333fcec72ae8f4ad92a6928b426ac7881d377547 --- /dev/null +++ b/pool/shard001/Python/0014647_newround.py @@ -0,0 +1,99 @@ +""" +``python-future``: pure Python implementation of Python 3 round(). +""" + +from future.utils import PYPY, PY26, bind_method + +# Use the decimal module for simplicity of implementation (and +# hopefully correctness). +from decimal import Decimal, ROUND_HALF_EVEN + + +def newround(number, ndigits=None): + """ + See Python 3 documentation: uses Banker's Rounding. + + Delegates to the __round__ method if for some reason this exists. + + If not, rounds a number to a given precision in decimal digits (default + 0 digits). This returns an int when called with one argument, + otherwise the same type as the number. ndigits may be negative. + + See the test_round method in future/tests/test_builtins.py for + examples. + """ + return_int = False + if ndigits is None: + return_int = True + ndigits = 0 + if hasattr(number, '__round__'): + return number.__round__(ndigits) + + if ndigits < 0: + raise NotImplementedError('negative ndigits not supported yet') + exponent = Decimal('10') ** (-ndigits) + + if PYPY: + # Work around issue #24: round() breaks on PyPy with NumPy's types + if 'numpy' in repr(type(number)): + number = float(number) + + if not PY26: + d = Decimal.from_float(number).quantize(exponent, + rounding=ROUND_HALF_EVEN) + else: + d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN) + + if return_int: + return int(d) + else: + return float(d) + + +### From Python 2.7's decimal.py. Only needed to support Py2.6: + +def from_float_26(f): + """Converts a float to a decimal number, exactly. + + Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). + Since 0.1 is not exactly representable in binary floating point, the + value is stored as the nearest representable value which is + 0x1.999999999999ap-4. The exact equivalent of the value in decimal + is 0.1000000000000000055511151231257827021181583404541015625. + + >>> Decimal.from_float(0.1) + Decimal('0.1000000000000000055511151231257827021181583404541015625') + >>> Decimal.from_float(float('nan')) + Decimal('NaN') + >>> Decimal.from_float(float('inf')) + Decimal('Infinity') + >>> Decimal.from_float(-float('inf')) + Decimal('-Infinity') + >>> Decimal.from_float(-0.0) + Decimal('-0') + + """ + import math as _math + from decimal import _dec_from_triple # only available on Py2.6 and Py2.7 (not 3.3) + + if isinstance(f, (int, long)): # handle integer inputs + return Decimal(f) + if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float + return Decimal(repr(f)) + if _math.copysign(1.0, f) == 1.0: + sign = 0 + else: + sign = 1 + n, d = abs(f).as_integer_ratio() + # int.bit_length() method doesn't exist on Py2.6: + def bit_length(d): + if d != 0: + return len(bin(abs(d))) - 2 + else: + return 0 + k = bit_length(d) - 1 + result = _dec_from_triple(sign, str(n*5**k), -k) + return result + + +__all__ = ['newround'] diff --git a/pool/shard001/Python/0014648_test_thumbnails.py b/pool/shard001/Python/0014648_test_thumbnails.py new file mode 100644 index 0000000000000000000000000000000000000000..01ba1cbb9527f347673935d8bb917d0cfdb810e0 --- /dev/null +++ b/pool/shard001/Python/0014648_test_thumbnails.py @@ -0,0 +1,63 @@ +from thumbnailer import _resizer +from unittest import TestCase, main +import os.path as path +from PIL import Image + +class ThumbnailerTests(TestCase): + + def path(self, filename): + return path.join(self.img_path, filename) + + def setUp(self): + self.img_path = path.join(path.dirname(__file__), "test_data") + self.img = Image.open(self.path("sample_image.jpg")) + + def testSquare(self): + r = _resizer('square', '100', self.img_path) + output = r.resize(self.img) + self.assertEqual((100, 100), output.size) + + def testExact(self): + r = _resizer('exact', '250x100', self.img_path) + output = r.resize(self.img) + self.assertEqual((250, 100), output.size) + + def testWidth(self): + r = _resizer('aspect', '250x?', self.img_path) + output = r.resize(self.img) + self.assertEqual((250, 166), output.size) + + def testHeight(self): + r = _resizer('aspect', '?x250', self.img_path) + output = r.resize(self.img) + self.assertEqual((375, 250), output.size) + +class ThumbnailerFilenameTest(TestCase): + + def path(self, *parts): + return path.join(self.img_path, *parts) + + def setUp(self): + self.img_path = path.join(path.dirname(__file__), "test_data") + + def testRoot(self): + """Test a file that is in the root of img_path.""" + + r = _resizer('square', '100', self.img_path) + new_name = r.get_thumbnail_name(self.path('sample_image.jpg')) + self.assertEqual('sample_image_square.jpg', new_name) + + def testRootWithSlash(self): + r = _resizer('square', '100', self.img_path + '/') + new_name = r.get_thumbnail_name(self.path('sample_image.jpg')) + self.assertEqual('sample_image_square.jpg', new_name) + + def testSubdir(self): + """Test a file that is in a sub-directory of img_path.""" + + r = _resizer('square', '100', self.img_path) + new_name = r.get_thumbnail_name(self.path('subdir', 'sample_image.jpg')) + self.assertEqual('subdir/sample_image_square.jpg', new_name) + +if __name__=="__main__": + main() diff --git a/pool/shard001/Python/0014649_call.py b/pool/shard001/Python/0014649_call.py new file mode 100644 index 0000000000000000000000000000000000000000..908b64e5eced503ad3a5e2aa459ebfcdac0cdff2 --- /dev/null +++ b/pool/shard001/Python/0014649_call.py @@ -0,0 +1,24 @@ +import random +import time + + +class Call(object): + def __init__(self, method, args, reply=None): + self.method = method + self.args = args + if reply is not None: + self.reply = reply + else: + self.reply = method.response_type() + + + def reset_client_cmd_id(self): + """Set the client command ID if the call is for a read-write method. + + The client command ID provides idempotency protection in conjunction + with the server. + """ + if self.method.is_write: + cmd_id = self.args.header.cmd_id + cmd_id.wall_time = int(time.time() * 1e9) + cmd_id.random = random.randint(0, 1 << 63) diff --git a/pool/shard001/Python/0014656_utils.py b/pool/shard001/Python/0014656_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..92a9a06af36abe0130efab3787a8f704e079874c --- /dev/null +++ b/pool/shard001/Python/0014656_utils.py @@ -0,0 +1,20 @@ +# coding: utf-8 + +from importlib import import_module + + +def import_class(module_path): + """Import class by string path. + + :param str module_path: Path to class to import (e.g. 'speedinfo.profiler.Profiler') + :raises ImportError: if path to class is invalid + :return: imported class + """ + path, class_name = module_path.rsplit(".", 1) + + try: + module = import_module(path) + return getattr(module, class_name) + except (AttributeError, ImportError) as e: + msg = "Could not import '{}'. {}: {}.".format(module_path, e.__class__.__name__, e) + raise ImportError(msg) diff --git a/pool/shard001/Python/0014659_utils.py b/pool/shard001/Python/0014659_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..001121f9c8467e3b534d5089ceca9004c9efcc14 --- /dev/null +++ b/pool/shard001/Python/0014659_utils.py @@ -0,0 +1,26 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import absolute_import, division, print_function + +import six + + +def _truncate_digest(digest, order_bits): + digest_len = len(digest) + + if 8 * digest_len > order_bits: + digest_len = (order_bits + 7) // 8 + digest = digest[:digest_len] + + if 8 * digest_len > order_bits: + rshift = 8 - (order_bits & 0x7) + assert 0 < rshift < 8 + + mask = 0xFF >> rshift << rshift + + # Set the bottom rshift bits to 0 + digest = digest[:-1] + six.int2byte(six.indexbytes(digest, -1) & mask) + + return digest diff --git a/pool/shard001/Python/0014660_InstallUpstreamKernel.py b/pool/shard001/Python/0014660_InstallUpstreamKernel.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1e14dfdef2f0c7d5e38ae91b930f62b6031da3 --- /dev/null +++ b/pool/shard001/Python/0014660_InstallUpstreamKernel.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +# OpenPOWER Automated Test Project +# +# Contributors Listed Below - COPYRIGHT 2018 +# [+] International Business Machines 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. +# + +import unittest +import os + +try: + from urllib.parse import urlparse +except ImportError: + from urllib.parse import urlparse + +import OpTestConfiguration +import OpTestLogger +from common.OpTestSystem import OpSystemState +from common.OpTestSOL import OpSOLMonitorThread +from common.OpTestInstallUtil import InstallUtil + +log = OpTestLogger.optest_logger_glob.get_logger(__name__) + + +class InstallUpstreamKernel(unittest.TestCase): + def setUp(self): + self.conf = OpTestConfiguration.conf + self.cv_HOST = self.conf.host() + self.cv_SYSTEM = self.conf.system() + self.host_cmd_timeout = self.conf.args.host_cmd_timeout + self.repo = self.conf.args.git_repo + self.branch = self.conf.args.git_branch + self.home = self.conf.args.git_home + self.config = self.conf.args.git_repoconfig + self.config_path = self.conf.args.git_repoconfigpath + self.disk = self.conf.args.host_scratch_disk + self.patch = self.conf.args.git_patch + self.use_kexec = self.conf.args.use_kexec + self.append_kernel_cmdline = self.conf.args.append_kernel_cmdline + if self.config_path: + self.config = "olddefconfig" + if not self.repo: + self.fail("Provide git repo of kernel to install") + if not (self.conf.args.host_ip and self.conf.args.host_user and self.conf.args.host_password): + self.fail( + "Provide host ip user details refer, --host-{ip,user,password}") + if self.disk: + OpIU = InstallUtil() + self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL) + log.debug("Set given disk as default bootable disk") + OpIU.set_bootable_disk(self.disk) + self.console_thread = OpSOLMonitorThread(1, "console") + + def runTest(self): + def is_url(path): + ''' + param path: path to download + return: boolean True if given path is url False Otherwise + ''' + valid_schemes = ['http', 'https', 'git', 'ftp'] + if urlparse(path).scheme in valid_schemes: + return True + return False + self.cv_SYSTEM.goto_state(OpSystemState.OFF) + self.cv_SYSTEM.goto_state(OpSystemState.OS) + self.console_thread.start() + try: + con = self.cv_SYSTEM.cv_HOST.get_ssh_connection() + try: + onlinecpus = int(con.run_command( + "lscpu --online -e|wc -l")[-1]) + except Exception: + onlinecpus = 20 + log.debug("Downloading linux kernel") + # Compile and install given kernel + linux_path = os.path.join(self.home, "linux") + con.run_command("[ -d %s ] || mkdir -p %s" % + (self.home, self.home)) + con.run_command("if [ -d %s ];then rm -rf %s;fi" % + (linux_path, linux_path), timeout=120) + con.run_command("cd %s && git clone --depth 1 %s -b %s linux" % + (self.home, self.repo, self.branch), timeout=self.host_cmd_timeout) + con.run_command("cd %s" % linux_path) + if self.patch: + patch_file = self.patch.split("/")[-1] + if is_url(self.patch): + con.run_command("wget %s -O %s" % (self.patch, patch_file)) + else: + self.cv_HOST.copy_test_file_to_host( + self.patch, dstdir=linux_path) + log.debug("Applying given patch") + con.run_command("git am %s" % + os.path.join(linux_path, patch_file)) + log.debug("Downloading linux kernel config") + if self.config_path: + if is_url(self.config_path): + con.run_command("wget %s -O .config" % self.config_path) + else: + self.cv_HOST.copy_test_file_to_host( + self.config_path, dstdir=os.path.join(linux_path, ".config")) + con.run_command("make %s" % self.config) + log.debug("Compile and install linux kernel") + con.run_command("make -j %d -s && make modules && make modules_install && make install" % + onlinecpus, timeout=self.host_cmd_timeout) + if not self.use_kexec: + # FIXME: Handle distributions which do not support grub + con.run_command( + 'grubby --set-default /boot/vmlinuz-`cat include/config/kernel.release 2> /dev/null`') + con.run_command( + "grub2-mkconfig --output=/boot/grub2/grub.cfg") + log.debug("Rebooting after kernel install...") + self.console_thread.console_terminate() + con.close() + self.cv_SYSTEM.goto_state(OpSystemState.OFF) + self.cv_SYSTEM.goto_state(OpSystemState.OS) + else: + self.console_thread.console_terminate() + cmdline = con.run_command("cat /proc/cmdline")[-1] + if self.append_kernel_cmdline: + cmdline += " %s" % self.append_kernel_cmdline + kern_rel_str = con.run_command( + "cat %s/include/config/kernel.release" % linux_path)[-1] + initrd_file = con.run_command( + "ls -l /boot/initr*-%s.img" % kern_rel_str)[-1].split(" ")[-1] + kexec_cmdline = "kexec --initrd %s --command-line=\"%s\" /boot/vmlinuz-%s -l" % ( + initrd_file, cmdline, kern_rel_str) + # Let's makesure we set the default boot index to current kernel + # to avoid leaving host in unstable state incase boot failure + con.run_command( + 'grubby --set-default /boot/vmlinuz-`uname -r 2> /dev/null`') + con.run_command(kexec_cmdline) + con.close() + raw_pty = self.cv_SYSTEM.console.get_console() + raw_pty.sendline("kexec -e") + raw_pty.expect("login:", timeout=600) + con = self.cv_SYSTEM.cv_HOST.get_ssh_connection() + res = con.run_command("uname -r") + log.info("Installed upstream kernel version: %s", res[-1]) + if self.conf.args.host_cmd: + con.run_command(self.conf.args.host_cmd, + timeout=self.host_cmd_timeout) + self.cv_HOST.host_gather_opal_msg_log() + self.cv_HOST.host_gather_kernel_log() + finally: + if self.console_thread.isAlive(): + self.console_thread.console_terminate() diff --git a/pool/shard001/Python/0014662_main.py b/pool/shard001/Python/0014662_main.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ae8bfa3fdd9ca6a6eafdbd443028940cd99bd3 --- /dev/null +++ b/pool/shard001/Python/0014662_main.py @@ -0,0 +1,16 @@ +from HER import HER +from scipy import misc +import matplotlib.pyplot as plt + +image = misc.imread('../data/test/08.png', mode='RGB') + +plt.figure +plt.imshow(image) +plt.draw() + +plt.figure +HER(image) +#plt.imshow(HER.HER(image)) + +print('-------------FINISHED COMPUTATION-------------') +plt.show() diff --git a/pool/shard001/Python/0014663_light.py b/pool/shard001/Python/0014663_light.py new file mode 100644 index 0000000000000000000000000000000000000000..0b944a682d4383003aada3abbdd682561e049bb5 --- /dev/null +++ b/pool/shard001/Python/0014663_light.py @@ -0,0 +1,114 @@ +"""Support for Freedompro light.""" +import json + +from pyfreedompro import put_state + +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_HS_COLOR, + COLOR_MODE_BRIGHTNESS, + COLOR_MODE_HS, + COLOR_MODE_ONOFF, + LightEntity, +) +from homeassistant.const import CONF_API_KEY +from homeassistant.core import callback +from homeassistant.helpers import aiohttp_client +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .const import DOMAIN + + +async def async_setup_entry(hass, entry, async_add_entities): + """Set up Freedompro light.""" + api_key = entry.data[CONF_API_KEY] + coordinator = hass.data[DOMAIN][entry.entry_id] + async_add_entities( + Device(hass, api_key, device, coordinator) + for device in coordinator.data + if device["type"] == "lightbulb" + ) + + +class Device(CoordinatorEntity, LightEntity): + """Representation of an Freedompro light.""" + + def __init__(self, hass, api_key, device, coordinator): + """Initialize the Freedompro light.""" + super().__init__(coordinator) + self._session = aiohttp_client.async_get_clientsession(hass) + self._api_key = api_key + self._attr_name = device["name"] + self._attr_unique_id = device["uid"] + self._attr_device_info = { + "name": self.name, + "identifiers": { + (DOMAIN, self.unique_id), + }, + "model": device["type"], + "manufacturer": "Freedompro", + } + self._attr_is_on = False + self._attr_brightness = 0 + color_mode = COLOR_MODE_ONOFF + if "hue" in device["characteristics"]: + color_mode = COLOR_MODE_HS + elif "brightness" in device["characteristics"]: + color_mode = COLOR_MODE_BRIGHTNESS + self._attr_color_mode = color_mode + self._attr_supported_color_modes = {color_mode} + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + device = next( + ( + device + for device in self.coordinator.data + if device["uid"] == self._attr_unique_id + ), + None, + ) + if device is not None and "state" in device: + state = device["state"] + if "on" in state: + self._attr_is_on = state["on"] + if "brightness" in state: + self._attr_brightness = round(state["brightness"] / 100 * 255) + if "hue" in state and "saturation" in state: + self._attr_hs_color = (state["hue"], state["saturation"]) + super()._handle_coordinator_update() + + async def async_added_to_hass(self) -> None: + """When entity is added to hass.""" + await super().async_added_to_hass() + self._handle_coordinator_update() + + async def async_turn_on(self, **kwargs): + """Async function to set on to light.""" + payload = {"on": True} + if ATTR_BRIGHTNESS in kwargs: + payload["brightness"] = round(kwargs[ATTR_BRIGHTNESS] / 255 * 100) + if ATTR_HS_COLOR in kwargs: + payload["saturation"] = round(kwargs[ATTR_HS_COLOR][1]) + payload["hue"] = round(kwargs[ATTR_HS_COLOR][0]) + payload = json.dumps(payload) + await put_state( + self._session, + self._api_key, + self._attr_unique_id, + payload, + ) + await self.coordinator.async_request_refresh() + + async def async_turn_off(self, **kwargs): + """Async function to set off to light.""" + payload = {"on": False} + payload = json.dumps(payload) + await put_state( + self._session, + self._api_key, + self._attr_unique_id, + payload, + ) + await self.coordinator.async_request_refresh() diff --git a/pool/shard001/Python/0014665_enter_qty.py b/pool/shard001/Python/0014665_enter_qty.py new file mode 100644 index 0000000000000000000000000000000000000000..505aed99198dffe4e8bcd0fa600971f75426bff6 --- /dev/null +++ b/pool/shard001/Python/0014665_enter_qty.py @@ -0,0 +1,39 @@ +import hycohanz as hfss +import os.path + +raw_input('Press "Enter" to connect to HFSS.>') + +[oAnsoftApp, oDesktop] = hfss.setup_interface() + +raw_input('Press "Enter" to open an example project.>') + +filepath = os.path.join(os.path.abspath(os.path.curdir), 'WR284.hfss') + +oProject = hfss.open_project(oDesktop, filepath) + +raw_input('Press "Enter" to set the active design to HFSSDesign1.>') + +oDesign = hfss.set_active_design(oProject, 'HFSSDesign1') + +raw_input('Press "Enter" to get a handle to the Fields Reporter module.>') + +oFieldsReporter = hfss.get_module(oDesign, 'FieldsReporter') + +raw_input('Press "Enter" to enter the field quantity "Jvol" in the Fields Calculator.>') + +hfss.enter_qty(oFieldsReporter, 'Jvol') + +print('Open the calculator to verify that the Calculator input reads "CVc : "') + +raw_input('Press "Enter" to close the example project.>') + +hfss.close_project_byhandle(oDesktop, oProject) + +raw_input('Press "Enter" to quit HFSS.>') + +hfss.quit_application(oDesktop) + +del oDesign +del oProject +del oDesktop +del oAnsoftApp diff --git a/pool/shard001/Python/0014672_urls.py b/pool/shard001/Python/0014672_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..77f32778d7b05300e6582216fd887e6e9e160dae --- /dev/null +++ b/pool/shard001/Python/0014672_urls.py @@ -0,0 +1,31 @@ +"""oscar_webstore_root 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 include, url +from django.contrib import admin +from oscar.app import application +from django.conf.urls.static import static +from django.conf import settings + +urlpatterns = [ + url(r'^i18n/', include('django.conf.urls.i18n')), + + # The Django admin is not officially supported; expect breakage. + # Nonetheless, it's often useful for debugging. + url(r'^admin/', include(admin.site.urls)), + + url(r'', include(application.urls)), +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ No newline at end of file diff --git a/pool/shard001/Python/0014673_listing7_2.py b/pool/shard001/Python/0014673_listing7_2.py new file mode 100644 index 0000000000000000000000000000000000000000..f177a879fb680f7b7980af178b46d3af6145cb20 --- /dev/null +++ b/pool/shard001/Python/0014673_listing7_2.py @@ -0,0 +1,20 @@ +# Use a better method to count the cities within 16,000 meters of a volcano, +# because it doesn't double-count stuff. + +import ogr + +# Open the layers as in listing 7.1 instead of reset reading. +shp_ds = ogr.Open(r'D:\osgeopy-data\US') +volcano_lyr = shp_ds.GetLayer('us_volcanos_albers') +cities_lyr = shp_ds.GetLayer('cities_albers') + +# This time, add each buffer to a multipolygon instead of a temporary later. +multipoly = ogr.Geometry(ogr.wkbMultiPolygon) +for volcano_feat in volcano_lyr: + buff_geom = volcano_feat.geometry().Buffer(16000) + multipoly.AddGeometry(buff_geom) + +# Then union all of the buffers together to get one polygon which you can use +# as a spatial filter. +cities_lyr.SetSpatialFilter(multipoly.UnionCascaded()) +print('Cities: {}'.format(cities_lyr.GetFeatureCount())) diff --git a/pool/shard001/Python/0014677_guardduty.py b/pool/shard001/Python/0014677_guardduty.py new file mode 100644 index 0000000000000000000000000000000000000000..88396e7368e9c5e27c926f5706ea9d0fb4b79e57 --- /dev/null +++ b/pool/shard001/Python/0014677_guardduty.py @@ -0,0 +1,180 @@ +"""Raw representations of every data type in the AWS GuardDuty service. + +See Also: + `AWS developer guide for GuardDuty + `_ + +This file is automatically generated, and should not be directly edited. +""" + +from attr import attrib +from attr import attrs + +from ..core import ATTRSCONFIG +from ..core import Resource +from ..core import ResourceProperties +from ..core import create_object_converter + +__all__ = [ + "Detector", + "DetectorProperties", + "Filter", + "FilterProperties", + "IPSet", + "IPSetProperties", + "Master", + "MasterProperties", + "Member", + "MemberProperties", + "ThreatIntelSet", + "ThreatIntelSetProperties", +] + + +@attrs(**ATTRSCONFIG) +class DetectorProperties(ResourceProperties): + Enable = attrib(default=None) + FindingPublishingFrequency = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class Detector(Resource): + """A Detector for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for Detector + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::Detector" + + Properties: DetectorProperties = attrib( + factory=DetectorProperties, + converter=create_object_converter(DetectorProperties), + ) + + +@attrs(**ATTRSCONFIG) +class FilterProperties(ResourceProperties): + Action = attrib(default=None) + Description = attrib(default=None) + DetectorId = attrib(default=None) + FindingCriteria = attrib(default=None) + Name = attrib(default=None) + Rank = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class Filter(Resource): + """A Filter for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for Filter + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::Filter" + + Properties: FilterProperties = attrib( + factory=FilterProperties, converter=create_object_converter(FilterProperties) + ) + + +@attrs(**ATTRSCONFIG) +class IPSetProperties(ResourceProperties): + Activate = attrib(default=None) + DetectorId = attrib(default=None) + Format = attrib(default=None) + Location = attrib(default=None) + Name = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class IPSet(Resource): + """A Ip Set for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for IPSet + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::IPSet" + + Properties: IPSetProperties = attrib( + factory=IPSetProperties, converter=create_object_converter(IPSetProperties) + ) + + +@attrs(**ATTRSCONFIG) +class MasterProperties(ResourceProperties): + DetectorId = attrib(default=None) + InvitationId = attrib(default=None) + MasterId = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class Master(Resource): + """A Master for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for Master + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::Master" + + Properties: MasterProperties = attrib( + factory=MasterProperties, converter=create_object_converter(MasterProperties) + ) + + +@attrs(**ATTRSCONFIG) +class MemberProperties(ResourceProperties): + DetectorId = attrib(default=None) + DisableEmailNotification = attrib(default=None) + Email = attrib(default=None) + MemberId = attrib(default=None) + Message = attrib(default=None) + Status = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class Member(Resource): + """A Member for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for Member + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::Member" + + Properties: MemberProperties = attrib( + factory=MemberProperties, converter=create_object_converter(MemberProperties) + ) + + +@attrs(**ATTRSCONFIG) +class ThreatIntelSetProperties(ResourceProperties): + Activate = attrib(default=None) + DetectorId = attrib(default=None) + Format = attrib(default=None) + Location = attrib(default=None) + Name = attrib(default=None) + + +@attrs(**ATTRSCONFIG) +class ThreatIntelSet(Resource): + """A Threat Intel Set for GuardDuty. + + See Also: + `AWS Cloud Formation documentation for ThreatIntelSet + `_ + """ + + RESOURCE_TYPE = "AWS::GuardDuty::ThreatIntelSet" + + Properties: ThreatIntelSetProperties = attrib( + factory=ThreatIntelSetProperties, + converter=create_object_converter(ThreatIntelSetProperties), + ) diff --git a/pool/shard001/Python/0014678_home_page.py b/pool/shard001/Python/0014678_home_page.py new file mode 100644 index 0000000000000000000000000000000000000000..d8925f9c083782c5ab290a7114a68f5533e20512 --- /dev/null +++ b/pool/shard001/Python/0014678_home_page.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +from selenium.webdriver.common.by import By +from browser import Browser +import time + +class HomePageLocator(object): + # Home Page Locators + + HEADER_TEXT = (By.XPATH, "//h1") + SEARCH_FIELD = (By.ID, "term") + SUBMIT_BUTTON = (By.ID, "submit") + + +class HomePage(Browser): + # Home Page Actions + + def fill(self, text, *locator): + wd = self.driver + wd.find_element(*locator).send_keys(text) + + def click_element(self, *locator): + wd = self.driver + wd.find_element(*locator).click() + + def navigate(self, address): + wd = self.driver + wd.get(address) + + def get_page_title(self): + wd = self.driver + return wd.title + + def search(self, search_term): + wd = self.driver + self.fill(search_term, *HomePageLocator.SEARCH_FIELD) + self.click_element(*HomePageLocator.SUBMIT_BUTTON) + + def login_main_page(self, username="atom2k@gmail.com1", password="111111"): + wd = self.driver + wd.find_element_by_css_selector("a.login__a").click() + wd.find_element_by_name("c_l").click() + wd.find_element_by_name("c_l").clear() + wd.find_element_by_name("c_l").send_keys(username) + wd.find_element_by_name("c_p").click() + wd.find_element_by_name("c_p").clear() + wd.find_element_by_name("c_p").send_keys(password) + wd.find_element_by_css_selector("a.sbm").click() + + def logout(self): + wd = self.driver + wd.find_element_by_css_selector("span.user-profile__span").click() + wd.find_element_by_css_selector("li.user-profile__item.logout > a.user-profile__a").click() + + def assert_balls(self): + wd = self.driver + return (len(wd.find_elements_by_id("user-points") !=0)) + + def enter_profile_in_main_page(self): + wd = self.driver + if wd.current_url.endswith("/profile/") and len(wd.find_elements_by_css_selector("a.bttn")) > 0: + return + wd.find_element_by_css_selector("span.user-profile__span").click() + wd.find_element_by_css_selector("span.user-profile__title").click() + + def del_address_in_profile(self): + wd = self.driver + wd.find_element_by_css_selector("a.delete_uaddress").click() + time.sleep(2) + alert = wd.switch_to_alert() + alert.accept() + time.sleep(2) \ No newline at end of file diff --git a/pool/shard001/Python/0014679_assign_manual_quants.py b/pool/shard001/Python/0014679_assign_manual_quants.py new file mode 100644 index 0000000000000000000000000000000000000000..e58e91ea315de337eb9052f80e3816e038af3024 --- /dev/null +++ b/pool/shard001/Python/0014679_assign_manual_quants.py @@ -0,0 +1,243 @@ +# Copyright 2015 Mikel Arregi - AvanzOSC +# Copyright 2015 Oihane Crucelaegui - AvanzOSC +# Copyright 2018 Fanha Giang +# Copyright 2018 Tecnativa - Vicent Cubells +# Copyright 2018 Tecnativa - Pedro M. Baeza +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html + +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError +from odoo.tools.float_utils import float_compare + + +class AssignManualQuants(models.TransientModel): + _name = "assign.manual.quants" + _description = "Assign Manual Quants" + + @api.constrains("quants_lines") + def _check_qty(self): + precision_digits = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + for record in self.filtered("quants_lines"): + if ( + float_compare( + record.lines_qty, + record.move_id.product_qty, + precision_digits=precision_digits, + ) + > 0 + ): + raise ValidationError(_("Quantity is higher than the needed one")) + + @api.depends("move_id", "quants_lines", "quants_lines.qty") + def _compute_qties(self): + for record in self: + record.lines_qty = sum( + record.quants_lines.filtered("selected").mapped("qty") + ) + record.move_qty = record.move_id.product_qty - record.lines_qty + + lines_qty = fields.Float( + string="Reserved qty", + compute="_compute_qties", + digits="Product Unit of Measure", + ) + move_qty = fields.Float( + string="Remaining qty", + compute="_compute_qties", + digits="Product Unit of Measure", + ) + quants_lines = fields.One2many( + "assign.manual.quants.lines", "assign_wizard", string="Quants" + ) + move_id = fields.Many2one( + comodel_name="stock.move", + string="Move", + ) + + def assign_quants(self): + move = self.move_id + move._do_unreserve() + for line in self.quants_lines: + line._assign_quant_line() + if move.picking_type_id.auto_fill_qty_done: + # Auto-fill all lines as done + for ml in move.move_line_ids: + ml.qty_done = ml.product_qty + move._recompute_state() + move.mapped("picking_id")._compute_state() + return {} + + @api.model + def default_get(self, fields): + res = super(AssignManualQuants, self).default_get(fields) + move = self.env["stock.move"].browse(self.env.context["active_id"]) + available_quants = self.env["stock.quant"].search( + [ + ("location_id", "child_of", move.location_id.id), + ("product_id", "=", move.product_id.id), + ("quantity", ">", 0), + ] + ) + q_lines = [] + for quant in available_quants: + line = self._prepare_wizard_line(move, quant) + q_lines.append(line) + res.update({"quants_lines": [(0, 0, x) for x in q_lines], "move_id": move.id}) + return res + + @api.model + def _prepare_wizard_line(self, move, quant): + line = { + "quant_id": quant.id, + "on_hand": quant.quantity, + "location_id": quant.location_id.id, + "lot_id": quant.lot_id.id, + "package_id": quant.package_id.id, + "owner_id": quant.owner_id.id, + "selected": False, + } + move_lines = move.move_line_ids.filtered( + lambda ml: ( + ml.location_id == quant.location_id + and ml.lot_id == quant.lot_id + and ml.owner_id == quant.owner_id + and ml.package_id == quant.package_id + ) + ) + line["qty"] = sum(move_lines.mapped("product_uom_qty")) + line["selected"] = bool(line["qty"]) + line["reserved"] = quant.reserved_quantity - line["qty"] + return line + + +class AssignManualQuantsLines(models.TransientModel): + _name = "assign.manual.quants.lines" + _description = "Assign Manual Quants Lines" + _rec_name = "quant_id" + + assign_wizard = fields.Many2one( + comodel_name="assign.manual.quants", + string="Move", + required=True, + ondelete="cascade", + ) + quant_id = fields.Many2one( + comodel_name="stock.quant", + string="Quant", + required=True, + ondelete="cascade", + ) + location_id = fields.Many2one( + comodel_name="stock.location", + string="Location", + related="quant_id.location_id", + groups="stock.group_stock_multi_locations", + ) + lot_id = fields.Many2one( + comodel_name="stock.production.lot", + string="Lot", + related="quant_id.lot_id", + groups="stock.group_production_lot", + ) + package_id = fields.Many2one( + comodel_name="stock.quant.package", + string="Package", + related="quant_id.package_id", + groups="stock.group_tracking_lot", + ) + owner_id = fields.Many2one( + comodel_name="res.partner", + string="Owner", + related="quant_id.owner_id", + groups="stock.group_tracking_owner", + ) + # This is not correctly shown as related or computed, so we make it regular + on_hand = fields.Float( + readonly=True, + string="On Hand", + digits="Product Unit of Measure", + ) + reserved = fields.Float(string="Others Reserved", digits="Product Unit of Measure") + selected = fields.Boolean(string="Select") + qty = fields.Float(string="QTY", digits="Product Unit of Measure") + + @api.onchange("selected") + def _onchange_selected(self): + for record in self: + if not record.selected: + record.qty = 0 + elif not record.qty: + # This takes current "snapshot" situation, so that we don't + # have to compute each time if current reserved quantity is + # for this current move. If other operations change available + # quantity on quant, a constraint would be raised later on + # validation. + quant_qty = record.on_hand - record.reserved + remaining_qty = record.assign_wizard.move_qty + record.qty = min(quant_qty, remaining_qty) + + @api.constrains("qty") + def _check_qty(self): + precision_digits = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + for record in self.filtered("qty"): + quant = record.quant_id + move_lines = record.assign_wizard.move_id.move_line_ids.filtered( + lambda ml: ( + ml.location_id == quant.location_id and ml.lot_id == quant.lot_id + ) + ) + reserved = quant.reserved_quantity - sum( + move_lines.mapped("product_uom_qty") + ) + if ( + float_compare( + record.qty, + record.quant_id.quantity - reserved, + precision_digits=precision_digits, + ) + > 0 + ): + raise ValidationError( + _( + "Selected line quantity is higher than the available " + "one. Maybe an operation with this product has been " + "done meanwhile or you have manually increased the " + "suggested value." + ) + ) + + def _assign_quant_line(self): + self.ensure_one() + quant = self.env["stock.quant"] + precision_digits = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + move = self.assign_wizard.move_id + if float_compare(self.qty, 0.0, precision_digits=precision_digits) > 0: + available_quantity = quant._get_available_quantity( + move.product_id, + self.location_id, + lot_id=self.lot_id, + package_id=self.package_id, + owner_id=self.owner_id, + ) + if ( + float_compare( + available_quantity, 0.0, precision_digits=precision_digits + ) + <= 0 + ): + return + move._update_reserved_quantity( + self.qty, + available_quantity, + self.location_id, + lot_id=self.lot_id, + package_id=self.package_id, + owner_id=self.owner_id, + strict=True, + ) diff --git a/pool/shard001/Python/0014692_qos.py b/pool/shard001/Python/0014692_qos.py new file mode 100644 index 0000000000000000000000000000000000000000..25d049fc2c9fb84513f9740f53ed5cf313e0c02d --- /dev/null +++ b/pool/shard001/Python/0014692_qos.py @@ -0,0 +1,187 @@ +# Copyright 2014 Red Hat, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# Refer to the README and COPYING files for full details of the license +# +from __future__ import absolute_import +import errno +import os +from distutils.version import StrictVersion + +from vdsm import netinfo + +from .. import tc +from .. import models +_NON_VLANNED_ID = 5000 +_DEFAULT_CLASSID = '%x' % _NON_VLANNED_ID +_ROOT_QDISC_HANDLE = '%x:' % 5001 # Leave 0 free for leaf qdisc of vlan tag 0 +_FAIR_QDISC_KIND = 'fq_codel' if (StrictVersion(os.uname()[2].split('-')[0]) > + StrictVersion('3.5.0')) else 'sfq' +_SHAPING_QDISC_KIND = 'hfsc' + + +def configure_outbound(qosOutbound, top_device): + """Adds the qosOutbound configuration to the backing device (be it bond + or nic). Adds a class and filter for default traffic if necessary""" + vlan_tag = models.hierarchy_vlan_tag(top_device) + device = models.hierarchy_backing_device(top_device).name + root_qdisc = _root_qdisc(tc._qdiscs(device)) + class_id = '%x' % (_NON_VLANNED_ID if vlan_tag is None else vlan_tag) + if not root_qdisc or root_qdisc['kind'] != _SHAPING_QDISC_KIND: + _fresh_qdisc_conf_out(device, vlan_tag, class_id, qosOutbound) + else: + _qdisc_conf_out(device, root_qdisc['handle'], vlan_tag, class_id, + qosOutbound) + + +def remove_outbound(top_device): + """Removes the qosOutbound configuration from the device and restores + pfifo_fast if it was the last QoSed network on the device""" + vlan_tag = models.hierarchy_vlan_tag(top_device) + device = models.hierarchy_backing_device(top_device).name + class_id = '%x' % (_NON_VLANNED_ID if vlan_tag is None else vlan_tag) + MISSING_OBJ_ERR_CODES = (errno.EINVAL, errno.ENOENT, errno.EOPNOTSUPP) + + try: + tc.filter.delete( + device, pref=_NON_VLANNED_ID if vlan_tag is None else vlan_tag) + except tc.TrafficControlException as tce: + if tce.errCode not in MISSING_OBJ_ERR_CODES: # No filter exists + raise + + device_qdiscs = list(tc._qdiscs(device)) + if not device_qdiscs: + return + root_qdisc_handle = _root_qdisc(device_qdiscs)['handle'] + try: + tc.cls.delete(device, classid=root_qdisc_handle + class_id) + except tc.TrafficControlException as tce: + if tce.errCode not in MISSING_OBJ_ERR_CODES: # No class exists + raise + + if not _uses_classes(device, root_qdisc_handle=root_qdisc_handle): + try: + tc._qdisc_del(device) + tc._qdisc_del(device, kind='ingress') + except tc.TrafficControlException as tce: + if tce.errCode not in MISSING_OBJ_ERR_CODES: # No qdisc + raise + + +def _uses_classes(device, root_qdisc_handle=None): + """Returns true iff there's traffic classes in the device, ignoring the + root class and a default unused class""" + if root_qdisc_handle is None: + root_qdisc_handle = _root_qdisc(tc._qdiscs(device))['handle'] + classes = [cls for cls in tc.classes(device, parent=root_qdisc_handle) if + not cls.get('root')] + return (classes and + not(len(classes) == 1 and not netinfo.ifaceUsed(device) and + classes[0]['handle'] == root_qdisc_handle + _DEFAULT_CLASSID)) + + +def _fresh_qdisc_conf_out(dev, vlan_tag, class_id, qos): + """Replaces the dev qdisc with hfsc and sets up the shaping""" + # Use deletion + addition to flush children classes and filters + try: + tc.qdisc.delete(dev) # Deletes the root qdisc by default + except tc.TrafficControlException as tce: + if tce.errCode != errno.ENOENT: + raise + try: + tc.qdisc.delete(dev, kind='ingress') # Deletes the ingress qdisc + except tc.TrafficControlException as tce: + if tce.errCode not in (errno.EINVAL, + errno.ENOENT): # No ingress exists + raise + + tc.qdisc.add(dev, _SHAPING_QDISC_KIND, handle='0x' + _ROOT_QDISC_HANDLE, + default='%#x' % _NON_VLANNED_ID) + tc.qdisc.add(dev, 'ingress') + + # Add traffic classes + _add_hfsc_cls(dev, _ROOT_QDISC_HANDLE, class_id, **qos) + if class_id != _DEFAULT_CLASSID: # We need to add a default class + _add_hfsc_cls(dev, _ROOT_QDISC_HANDLE, _DEFAULT_CLASSID, ls=qos['ls']) + + # Add filters to move the traffic into the classes we just created + _add_non_vlanned_filter(dev, _ROOT_QDISC_HANDLE) + if class_id != _DEFAULT_CLASSID: + _add_vlan_filter(dev, vlan_tag, _ROOT_QDISC_HANDLE, class_id) + + # Add inside intra-class fairness qdisc (fq_codel/sfq) + _add_fair_qdisc(dev, _ROOT_QDISC_HANDLE, class_id) + if class_id != _DEFAULT_CLASSID: + _add_fair_qdisc(dev, _ROOT_QDISC_HANDLE, _DEFAULT_CLASSID) + + +def _qdisc_conf_out(dev, root_qdisc_handle, vlan_tag, class_id, qos): + """Adds the traffic class and filtering to the current hfsc qdisc""" + flow_id = ':' + class_id + filters = [filt for filt in tc._filters(dev, parent=root_qdisc_handle) if + 'u32' in filt and filt['u32'].get('flowid') == flow_id] + + # Clear up any previous filters to the class + for filt in filters: + try: + tc.filter.delete(dev, filt['pref'], parent=root_qdisc_handle) + except tc.TrafficControlException as tce: + if tce.errCode != errno.EINVAL: # no filters exist -> EINVAL + raise + + # Clear the class in case it exists + try: + tc.cls.delete(dev, classid=root_qdisc_handle + class_id) + except tc.TrafficControlException as tce: + if tce.errCode != errno.ENOENT: + raise + + _add_hfsc_cls(dev, root_qdisc_handle, class_id, **qos) + if class_id == _DEFAULT_CLASSID: + _add_non_vlanned_filter(dev, root_qdisc_handle) + else: + _add_vlan_filter(dev, vlan_tag, root_qdisc_handle, class_id) + _add_fair_qdisc(dev, root_qdisc_handle, class_id) + + +def _add_vlan_filter(dev, vlan_tag, root_qdisc_handle, class_id): + tc.filter.replace(dev, parent=root_qdisc_handle, protocol='802.1q', + pref=vlan_tag, + u32=['match', 'u16', '0x%x' % vlan_tag, '0xFFF', 'at', + '-4', 'flowid', '0x' + class_id]) + + +def _add_non_vlanned_filter(dev, root_qdisc_handle): + tc.filter.replace(dev, parent=root_qdisc_handle, protocol='all', + pref=_NON_VLANNED_ID, + u32=['match', 'u8', '0', '0', 'flowid', + '%#x' % _NON_VLANNED_ID]) + + +def _add_fair_qdisc(dev, root_qdisc_handle, class_id): + tc.qdisc.add(dev, _FAIR_QDISC_KIND, parent=root_qdisc_handle + class_id, + handle=class_id + ':') + + +def _add_hfsc_cls(dev, root_qdisc_handle, class_id, **qos_opts): + tc.cls.add(dev, _SHAPING_QDISC_KIND, parent=root_qdisc_handle, + classid=root_qdisc_handle + class_id, **qos_opts) + + +def _root_qdisc(qdiscs): + for qdisc in qdiscs: + if 'root' in qdisc: + return qdisc diff --git a/pool/shard001/Python/0014693_neymanPearson2.py b/pool/shard001/Python/0014693_neymanPearson2.py new file mode 100644 index 0000000000000000000000000000000000000000..30149dd1a88252e413d16253e5d15da06de5f87d --- /dev/null +++ b/pool/shard001/Python/0014693_neymanPearson2.py @@ -0,0 +1,61 @@ +# Convert Neyman-Pearson testing paradigm(Fig 5.15 (a)) to python/JAX +# Author: Garvit9000c + +import superimport + +from scipy.stats import multivariate_normal as gaussprob +import numpy as np +import matplotlib.pyplot as plt +import pyprobml_utils as pml + +#constants +pi=np.pi +sigma=1.5 +xmin = -4 +xmax = 8 +ymin = 0 +ymax = 0.3 +res = 0.01 + +#Domain +x=np.arange(xmin,xmax,res) + +#functions +y1=gaussprob.pdf(x, 0, sigma**2) +y2=gaussprob.pdf(x, 4, sigma**2) + +#Axes Limits +plt.ylim(ymin,ymax) +plt.xlim(xmin,xmax) + +#Ploting Curve +plt.plot(x,y1,'b') #Curve_B +plt.plot(x,y2,'r') #Curve_A + + +plt.vlines(x=2.3, ymin=0, ymax=0.5, linewidth=1.5, color='k') +plt.xticks([2.3],['$X^*$'],size=18) +plt.yticks([]) + +#Shading α Region +x1=np.arange(2.3,xmax,res) +y_1=gaussprob.pdf(x1, 0, sigma**2) +plt.fill_between(x1,y_1, 0, alpha=0.50) + +#Shading β Region +x2=np.arange(xmin,2.3,res) +y_2=gaussprob.pdf(x2, 4, sigma**2) +plt.fill_between(x2,y_2, 0, alpha=0.50) + +#Axis Arrows +plt.arrow(0,0.07,1.2,-0.05,color='black',head_width=0.02,head_length=0.2) #β +plt.arrow(4,0.07,-1.2,-0.05,color='black',head_width=0.02,head_length=0.2)#α + +#label +plt.text(-0.4, 0.07, r'$\beta$', fontsize=15) #β +plt.text(4, 0.07, r'$\alpha$', fontsize=15) #α +plt.text(-0.2, 0.28, '$H_0$', fontsize=15) #H0 +plt.text(3.8,0.28, '$H_1$', fontsize=15) #H1 + +pml.savefig('neymanPearson2.pdf') +plt.show() diff --git a/pool/shard001/Python/0014695_deploy_sdk.py b/pool/shard001/Python/0014695_deploy_sdk.py new file mode 100644 index 0000000000000000000000000000000000000000..665a17e4f4274e57e79bb383374fcea54790fc2b --- /dev/null +++ b/pool/shard001/Python/0014695_deploy_sdk.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# Copyright 2015 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. + +import argparse +from datetime import datetime +import logging +import os +import shutil +import subprocess +import sys + +# Generates the sky_sdk from the template at sky/sdk. + +SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +SKY_DIR = os.path.dirname(SKY_TOOLS_DIR) +SRC_ROOT = os.path.dirname(SKY_DIR) + +DEFAULT_REL_BUILD_DIR = os.path.join('out', 'android_Release') + +def git_revision(): + return subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip() + + +def ensure_dir_exists(path): + if not os.path.exists(path): + os.makedirs(path) + + +def copy(from_root, to_root, filter_func=None): + assert os.path.exists(from_root), "%s does not exist!" % from_root + if os.path.isfile(from_root): + ensure_dir_exists(os.path.dirname(to_root)) + shutil.copy(from_root, to_root) + return + + ensure_dir_exists(to_root) + + for root, dirs, files in os.walk(from_root): + # filter_func expects paths not names, so wrap it to make them absolute. + wrapped_filter = None + if filter_func: + wrapped_filter = lambda name: filter_func(os.path.join(root, name)) + + for name in filter(wrapped_filter, files): + from_path = os.path.join(root, name) + root_rel_path = os.path.relpath(from_path, from_root) + to_path = os.path.join(to_root, root_rel_path) + to_dir = os.path.dirname(to_path) + if not os.path.exists(to_dir): + os.makedirs(to_dir) + shutil.copy(from_path, to_path) + + dirs[:] = filter(wrapped_filter, dirs) + + +def confirm(prompt): + response = raw_input('%s [N]|y: ' % prompt) + return response and response.lower() == 'y' + + +def delete_all_non_hidden_files_in_directory(root, non_interactive=False): + to_delete = [os.path.join(root, p) + for p in os.listdir(root) if not p.startswith('.')] + if not to_delete: + return + if not non_interactive: + prompt = 'This will delete everything in %s:\n%s\nAre you sure?' % ( + root, '\n'.join(to_delete)) + if not confirm(prompt): + print 'User aborted.' + sys.exit(2) + + for path in to_delete: + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + else: + os.remove(path) + + +def main(): + logging.basicConfig(level=logging.WARN) + parser = argparse.ArgumentParser(description='Deploy a new sky_sdk.') + parser.add_argument('sdk_root', type=str) + parser.add_argument('--build-dir', action='store', type=str, + default=os.path.join(SRC_ROOT, DEFAULT_REL_BUILD_DIR)) + parser.add_argument('--non-interactive', action='store_true') + args = parser.parse_args() + + build_dir = os.path.abspath(args.build_dir) + sdk_root = os.path.abspath(args.sdk_root) + + print 'Building SDK from %s into %s' % (build_dir, sdk_root) + start_time = datetime.now() + + def sdk_path(rel_path): + return os.path.join(sdk_root, rel_path) + + def src_path(rel_path): + return os.path.join(SRC_ROOT, rel_path) + + ensure_dir_exists(sdk_root) + # Manually clear sdk_root above to avoid deleting dot-files. + delete_all_non_hidden_files_in_directory(sdk_root, args.non_interactive) + + copy(src_path('sky/sdk/README.md'), sdk_root) + + ensure_dir_exists(sdk_path('packages')) + subprocess.check_call([ + 'mojo/tools/prepare_pub_packages.py', + '--out-dir', sdk_path('packages'), + 'out' + ]) + + with open(sdk_path('LICENSES.sky'), 'w') as license_file: + subprocess.check_call([src_path('tools/licenses.py'), 'credits'], + stdout=license_file) + + time_delta = datetime.now() - start_time + print 'SDK built at %s in %ss' % (sdk_root, time_delta.total_seconds()) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014701_engine.py b/pool/shard001/Python/0014701_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5e1de8f2e377ca1fa5447fd1c3396d73720e3d --- /dev/null +++ b/pool/shard001/Python/0014701_engine.py @@ -0,0 +1,77 @@ +import curses + + +class Entity: + def __init__(self): + pass + + +class Tile: + def __init__(self, pychar, y_pos, x_pos): + self.chcode = ord(pychar) + self.char = pychar + self.y_pos = y_pos + self.x_pos = x_pos + + +class Tilemap: + def __init__(self): + self.tiles = list() + self.map_index = None + + def get_tile_at(self, y, x): + for tile in self.tiles(): + if tile.y_pos == y and tile.x_pos == x: + return tile + return None + + def file_to_array(self, filename): + with open(filename) as f: + map_array = list() + for line in f: + map_array.append([int(char) for char in list(line.strip())]) + + return map_array + + def array_to_tile_list(self, map_array, map_index): + tile_list = list() + for y, row in enumerate(map_array): + for x, col in enumerate(row): + tile_list.append(Tile(map_index[col], y, x)) + + return tile_list + + def load_from_file(self, map_filename, map_index): + self.map_index = map_index + self.tile_list = self.array_to_tile_list( + self.file_to_array(map_filename), map_index) + + +class CursesWrapper(): + def __init__(self): + self.stdscr = curses.initscr() + # Disables displaying pressed keys to the window + curses.noecho() + # Allows keys to be captured without hitting enter + curses.cbreak() + self.stdscr.keypad(True) + curses.curs_set(False) + self.stdscr.nodelay(True) + + def reset_terminal_settings(self): + curses.echo() + curses.nocbreak + self.stdscr.keypad(False) + curses.endwin() + + def get_pressed_keys(self): + return self.stdscr.getkey() + + def draw(self, char, y_pos, x_pos): + self.stdscr.addch(y_pos, x_pos, char) + + def refresh(self): + self.stdscr.refresh() + + def clear(self): + self.stdscr.erase() diff --git a/pool/shard001/Python/0014704_create_lokallagovervakingar.py b/pool/shard001/Python/0014704_create_lokallagovervakingar.py new file mode 100644 index 0000000000000000000000000000000000000000..1f16250d35404c5d4800c645484f824edb2961fa --- /dev/null +++ b/pool/shard001/Python/0014704_create_lokallagovervakingar.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# vim: shiftwidth=4 tabstop=4 expandtab softtabstop=4 ai + +# Copyright 2009-2014 Odin Hørthe Omdal + +# This file is part of Medlemssys. + +# Medlemssys is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# Medlemssys is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. + +# You should have received a copy of the GNU Affero General Public License +# along with Medlemssys. If not, see . +from __future__ import print_function +import datetime +from django.core.management.base import BaseCommand +from django.db import transaction +from optparse import make_option + +from medlem.models import LokallagOvervaking, Lokallag + +class Command(BaseCommand): + args = '[ delete ]' + help = 'Opprett (og reinsk inaktive) standard LokallagsOvervakingar' + option_list = BaseCommand.option_list + ( + make_option('-d', '--delete', + action='store_true', + dest='delete', + default=False, + help=u"""Slettar alle lokallagsovervakingar som ikkje er spesielle på nokon helst måte (altso: truleg automatisk oppretta)."""), + ) + + def handle(self, *args, **options): + if options['delete']: + self.delete_lokallagovervakingar() + else: + self.clean_stale() + self.create_lokallagovervakingar() + + @transaction.commit_on_success + def clean_stale(self): + stale = LokallagOvervaking.objects.filter( + lokallag__aktivt=False, + epost='', + medlem__isnull=True, + deaktivert__isnull=True) + for lo in stale: + self.out('Deactivating ' + unicode(lo)) + lo.deaktivert = datetime.datetime.now() + lo.save() + + @transaction.commit_on_success + def create_lokallagovervakingar(self): + new = Lokallag.objects.filter(aktivt=True, lokallagovervaking__isnull=True) + for n in new: + lo = LokallagOvervaking(lokallag=n) + lo.save() + self.out(u"{}: {}".format( + unicode(lo), unicode(lo.epostar()))) + + def delete_lokallagovervakingar(self): + """Slettar alle lokallagsovervakingar som ikkje er spesielle på nokon + helst måte (altso: truleg automatisk oppretta).""" + num = LokallagOvervaking.objects.filter( + epost='', + medlem__isnull=True).delete() + self.out("Sletta {} overvakingar.".format(num)) + + def err(self, msg): + self.stderr.write((unicode(msg) + "\n").encode('utf-8')) + def out(self, msg): + self.stdout.write((unicode(msg) + "\n").encode('utf-8')) diff --git a/pool/shard001/Python/0014705_feedme.py b/pool/shard001/Python/0014705_feedme.py new file mode 100644 index 0000000000000000000000000000000000000000..9b45fcd30e0b258cad73b4b005b81a5c7b76ddf6 --- /dev/null +++ b/pool/shard001/Python/0014705_feedme.py @@ -0,0 +1,127 @@ +#! /usr/bin/env python + +from __future__ import print_function +from httplib2 import Http +import yaml +from io import open +from apiclient import discovery +from oauth2client.service_account import ServiceAccountCredentials +import logging +import time + + +class Feed: + SCOPES = [ + 'https://www.googleapis.com/auth/admin.directory.group', + 'https://www.googleapis.com/auth/admin.directory.group.member' + ] + SERVICE = [] + CONFIG = [] + CURRENT_MEMBERS = [] + DESIRED_MEMBERS = [] + MEMBERS_TO_ADD = [] + MEMBERS_TO_DEL = [] + SOURCE_FILE = '' + TARGET_GROUP = '' + DATE = '' + + # Reads our config file + def get_config(self): + with open('config.yml', 'r') as stream: + try: + return yaml.load(stream) + except yaml.YAMLError as exc: + print(exc) + + # Gets credentials from OAuth provider and impersonates the designated super admin. + def get_credentials(self): + credentials = ServiceAccountCredentials.from_json_keyfile_name(self.CONFIG['key_file_path'], self.SCOPES) + return credentials.create_delegated(self.CONFIG['super_admin_email']) + + # Builds a google directory service + def build_service(self): + credentials = self.get_credentials() + http = credentials.authorize(Http()) + return discovery.build('admin', 'directory_v1', http=http) + + # Gets all member emails from the service and dumps them into an array + def get_members_from_google(self): + members = self.SERVICE.members() + request = members.list(groupKey=self.TARGET_GROUP) + while request is not None: + members_doc = request.execute() + for m in members_doc['members']: + self.CURRENT_MEMBERS.append(m['email']) + request = members.list_next(request, members_doc) + + # Get users from local file + def get_members_from_local(self): + self.DESIRED_MEMBERS = [line.rstrip('\n').strip('"').lower() for line in open(self.SOURCE_FILE)] + + # Builds two lists based on a comparision of each. One list is users that need to be made members + # and the other is a list of users that should have their membership revoked. + def reconcile_lists(self): + self.MEMBERS_TO_ADD = set(self.DESIRED_MEMBERS).difference(self.CURRENT_MEMBERS) + self.MEMBERS_TO_DEL = set(self.CURRENT_MEMBERS).difference(self.DESIRED_MEMBERS) + + # Removes user's membership from group + def remove_members(self): + members = self.SERVICE.members() + info_log = self.CONFIG['log_path'] + '/info-' + self.DATE + '.log' + error_log = self.CONFIG['log_path'] + '/error-' + self.DATE + '.log' + logging.basicConfig(level=logging.INFO, filename=info_log, format='%(asctime)s %(message)s') + logging.basicConfig(level=logging.ERROR, filename=error_log, format='%(asctime)s %(message)s') + for member in self.MEMBERS_TO_DEL: + try: + members.delete(groupKey=self.TARGET_GROUP, memberKey=member).execute() + logging.info('del success' + member) + except Exception as e: + logging.error('del fail ' + member + ' ' + str(e)) + + return None + + # Creates user's membership within group + def add_members(self): + members = self.SERVICE.members() + info_log = self.CONFIG['log_path'] + '/info-' + self.DATE + '.log' + error_log = self.CONFIG['log_path'] + '/error-' + self.DATE + '.log' + logging.basicConfig(level=logging.INFO, filename=info_log, format='%(asctime)s %(message)s') + logging.basicConfig(level=logging.ERROR, filename=error_log, format='%(asctime)s %(message)s') + for member in self.MEMBERS_TO_ADD: + try: + members.insert(groupKey=self.TARGET_GROUP, body={'email': member}).execute() + logging.info('add success' + member) + except Exception as e: + logging.error('add fail ' + member + ' ' + str(e)) + + return None + + # Main function + def main(self): + self.DATE = time.strftime("%d-%m-%Y") + print('Reading config...') + self.CONFIG = self.get_config() + print('Building service...') + self.SERVICE = self.build_service() + for pair in self.CONFIG['group_source_map']: + self.SOURCE_FILE = pair[0] + self.TARGET_GROUP = pair[1] + print('Gathering current members of group: \n - ' + self.TARGET_GROUP + '...') + self.get_members_from_google() + print('Gathering list of desired members from: \n - ' + self.SOURCE_FILE + '...') + self.get_members_from_local() + print('Building operations list...') + self.reconcile_lists() + print('Removing user memberships...') + self.remove_members() + print('Assigning new memberships...') + self.add_members() + self.CURRENT_MEMBERS = [] + self.DESIRED_MEMBERS = [] + self.MEMBERS_TO_ADD = [] + self.MEMBERS_TO_DEL = [] + self.SOURCE_FILE = '' + self.TARGET_GROUP = '' + + +Feed().main() diff --git a/pool/shard001/Python/0014709_base_test.py b/pool/shard001/Python/0014709_base_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7bcd1ac7908c3f82a0579cfc0393fdfaadb2734f --- /dev/null +++ b/pool/shard001/Python/0014709_base_test.py @@ -0,0 +1,178 @@ +# Copyright 2018 Google LLC +# +# 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 __future__ import print_function + +import sys +import unittest + +import httplib2 +from googleapiclient import errors +from googleapiclient.discovery import build +from oauth2client.client import GoogleCredentials + + +class BaseTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.credentials = cls.create_credentials() + http = cls.credentials.authorize(httplib2.Http()) + cls.credentials.refresh(http) + cls.service = build('slides', 'v1', http=http) + cls.drive_service = build('drive', 'v3', http=http) + cls.sheets_service = build('sheets', 'v4', http=http) + # Hide STDOUT output generated by snippets. + cls.stdout = sys.stdout + sys.stdout = None + + @classmethod + def tearDownClass(cls): + # Restore STDOUT. + sys.stdout = cls.stdout + + @classmethod + def create_credentials(cls): + credentials = GoogleCredentials.get_application_default() + scope = [ + 'https://www.googleapis.com/auth/drive', + ] + return credentials.create_scoped(scope) + + def setUp(self): + self.files_to_delete = [] + + def tearDown(self): + for file_id in self.files_to_delete: + try: + self.drive_service.files().delete(fileId=file_id).execute() + except errors.HttpError: + print('Unable to delete file %s' % file_id, file=sys.stderr) + + def delete_file_on_cleanup(self, file_id): + self.files_to_delete.append(file_id) + + def create_test_presentation(self): + presentation = { + 'title': 'Test Preso' + } + presentation = self.service.presentations().create( + body=presentation).execute() + self.delete_file_on_cleanup(presentation.get('presentationId')) + return presentation.get('presentationId') + + def add_slides(self, presentation_id, num, layout='TITLE_AND_TWO_COLUMNS'): + requests = [] + slide_ids = [] + for i in range(num): + slide_id = 'slide_{0}'.format(i) + slide_ids.append(slide_id) + requests.append({ + 'createSlide': { + 'objectId': slide_ids[i], + 'slideLayoutReference': { + 'predefinedLayout': layout + } + } + }) + body = { + 'requests': requests + } + self.service.presentations().batchUpdate( + presentationId=presentation_id, body=body).execute() + return slide_ids + + def create_test_textbox(self, presentation_id, page_id): + box_id = 'MyTextBox_01' + pt350 = { + 'magnitude': 350, + 'unit': 'PT' + } + requests = [] + requests.append({ + 'createShape': { + 'objectId': box_id, + 'shapeType': 'TEXT_BOX', + 'elementProperties': { + 'pageObjectId': page_id, + 'size': { + 'height': pt350, + 'width': pt350 + }, + 'transform': { + 'scaleX': 1, + 'scaleY': 1, + 'translateX': 350, + 'translateY': 100, + 'unit': 'PT' + } + } + } + }) + requests.append({ + 'insertText': { + 'objectId': box_id, + 'insertionIndex': 0, + 'text': 'New Box Text Inserted' + } + }) + + body = { + 'requests': requests + } + response = self.service.presentations().batchUpdate( + presentationId=presentation_id, body=body).execute() + return response.get('replies')[0].get('createShape').get('objectId') + + def create_test_sheets_chart( + self, presentation_id, page_id, spreadsheet_id, sheet_chart_id): + chart_id = 'MyChart_01' + emu4M = { + 'magnitude': 4000000, + 'unit': 'EMU' + } + requests = [] + requests.append({ + 'createSheetsChart': { + 'objectId': chart_id, + 'spreadsheetId': spreadsheet_id, + 'chartId': sheet_chart_id, + 'linkingMode': 'LINKED', + 'elementProperties': { + 'pageObjectId': page_id, + 'size': { + 'height': emu4M, + 'width': emu4M + }, + 'transform': { + 'scaleX': 1, + 'scaleY': 1, + 'translateX': 100000, + 'translateY': 100000, + 'unit': 'EMU' + } + } + } + }) + + body = { + 'requests': requests + } + response = self.service.presentations().batchUpdate( + presentationId=presentation_id, body=body).execute() + return response.get('replies')[0] \ + .get('createSheetsChart').get('objectId') + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard001/Python/0014713_register.py b/pool/shard001/Python/0014713_register.py new file mode 100644 index 0000000000000000000000000000000000000000..f76f7de994c348485a0c49249541c39ca8942c71 --- /dev/null +++ b/pool/shard001/Python/0014713_register.py @@ -0,0 +1,34 @@ +import copy +from django.conf import settings +from django.utils.importlib import import_module +from django.utils.module_loading import module_has_submodule + +from tendenci.apps.registry.sites import site + + +def autodiscover(): + """ + Auto-discover INSTALLED_APPS app_registry.py modules and fail silently when + not present. This forces an import on them to register any admin bits they + may want. + """ + + + for app in settings.INSTALLED_APPS: + mod = import_module(app) + # Attempt to import the app's admin module. + try: + before_import_registry = copy.copy(site._registry) + import_module('%s.app_registry' % app) + except: + # Reset the model registry to the state before the last import as + # this import will have to reoccur on the next request and this + # could raise NotRegistered and AlreadyRegistered exceptions + # (see #8245). + site._registry = before_import_registry + + # Decide whether to bubble up this error. If the app just + # doesn't have an admin module, we can ignore the error + # attempting to import it, otherwise we want it to bubble up. + if module_has_submodule(mod, 'app_registry'): + raise diff --git a/pool/shard001/Python/0014722_main.py b/pool/shard001/Python/0014722_main.py new file mode 100644 index 0000000000000000000000000000000000000000..00cf786ecc2732794161d29d529bdc7648ae36e4 --- /dev/null +++ b/pool/shard001/Python/0014722_main.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python + +import ibm_db +import tweepy +import inspect +from datetime import date +from alchemyapi import AlchemyAPI +import time + + +tracking = ['db2', 'mysql', 'dashdb', 'oracle 12c', 'mongodb', 'postgresql', 'microsoft sql server', 'sqlite'] + +conn = ibm_db.connect('DATABASE=BLUDB; HOSTNAME=awh-yp-small02.services.dal.bluemix.net; PORT=50000; PROTOCAL=TCPIP; UID=dash104862; PWD=rBZIHKHQqX0o', '', '') + +class MyStreamListener(tweepy.StreamListener): + def __init__(self, api): + tweepy.StreamListener.__init__(self, api) + self.alchemyapi = AlchemyAPI() + self.inserts = 0 + self.print_count = 0 + + def get_main_keyword(self, text): + if 'keywords' in self.alchemyapi.keywords('text', text): + if len(self.alchemyapi.keywords('text', text)['keywords']) > 0: + return self.alchemyapi.keywords('text', text)['keywords'][0]['text'] + return '' + + def get_sentiment(self, text): + if 'docSentiment' in self.alchemyapi.sentiment('text', text): + return self.alchemyapi.sentiment('text', text)['docSentiment']['type'] + + def is_english(self, text): + if self.alchemyapi.keywords('text', text)['language'] == 'english': + return True + return False + + def what_cat(self, text): + for elem in tracking: + for smaller_elem in elem.split(): + if smaller_elem in text.lower(): + return elem + return 'unknown' + + def insert_into_table(self, data): + sql = 'insert into dash104862.tweepy_tweets(' + columns = '' + values = ' values(' + + for key,val in data.items(): + columns += str(key) + ',' + values += str(val) + ',' + columns = columns[:-1] + ')' + values = values[:-1] + ')' + + sql += columns + values + + # print (sql) + stmt = ibm_db.prepare(conn, sql) + try: + ibm_db.execute(stmt) + self.inserts += 1 + print ("%d inserts completed" % (self.inserts)) + except: + print("Warning: Insertion into table failed.") + # result = ibm_db.fetch_both(stmt) + # while (result): + # print( result ) + # result = ibm_db.fetch_both(stmt) + + def on_status(self, status): + if self.print_count == 0: + print ("Searching for tweets...") + self.print_count += 1 + + print ('%d Twitter API calls remaining...' % api.rate_limit_status()['resources']['application']['/application/rate_limit_status']['remaining']) + + if self.is_english(status.text): + tweet_dict = {} + tweet_dict['tweet'] = "\'" + status.text.lower().replace('\'', ' ') + "\'" + tweet_dict['date_of_tweet'] = 'TIMESTAMP_FORMAT(\'' + str(status.created_at) + '\',\'YYYY-MM-DD HH24:MI:SS\')' + tweet_dict['date_of_author'] = 'TIMESTAMP_FORMAT(\'' + str(status.author.created_at) + '\',\'YYYY-MM-DD HH24:MI:SS\')' # when the user was created + tweet_dict['verified'] = "\'" + str(status.author.verified) + "\'" # verfied + tweet_dict['author_favourites'] = status.author.favourites_count # total number of favourites + tweet_dict['author_followers'] = status.author.followers_count # total number of followers + tweet_dict['author_friends'] = status.author.friends_count # total number of follows + tweet_dict['screen_name'] = "\'" + status.author.screen_name + "\'" # username + tweet_dict['tweet_time_zone'] = "\'" + str(status.author.time_zone) + "\'" # where the user is from + tweet_dict['tweet_favourite_count'] = status.favorite_count + tweet_dict['tweet_retweet_count'] = status.retweet_count + tweet_dict['tweet_keyword'] = "\'" + str(self.get_main_keyword(status.text).lower()) + "\'" + tweet_dict['tweet_sentiment'] = "\'" + str(self.get_sentiment(status.text)) + "\'" + tweet_dict['search_string'] = "\'" + self.what_cat(status.text) + "\'" + self.insert_into_table(tweet_dict) + + + +consumer_key = 'aAG0jYGwxKSHwdQ2tSfDRMskR' +consumer_secret = '3w2JOgJDHulIXZtdB1WZPjJZXjbLNGkH0eG2H1RNehIyPDVTIV' + +auth = tweepy.OAuthHandler(consumer_key, consumer_secret) +auth.set_access_token('3313570090-Z2EApD4DAMJqKCCbGyG3CpEymk9Kx5l8Wqng0VM', 'tlU875YAS94wnpZGFXaHno55Ow6AX9aJctHNvQzfPaL9y') + +# Construct the API instance +api = tweepy.API(auth, wait_on_rate_limit=True) +myStreamListener = MyStreamListener(api) +myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener) + +myStream.filter(track=tracking) diff --git a/pool/shard001/Python/0014723_stimulus.py b/pool/shard001/Python/0014723_stimulus.py new file mode 100644 index 0000000000000000000000000000000000000000..f10879d5ec58a6119cecb201bd26f99499c3cfd2 --- /dev/null +++ b/pool/shard001/Python/0014723_stimulus.py @@ -0,0 +1,194 @@ +""" +File: stimulus.py +Author: Dilawar Singh +Created on: 2013-11-25 +Description: generates stimuous +""" + +import random +import numpy as np + +def countSpikes(spikeArray): + count = 0 + for i in spikeArray: + if i == True: + count += 1 + return count + +def generateSpikeTrainPoission(frequency, dt=1e-3, simTime=100e-3 + , refractoryPeriod=1e-3 + ): + """ + Generate a Poission spike train. + + All units are in SI. + + @return: A numpy array of time when there is a spike. + + @raise e: Description + """ + + frequency = float(frequency) + + def checkIfRefractoryPeriodIsViolated(simArray): + """ + Local function to check if refractory period is violated. + """ + deadPeriod = int(refractoryPeriod / dt) + indicesOfViolation = [] + for i in range(simArray.size - deadPeriod): + if simArray[i] == True: + for j in range(1, deadPeriod+1): + if simArray[i+j] == True: + indicesOfViolation.append((i, i+j)) + return indicesOfViolation + + + def fixRefractoryViolation(simArray): + """ + Fix violation of refractory period, if any. We are just deleting the + spike. Can't think of a fast solution. + """ + deadPeriod = int(refractoryPeriod / dt) + for i in range(simArray.size - deadPeriod): + if simArray[i] == True: + for j in range(1, deadPeriod+1): + if simArray[i+j] == True: + simArray[i+j] = False + return simArray + + + arraySize = int(simTime/dt) + # Initialize array to hold absense or presence of spike. By default there is + # no spike. + simArray = np.zeros(arraySize, dtype=np.bool_) + stepSize = dt * frequency + for i in range(arraySize): + # generate a random number between 0 and 1 and check if it is larger + # than (frequency*dt)/1000 (sec) + n = random.random() + if n < stepSize: + simArray[i] = True + # If refractory period is given then shift invalid firing to next location. + simArray = fixRefractoryViolation(simArray) + # We need to return only time on which there is a spike. + eventArray = np.array([], dtype=np.float_) + for i in range(simArray.size): + if simArray[i] == True: + eventArray = np.append(eventArray, i*dt) + return eventArray + + +""" + + +Following functions create two time tables. #1 is filled with entries in a +numpy array and #2 is filled from a text file containing the event times. + +The `state` field of #1, which becomes 1 when an event occurs and 0 +otherwise, is recorded. + +On the other hand, #2 is connected to a synapse (in a SynChan element) +to demonstrate artificial spike event generation. + +""" + +import numpy as np + +simdt = 1e-3 +simtime = 100 + +def generate_poisson_times(rate=20, simtime=100, seed=1): + """Generate Poisson spike times using `rate`. Use `seed` for seeding + the numpy rng""" + np.random.seed(seed) # ensure repeatability + isi = np.random.exponential(rate, int(simtime/rate)) + # The stimulus times are the cumulative sum of the inter-stimulus intervals. + stimtimes = np.cumsum(isi) + # Select only stimulus times that are within simulation time - + # this may leave out some possible stimuli at the end, but the + # exoected number of Poisson events within simtime is + # simtime/rate. + stimtimes = stimtimes[stimtimes < simtime] + return stimtimes + +def timetable_nparray(simtime=100): + """Create a time table and populate it with numpy array. The `vec` + field in a Table can be directly assigned a sequence to fill the + table entries. + + """ + times = generate_poisson_times(rate=20, simtime=simtime, seed=1) + model = moose.Neutral('/model') + tt = moose.TimeTable('%s/tt_array' % (model.path)) + tt.vec = times + return tt, times, + +def timetable_file(filename='timetable.txt', simtime=100): + """Create a TimeTable and populate it from file specified by + `filename`. If `filename` does not exist, a file of the same name is + created and a random series of spike times is saved in it""" + if not os.access(filename, os.R_OK): + times = generate_poisson_times(rate=10, simtime=simtime, seed=1) + np.savetxt(filename, times) + model = moose.Neutral('/model') + tt = moose.TimeTable('%s/tt_file' % (model.path)) + tt.filename = filename + return tt, np.loadtxt(filename), + +def timetable_demo(): + + tt_array, sp_array = timetable_nparray() + print(sp_array) + tt_file, sp_file = timetable_file() + # Create a synchan inside a compartment to demonstrate how to use + # TimeTable to send artificial spike events to a synapse. + comp = moose.Compartment('/model/comp') + comp.Em = -60e-3 + comp.Rm = 1e9 + comp.Cm = 1e-12 + synchan = moose.SynChan('/model/comp/synchan') + synchan.Gbar = 1e-6 + synchan.Ek = 0.0 + moose.connect(synchan, 'channel', comp, 'channel') + synchan.synapse.num = 1 + moose.connect(tt_file, 'event', moose.element(synchan.path + '/synapse'), 'addSpike') + # Data recording: record the `state` of the time table filled + # using array. + data = moose.Neutral('/data') + tab_array = moose.Table('/data/tab_array') + moose.connect(tab_array, 'requestData', tt_array, 'get_state') + # Record the synaptic conductance for the other time table, which + # is filled from a text file and sends spike events to a synchan. + tab_file = moose.Table('/data/tab_file') + moose.connect(tab_file, 'requestData', synchan, 'get_Gk') + + # Scheduling + moose.setClock(0, simdt) + moose.setClock(1, simdt) + + # Using clocks + moose.useClock(1, '/model/##[ISA=Compartment]', 'init') + moose.useClock(1, '/model/##,/data/##', 'process') + moose.useClock(0, '/neuroml/cells/##', 'process') + moose.reinit() + moose.start(simtime) + + # Plotting + pylab.subplot(2,1,1) + pylab.plot(sp_array, np.ones(len(sp_array)), 'rx', label='spike times from numpy array') + pylab.plot(np.linspace(0, simtime, len(tab_array.vec)), tab_array.vec, 'b-', label='TimeTable state') + pylab.legend() + pylab.subplot(2,1,2) + pylab.plot(sp_file, np.ones(len(sp_file)), 'rx', label='spike times from file') + pylab.plot(np.linspace(0, simtime, len(tab_file.vec)), tab_file.vec*1e6, 'b-', label='Syn Gk (uS)') + pylab.legend() + pylab.show() + +if __name__ == '__main__': + import moose + import os + import pylab + timetable_demo() + + diff --git a/pool/shard001/Python/0014726_hillviewCommon.py b/pool/shard001/Python/0014726_hillviewCommon.py new file mode 100644 index 0000000000000000000000000000000000000000..9349403b3d00ca804cf8c72d39ee5ec4bc6cde30 --- /dev/null +++ b/pool/shard001/Python/0014726_hillviewCommon.py @@ -0,0 +1,200 @@ +"""Common functions user by the Hillview deployment scripts""" + +# pylint: disable=invalid-name,too-few-public-methods, bare-except +import os.path +import subprocess +import tempfile +import json +from argparse import ArgumentParser + +def execute_command(command): + """Executes the specified command using a shell""" + print(command) + exitcode = subprocess.call(command, shell=True) + if exitcode != 0: + print("Exit code returned:", exitcode) + exit(exitcode) + +class RemoteHost(object): + """Abstraction for a remote host""" + def __init__(self, user, host, parent, heapsize="200M"): + """Create a remote host""" + assert isinstance(user, str) + assert isinstance(host, str) + assert parent is None or isinstance(parent, RemoteHost) + self.host = host + self.user = user + self.parent = parent + self.heapsize = heapsize + + def uh(self): + """user@host""" + if self.user is not None: + return self.user + "@" + self.host + else: + return self.host + + def run_remote_shell_command(self, command, verbose=True): + """Executes a command on a remote machine""" + file = tempfile.NamedTemporaryFile(mode="w", delete=False) + file.write(command) + file.close() + + f = open(file.name) + text = f.read() + if verbose: + print("On", self.host, ":", text) + f.close() + + command = "ssh " + self.uh() + " bash -s < " + file.name + exitcode = subprocess.call(command, shell=True) + if exitcode != 0: + print("Exit code returned:", exitcode) + exit(exitcode) + os.unlink(file.name) + + def create_remote_folder(self, folder): + """Ensures that a folder exists on the remote host""" + self.run_remote_shell_command("mkdir -p " + folder) + + def copy_file_to_remote(self, source, dest, copyOption): + """Copy a file to the remote host as the specified destination if not changed. + copyOption can be -L to follow symlinks.""" + u = self.user + if u is None: + u = "" + else: + u = self.user + "@" + command = "rsync -u " + copyOption + " " + source + " " + u + self.host + ":" + dest + execute_command(command) + + def __str__(self): + """Converts host to a string""" + return self.host + +class RemoteAggregator(RemoteHost): + """Abstraction for an aggregator""" + def __init__(self, user, host, parent, children): + "Create a remote aggregator""" + super().__init__(user, host, parent) + self.children = children + +class JsonConfig(object): + """ Configuration read from a JSON file.""" + + def __init__(self, d): + """Create configuration from a dictionary""" + for a, b in d.items(): + if isinstance(b, (list, tuple)): + setattr(self, a, [JsonConfig(x) if isinstance(x, dict) else x for x in b]) + else: + setattr(self, a, JsonConfig(b) if isinstance(b, dict) else b) + + def __getitem__(self, key): + """Get a configuration field""" + return self.__dict__[key] + + def has_key(self, k): + """Check if configuration has a specific field""" + return k in self.__dict__ + + def __contains__(self, item): + """Check if configuration has a specific field""" + return item in self.__dict__ + +class ClusterConfiguration(object): + """Represents a Hillview cluster""" + + def __init__(self, file): + """Load the configuration file describing the Hillview deployment.""" + print("Reading cluster configuration from", file) + if not os.path.exists(file): + print("Configuration file `" + file + "' does not exist") + exit(1) + try: + with open(file) as contents: + stripped = "".join(line.partition("//")[0] for line in contents) + self.jsonConfig = json.loads(stripped, object_hook=JsonConfig) + except: + print("Error parsing configuration file", file) + exit(1) + if not os.path.isabs(self.jsonConfig.service_folder): + print("service_folder must be an absolute path in configuration file", + self.jsonConfig.service_folder) + exit(1) + # The path where the current script is installed + self.scriptFolder = os.path.dirname(os.path.abspath(__file__)) + self.service_folder = self.jsonConfig.service_folder + self.worker_port = self.jsonConfig.worker_port + self.tomcat = self.jsonConfig.tomcat + self.tomcat_version = self.jsonConfig.tomcat_version + if hasattr(self.jsonConfig, "aggregator_port"): + self.aggregator_port = self.jsonConfig.aggregator_port + + def get_user(self): + """Returns the user used by the hillview service""" + return self.jsonConfig.user + + def _get_heap_size(self, hostname): + """The heap size used for the specified host""" + if hostname in self.jsonConfig.workers_heapsize: + return self.jsonConfig.workers_heapsize[hostname] + return self.jsonConfig.default_heap_size + + def get_workers(self): + """Returns an array of RemoteHost objects containing all workers""" + webserver = self.get_webserver() + if hasattr(self.jsonConfig, "aggregators"): + return [RemoteHost(self.jsonConfig.user, h, + RemoteHost(self.jsonConfig.user, a.name, webserver), + self._get_heap_size(h)) + for a in self.jsonConfig.aggregators + for h in a.workers] + return [RemoteHost(self.jsonConfig.user, h, webserver, self._get_heap_size(h)) + for h in self.jsonConfig.workers] + + def get_webserver(self): + """Returns a remote host representing the web server""" + return RemoteHost(self.jsonConfig.user, self.jsonConfig.webserver, None) + + def get_aggregators(self): + """Returns an array of RemoteAggregator objects""" + if not hasattr(self.jsonConfig, "aggregators"): + return [] + webserver = self.get_webserver() + return [RemoteAggregator(self.jsonConfig.user, h.name, webserver, h.workers) + for h in self.jsonConfig.aggregators] + + def cleanup_on_install(self): + """Returns true if we need to cleaup when installing""" + return self.jsonConfig.cleanup + + def run_on_all_aggregators(self, function, parallel=True): + # pylint: disable=unused-argument + """Run a lambda on all aggregators. function is a lambda that takes a + RemoteHost object as an argument. If parallel is True the function is + run concurrently.""" + for rh in self.get_aggregators(): + function(rh) + + def run_on_all_workers(self, function, parallel=True): + # pylint: disable=unused-argument + """Run a lambda on all workers. function is a lambda that takes a + RemoteHost object as an argument. If parallel is True the function is + run concurrently.""" + # Unfortunately there seems to be no way to reliably + # run something in parallel in Python, so this is not working yet. + for rh in self.get_workers(): + function(rh) + +def get_config(parser, args): + """Given an argument parser and the results obtained by parsing, + this function loads the cluster configuration. This is always + the config argument of the parser.""" + assert isinstance(parser, ArgumentParser) + try: + config = ClusterConfiguration(args.config) + return config + except: + parser.print_help() + exit(1) diff --git a/pool/shard001/Python/0014727_FitOneNamedEquation_3D.py b/pool/shard001/Python/0014727_FitOneNamedEquation_3D.py new file mode 100644 index 0000000000000000000000000000000000000000..f29c815c70c038268db3766ba1536a597b296929 --- /dev/null +++ b/pool/shard001/Python/0014727_FitOneNamedEquation_3D.py @@ -0,0 +1,129 @@ +# Version info: $Id: FitOneNamedEquation_3D.py 1 2012-01-07 22:20:43Z zunzun.com@gmail.com $ + +import os, sys, inspect, time + +# ensure pyeq2 can be imported +if os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '../..') not in sys.path: + sys.path.append(os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '../..')) +import pyeq2 + + + +if __name__ == "__main__": + + # see IModel.fittingTargetDictionary + equation = pyeq2.Models_3D.BioScience.HighLowAffinityIsotopeDisplacement('SSQABS') + + data = equation.exampleData + pyeq2.dataConvertorService().ConvertAndSortColumnarASCII(data, equation, False) + equation.Solve() + + + ########################################################## + + + print "Equation:", equation.GetDisplayName(), str(equation.GetDimensionality()) + "D" + print "Fitting target of", equation.fittingTargetDictionary[equation.fittingTarget], '=', equation.CalculateAllDataFittingTarget(equation.solvedCoefficients) + print "Fitted Parameters:" + for i in range(len(equation.solvedCoefficients)): + print " %s = %-.16E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]) + + + ########################################################## + + + equation.CalculateModelErrors(equation.solvedCoefficients, equation.dataCache.allDataCacheDictionary) + print + for i in range(len(equation.dataCache.allDataCacheDictionary['DependentData'])): + print 'X:', equation.dataCache.allDataCacheDictionary['IndependentData'][0][i], + print 'Y:', equation.dataCache.allDataCacheDictionary['IndependentData'][1][i], + print 'Z:', equation.dataCache.allDataCacheDictionary['DependentData'][i], + print 'Model:', equation.modelPredictions[i], + print 'Abs. Error:', equation.modelAbsoluteError[i], + if not equation.dataCache.DependentDataContainsZeroFlag: + print 'Rel. Error:', equation.modelRelativeError[i], + print 'Percent Error:', equation.modelPercentError[i] + else: + print + print + + + ########################################################## + + + equation.CalculateCoefficientAndFitStatistics() + + + print 'Degress of freedom error', equation.df_e + print 'Degress of freedom regression', equation.df_r + + if equation.rmse == None: + print 'Root Mean Squared Error (RMSE): n/a' + else: + print 'Root Mean Squared Error (RMSE):', equation.rmse + + if equation.r2 == None: + print 'R-squared: n/a' + else: + print 'R-squared:', equation.r2 + + if equation.r2adj == None: + print 'R-squared adjusted: n/a' + else: + print 'R-squared adjusted:', equation.r2adj + + if equation.Fstat == None: + print 'Model F-statistic: n/a' + else: + print 'Model F-statistic:', equation.Fstat + + if equation.Fpv == None: + print 'Model F-statistic p-value: n/a' + else: + print 'Model F-statistic p-value:', equation.Fpv + + if equation.ll == None: + print 'Model log-likelihood: n/a' + else: + print 'Model log-likelihood:', equation.ll + + if equation.aic == None: + print 'Model AIC: n/a' + else: + print 'Model AIC:', equation.aic + + if equation.bic == None: + print 'Model BIC: n/a' + else: + print 'Model BIC:', equation.bic + + + print + print "Individual Parameter Statistics:" + for i in range(len(equation.solvedCoefficients)): + if equation.tstat_beta == None: + tstat = 'n/a' + else: + tstat = '%-.5E' % ( equation.tstat_beta[i]) + + if equation.pstat_beta == None: + pstat = 'n/a' + else: + pstat = '%-.5E' % ( equation.pstat_beta[i]) + + if equation.sd_beta != None: + print "Coefficient %s = %-.16E, std error squared: %-.5E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i], equation.sd_beta[i]) + else: + print "Coefficient %s = %-.16E, std error squared: n/a" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]) + print " t-stat: %s, p-stat: %s, 95 percent confidence intervals: [%-.5E, %-.5E]" % (tstat, pstat, equation.ci[i][0], equation.ci[i][1]) + + + print + print "Coefficient Covariance Matrix:" + for i in equation.cov_beta: + print i + + + print + print 'Java Source Code:' + print pyeq2.outputSourceCodeService().GetOutputSourceCodeJAVA(equation) diff --git a/pool/shard001/Python/0014730_gen-swizzles.py b/pool/shard001/Python/0014730_gen-swizzles.py new file mode 100644 index 0000000000000000000000000000000000000000..bdeac6b8fcbc21f412c2d364aab144ec40a52917 --- /dev/null +++ b/pool/shard001/Python/0014730_gen-swizzles.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------- +# drawElements Quality Program utilities +# -------------------------------------- +# +# Copyright 2015 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#------------------------------------------------------------------------- + +import sys +import random +import operator +import itertools + +from genutil import * + +random.seed(1234567) +indices = xrange(sys.maxint) + +# Swizzles: +# - vector components +# * int, float, bool vectors +# * .xyzw, .rgba, .stpq +# * illegal to mix +# * not allowed for scalar types +# * legal to chain: vec4.rgba.xyzw.stpq +# * illegal to select more than 4 components +# +# Subscripts: +# - array-like indexing with [] operator +# * vectors, matrices +# - read & write +# - vectors components +# * [] accessor +# - matrix columns +# * [] accessor +# * note: mat4[0].x = 1.0; vs mat4[0][0] = 1.0; ?? +# * out-of-bounds accesses + +# +# - vector swizzles +# * all vector types (bvec2..4, ivec2..4, vec2..4) +# * all precisions (lowp, mediump, highp) +# * all component names (xyzw, rgba, stpq) +# * broadcast each, reverse, N random +# - component-masked writes +# * all vector types (bvec2..4, ivec2..4, vec2..4) +# * all precisions (lowp, mediump, highp) +# * all component names (xyzw, rgba, stpq) +# * all possible subsets +# * all input types (attribute, varying, uniform, tmp) +# -> a few hundred cases +# - concatenated swizzles + +# +VECTOR_TYPES = [ "vec2", "vec3", "vec4", "ivec2", "ivec3", "ivec4", "bvec2", "bvec3", "bvec4" ] +PRECISION_TYPES = [ "lowp", "mediump", "highp" ] +INPUT_TYPES = [ "uniform", "varying", "attribute", "tmp" ] +SWIZZLE_NAMES = [ "xyzw", "stpq", "rgba" ] + +def getDataTypeScalarSize (dt): + return { + "float": 1, + "vec2": 2, + "vec3": 3, + "vec4": 4, + "int": 1, + "ivec2": 2, + "ivec3": 3, + "ivec4": 4, + "bool": 1, + "bvec2": 2, + "bvec3": 3, + "bvec4": 4, + "mat2": 4, + "mat3": 9, + "mat4": 16 + }[dt] + +if False: + class Combinations: + def __init__(self, *args): + self.lists = list(args) + self.numLists = len(args) + self.numCombinations = reduce(operator.mul, map(len, self.lists), 1) + print(self.lists) + print(self.numCombinations) + + def iterate(self): + return [tuple(map(lambda x: x[0], self.lists))] + + combinations = Combinations(INPUT_TYPES, VECTOR_TYPES, PRECISION_TYPES) + print(combinations.iterate()) + for (inputType, dataType, precision) in combinations.iterate(): + scalarSize = getDataTypeScalarSize(dataType) + print(inputType, precision, dataType) + +def getSwizzlesForWidth(width): + if (width == 2): + return [(0,), (0,0), (0,1), (1,0), (1,0,1), (0,1,0,0), (1,1,1,1)] + elif (width == 3): + return [(0,), (2,), (0,2), (2,2), (0,1,2), (2,1,0), (0,0,0), (2,2,2), (2,2,1), (1,0,1), (0,2,0), (0,1,1,0), (2,2,2,2)] + elif (width == 4): + return [(0,), (3,), (3,0), (3,2), (3,3,3), (1,1,3), (3,2,1), (0,1,2,3), (3,2,1,0), (0,0,0,0), (1,1,1,1), (3,3,3,3), (3,2,2,3), (3,3,3,1), (0,1,0,0), (2,2,3,2)] + else: + assert False + +# Templates. + +s_swizzleCaseTemplate = """ +case ${{NAME}} + values + { + ${{VALUES}} + } + + both "" + precision mediump float; + + ${DECLARATIONS} + + void main() + { + ${SETUP} + ${{OP}} + ${OUTPUT} + } + "" +end +"""[1:] + +s_simpleIllegalCaseTemplate = """ +case ${{NAME}} + expect compile_fail + values {} + + both "" + precision mediump float; + precision mediump int; + + ${DECLARATIONS} + + void main() + { + ${SETUP} + ${{OP}} + ${OUTPUT} + } + "" +end +"""[1:] + +class SwizzleCase(ShaderCase): + def __init__(self, name, precision, dataType, swizzle, inputs, outputs): + self.name = name + self.precision = precision + self.dataType = dataType + self.swizzle = swizzle + self.inputs = inputs + self.outputs = outputs + self.op = "out0 = in0.%s;" % swizzle + + def __str__(self): + params = { + "NAME": self.name, + "VALUES": genValues(self.inputs, self.outputs), + "OP": self.op + } + return fillTemplate(s_swizzleCaseTemplate, params) + +# CASE DECLARATIONS + +inFloat = [Scalar(x) for x in [0.0, 1.0, 2.0, 3.5, -0.5, -20.125, 36.8125]] +inInt = [Scalar(x) for x in [0, 1, 2, 5, 8, 11, -12, -66, -192, 255]] +inBool = [Scalar(x) for x in [True, False]] + +inVec4 = [Vec4(0.0, 0.5, 0.75, 0.825), Vec4(1.0, 1.25, 1.125, 1.75), + Vec4(-0.5, -2.25, -4.875, 9.0), Vec4(-32.0, 64.0, -51.0, 24.0), + Vec4(-0.75, -1.0/31.0, 1.0/19.0, 1.0/4.0)] +inVec3 = toVec3(inVec4) +inVec2 = toVec2(inVec4) +inIVec4 = toIVec4(inVec4) +inIVec3 = toIVec3(inVec4) +inIVec2 = toIVec2(inVec4) +inBVec4 = [Vec4(True, False, False, True), Vec4(False, False, False, True), Vec4(False, True, False, False), Vec4(True, True, True, True), Vec4(False, False, False, False)] +inBVec3 = toBVec3(inBVec4) +inBVec2 = toBVec2(inBVec4) + +# \todo [petri] Enable large values when epsilon adapts to the values. +inMat4 = [Mat4(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0), + Mat4(6.5, 12.5, -0.75, 9.975, 32.0, 1.0/48.0, -8.425, -6.542, 1.0/8.0, 1.0/16.0, 1.0/32.0, 1.0/64.0, -6.725, -0.5, -0.0125, 9.975), + #Mat4(128.0, 256.0, -512.0, -1024.0, 2048.0, -4096.0, 8192.0, -8192.0, 192.0, -384.0, 768.0, -1536.0, 8192.0, -8192.0, 6144.0, -6144.0) + ] +inMat3 = [Mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0), + Mat3(6.5, 12.5, -0.75, 32.0, 1.0/32.0, 1.0/64.0, 1.0/8.0, 1.0/16.0, 1.0/32.0), + #Mat3(-18.725, -0.5, -0.0125, 19.975, -0.25, -17.75, 9.25, 65.125, -21.425), + #Mat3(128.0, -4096.0, -8192.0, 192.0, 768.0, -1536.0, 8192.0, 6144.0, -6144.0) + ] +inMat2 = [Mat2(1.0, 0.0, 0.0, 1.0), + Mat2(6.5, 12.5, -0.75, 9.975), + Mat2(6.5, 12.5, -0.75, 9.975), + Mat2(8.0, 16.0, -24.0, -16.0), + Mat2(1.0/8.0, 1.0/16.0, 1.0/32.0, 1.0/64.0), + Mat2(-18.725, -0.5, -0.0125, 19.975), + #Mat2(128.0, -4096.0, 192.0, -1536.0), + #Mat2(-1536.0, 8192.0, 6144.0, -6144.0) + ] + +INPUTS = { + "float": inFloat, + "vec2": inVec2, + "vec3": inVec3, + "vec4": inVec4, + "int": inInt, + "ivec2": inIVec2, + "ivec3": inIVec3, + "ivec4": inIVec4, + "bool": inBool, + "bvec2": inBVec2, + "bvec3": inBVec3, + "bvec4": inBVec4, + "mat2": inMat2, + "mat3": inMat3, + "mat4": inMat4 +} + +def genConversionCases(inValueList, convFuncList): + combinations = list(itertools.product(inValueList, convFuncList)) + return [ConversionCase(inValues, convFunc) for (inValues, convFunc) in combinations] + +allCases = [] + +# Vector swizzles. + +vectorSwizzleCases = [] + +# \todo [petri] Uses fixed precision. +for dataType in VECTOR_TYPES: + scalarSize = getDataTypeScalarSize(dataType) + precision = "mediump" + for swizzleComponents in SWIZZLE_NAMES: + for swizzleIndices in getSwizzlesForWidth(scalarSize): + swizzle = "".join(map(lambda x: swizzleComponents[x], swizzleIndices)) + #print("%s %s .%s" % (precision, dataType, swizzle)) + caseName = "%s_%s_%s" % (precision, dataType, swizzle) + inputs = INPUTS[dataType] + outputs = map(lambda x: x.swizzle(swizzleIndices), inputs) + outType = outputs[0].typeString() + vectorSwizzleCases.append(SwizzleCase(caseName, precision, dataType, swizzle, [("%s in0" % dataType, inputs)], [("%s out0" % outType, outputs)])) + +# ?? +#for dataType in VECTOR_TYPES: +# scalarSize = getDataTypeScalarSize(dataType) +# for precision in PRECISION_TYPES: +# for swizzleIndices in getSwizzlesForWidth(scalarSize): +# swizzle = "".join(map(lambda x: "xyzw"[x], swizzleIndices)) +# #print("%s %s .%s" % (precision, dataType, swizzle)) +# caseName = "%s_%s_%s" % (precision, dataType, swizzle) +# inputs = INPUTS[dataType] +# outputs = map(lambda x: x.swizzle(swizzleIndices), inputs) +# vectorSwizzleCases.append(SwizzleCase(caseName, precision, dataType, swizzle, [("in0", inputs)], [("out0", outputs)])) + +allCases.append(CaseGroup("vector_swizzles", "Vector Swizzles", vectorSwizzleCases)) + +# Swizzles: +# - vector components +# * int, float, bool vectors +# * .xyzw, .rgba, .stpq +# * illegal to mix +# * not allowed for scalar types +# * legal to chain: vec4.rgba.xyzw.stpq +# * illegal to select more than 4 components + +# TODO: precisions!! + +#allCases.append(CaseGroup("vector_swizzles", "Vector Swizzles", +# genSwizzleCase([inVec2, inVec3, inVec4], + +# Main program. + +if __name__ == "__main__": + print("Generating shader case files.") + writeAllCases("swizzles.test", allCases) diff --git a/pool/shard001/Python/0014732_init__.py b/pool/shard001/Python/0014732_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a564e9decede3efbb80b5b9a07b9d32433d71c85 --- /dev/null +++ b/pool/shard001/Python/0014732_init__.py @@ -0,0 +1,128 @@ +# -*- encoding: utf-8 -*- + +from pysis.services.base import Service +from datetime import datetime + +class Outputs(Service): + """Outputs Service + + Consumes Outputs API: <{url}/outputs> + """ + + def __init__(self, client): + """Creates Outputs object with a client""" + super(Outputs, self).__init__(client) + + def get(self, id=None, + type=None, category=None, feed_id=None, + building_id=None, facility_id=None, organization_id=None): + """Get a specific output or all of them if id=None + + Apply a filter if one is given. + Only 1 filter can be used at a time! + + Args: + id (int): id of the output. + type (str): Filter - if used, will get a list of outputs of the given type + category (str): Filter - if used, will get a list of outputs of the given category + feed_id (int): Filter - if used, will get a list of outputs with the given feed_id + building_id (int): Filter - if used, will get a list of outputs with the given building_id + facility_id (int): Filter - if used, will get a list of outputs with the given facility_id + organization_id (int): Filter - if used, will get a list of outputs with the given organization_id + + Returns: + Fields resources + """ + + _filterDict = {} + _filterDict['type'] = type + _filterDict['category'] = category + _filterDict['feed_id'] = feed_id + _filterDict['building_id'] = building_id + _filterDict['facility_id'] = facility_id + _filterDict['organization_id'] = organization_id + + #Check for a filter, but only allow one + filterName = None + filterValue = None + + for filter, value in _filterDict.items(): + if value is not None: + if filterName is not None: + #only 1 filter at a time + raise ValueError('Only one filter can be used at a time') + else: + filterName, filterValue = filter, value + + if id is None: + request = self.request_builder('outputs.get', filterName=filterName, filterValue=filterValue) + else: + assert isinstance(id, int) + request = self.request_builder('outputs.get', id=id, filterName=filterName, filterValue=filterValue) + + return self._get(request) + + def getFields(self, id): + """Get all the fields for an output + + Args: + id (int): id of the output. + + Returns: + Fields resources + """ + assert isinstance(id, int) + request = self.request_builder('outputs.getFields', id=id) + return self._get(request) + + def getData(self, id, timeStart=None, timeEnd=None, window=None, field=""): + """Get the data of an output + + Args: + id (int): id of the output. + timeStart (datetime or None): start time of the data + timeEnd (datetime or None): end time of the data + window (int): window of data in seconds + field (str): field_human_name filter + + Returns: + Data resources + """ + assert isinstance(id, int) + assert isinstance(timeStart, (datetime, type(None))) + assert isinstance(timeEnd, (datetime, type(None))) + assert isinstance(window, (int, type(None))) + assert isinstance(field, str) + + if timeStart is not None: + timeStart = int((timeStart - datetime(1970,1,1)).total_seconds()) + if timeEnd is not None: + timeEnd = int((timeEnd - datetime(1970,1,1)).total_seconds()) + + request = self.request_builder('outputs.getData', + id=id, + timeStart=timeStart, + timeEnd=timeEnd, + window=window, + field=field) + return self._get(request) + + + def getMetrics(self, id, field, metric_name, timeStart=None, timeEnd=None): + + assert isinstance(timeStart, (datetime, type(None))) + assert isinstance(timeEnd, (datetime, type(None))) + + if timeStart is not None: + timeStart = int((timeStart - datetime(1970,1,1)).total_seconds()) + if timeEnd is not None: + timeEnd = int((timeEnd - datetime(1970,1,1)).total_seconds()) + + request = self.request_builder('outputs.getMetrics', + id=id, + field=field, + metric_name=metric_name, + timeStart=timeStart, + timeEnd=timeEnd) + + return self._get(request) \ No newline at end of file diff --git a/pool/shard001/Python/0014734_auth_backends.py b/pool/shard001/Python/0014734_auth_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9674e33b0d8b586f15133fe59a7fb6ca4f9c55 --- /dev/null +++ b/pool/shard001/Python/0014734_auth_backends.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# +# OpenCraft -- tools to aid developing and hosting free software projects +# Copyright (C) 2015-2019 OpenCraft +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +""" +Authentication backends +""" + +# Imports ##################################################################### + +from django.contrib.auth import get_user_model +from django.contrib.auth import backends +from django.db.models import Q + + +# Auth backends ############################################################### + +class ModelBackend(backends.ModelBackend): + """ + Extends the default ModelBackend to fetch users by email address as well as + by username. + """ + def authenticate(self, request, username=None, password=None, **kwargs): + """ + This is mostly copied from the default ModelBackend. Attempts to fetch + users by username or email address, instead of just by username. + """ + if not username or not password: + return None + UserModel = get_user_model() # noqa pylint: disable=invalid-name + try: + user = UserModel._default_manager.get(Q(username=username) | + Q(email=username)) + except (UserModel.DoesNotExist, UserModel.MultipleObjectsReturned): + # Run the default password hasher once to reduce the timing + # difference between an existing and a non-existing user (#20760). + UserModel().set_password(password) + else: + if user.check_password(password) and self.user_can_authenticate(user): + return user + return None diff --git a/pool/shard001/Python/0014735_mr_base.py b/pool/shard001/Python/0014735_mr_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4f86de79345662431b63f6f6242b199b546341 --- /dev/null +++ b/pool/shard001/Python/0014735_mr_base.py @@ -0,0 +1,101 @@ +'Base classes and stuff for Disco jobs.' + +# Copyright (c) Los Alamos National Security, LLC, and others. + +import datetime +import io +import os.path +from pprint import pprint + +import mr_path +mr_path.fix_pythonpath() + +import disco.core +import disco.ddfs + +import testable +import u +l = u.l + + +### Job submission helper function + +def run(jobclass, args): + l.info('starting; args:') + for (arg, val) in sorted(vars(args).items()): + l.info(' %-16s %s' % (arg, val)) + job = jobclass(args) + job.run(input=['tag://' + args.input]) + l.info('started job %s' % (job.name)) + if (args.verbose): + l.debug('will wait for job to finish') + job.wait(show='nocolor') + l.debug('job done') + for tag in job.out_tags: + l.info('output tag: %s' % (tag)) + l.info('job submission complete') + + +### Core job superclass + +class Job(disco.core.Job): + + def __init__(self, args, **kw): + super(Job, self).__init__(**kw) + self.args = args + self.name = (self.__module__ + '_' + + datetime.datetime.now().strftime('%Y%m%d_%H%M%S')) + self.fs = disco.ddfs.DDFS() + self.out_tags = set() + + def add_check_out_tags(self, *tags): + self.add_out_tags(*args) + self.check_out_tags() + + def add_out_tags(self, *tags): + '''*tags is the list of tags to use; any tag beginning in ``:`` is a + suffix to be appended to the job name. E.g.: + + >>> j = Job(object()) + >>> j.name = 'doctest_foo' + >>> j.add_out_tags('doctest_bar', ':baz') + >>> pprint(j.out_tags) + ['doctest_bar', 'doctest_foo:baz']''' + for tag in tags: + if (tag[0] == ':'): + self.out_tags.add(self.name + tag) + else: + self.out_tags.add(tag) + + def check_out_tags(self): + '''Raise ValueError if any of the output tags already exist. Note that + there's a race condition here, so it's nothing more than a sanity + check.''' + for tag in self.out_tags: + if (self.fs.exists(tag)): + raise ValueError('tag %s already exists' % (tag)) + + def run(self, **kw): + if ('required_modules' in kw): + raise ValueError('required_modules is not supported by this subclass') + kw['required_modules'] = [('mr_path', os.path.abspath(mr_path.__file__))] + super(Job, self).run(**kw) + + +# Some mixins for various handy behavior. + +class TSV_Reader_Job(object): + + @staticmethod + def map_reader(fp, size, url, params): + # Note: I can't find this in the docs or the source, but fp is + # apparently a regular old open file, at least on my one-node tests. I + # suspect this may be different when nodes start to send each other data + # over HTTP, but we'll cross that bridge when we come to it. + fp_unicode = io.open(fp.fileno(), encoding='utf8') + for line in fp_unicode: + yield line.split('\t') + + +# Test-Depends: manual +testable.register('') diff --git a/pool/shard001/Python/0014738_cht.py b/pool/shard001/Python/0014738_cht.py new file mode 100644 index 0000000000000000000000000000000000000000..24956ea22548440de2b4d67ba482d9e02daf4ff5 --- /dev/null +++ b/pool/shard001/Python/0014738_cht.py @@ -0,0 +1,42 @@ +import esccmd +from esctypes import Point +from escutil import AssertEQ, GetCursorPosition, knownBug + +class CHTTests(object): + @knownBug(terminal="iTerm2", reason="iTerm2 doesn't support CHT") + def test_CHT_OneTabStopByDefault(self): + esccmd.CHT() + position = GetCursorPosition() + AssertEQ(position.x(), 9) + + @knownBug(terminal="iTerm2", reason="iTerm2 doesn't support CHT") + def test_CHT_ExplicitParameter(self): + esccmd.CHT(2) + position = GetCursorPosition() + AssertEQ(position.x(), 17) + + @knownBug(terminal="iTerm2", reason="iTerm2 doesn't support CHT") + @knownBug(terminal="xterm", reason="xterm respects scrolling regions for CHT") + def test_CHT_IgnoresScrollingRegion(self): + # Set a scroll region. + esccmd.DECSET(esccmd.DECLRMM) + esccmd.DECSLRM(5, 30) + + # Move to center of region + esccmd.CUP(Point(7, 9)) + + # Ensure we can tab within the region + esccmd.CHT(2) + position = GetCursorPosition() + AssertEQ(position.x(), 17) + + # Ensure that we can tab out of the region + esccmd.CHT(2) + position = GetCursorPosition() + AssertEQ(position.x(), 33) + + # Try again, starting before the region. + esccmd.CUP(Point(1, 9)) + esccmd.CHT(9) + position = GetCursorPosition() + AssertEQ(position.x(), 73) diff --git a/pool/shard001/Python/0014739_tests.py b/pool/shard001/Python/0014739_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa7ada00cd2974a474468a38ea4281139514885 --- /dev/null +++ b/pool/shard001/Python/0014739_tests.py @@ -0,0 +1,91 @@ +from exam import fixture + +from webtest import TestApp as WebtestApp # prevent pytest-warning + +import bottle + +from raven.base import Client +from raven.contrib.bottle import Sentry +from raven.utils.testutils import TestCase + + +class TempStoreClient(Client): + def __init__(self, **kwargs): + self.events = [] + super(TempStoreClient, self).__init__(**kwargs) + + def is_enabled(self): + return True + + def send(self, **kwargs): + self.events.append(kwargs) + + +def create_app(raven): + app = bottle.app() + app.catchall = False + app = Sentry(app, client=raven) + tapp = WebtestApp(app) + + @bottle.route('/error/', ['GET', 'POST']) + def an_error(): + raise ValueError('hello world') + + @bottle.route('/capture/', ['GET', 'POST']) + def capture_exception(): + try: + raise ValueError('Boom') + except: + tapp.app.captureException() + return 'Hello' + + @bottle.route('/message/', ['GET', 'POST']) + def capture_message(): + tapp.app.captureMessage('Interesting') + return 'World' + + return tapp + + +class BaseTest(TestCase): + @fixture + def app(self): + self.raven = TempStoreClient() + return create_app(self.raven) + + @fixture + def client(self): + return self.app + + +class BottleTest(BaseTest): + def test_error(self): + self.assertRaises(ValueError, self.client.get, '/error/?foo=bar') + + self.assertEquals(len(self.raven.events), 1) + event = self.raven.events.pop(0) + assert 'exception' in event + + exc = event['exception']['values'][-1] + self.assertEquals(exc['type'], 'ValueError') + + def test_captureException_captures_http(self): + response = self.client.get('/capture/?foo=bar') + self.assertEquals(response.status_code, 200) + self.assertEquals(len(self.raven.events), 1) + + event = self.raven.events.pop(0) + + assert event['message'] == 'ValueError: Boom' + assert 'request' in event + assert 'exception' in event + + def test_captureMessage_captures_http(self): + response = self.client.get('/message/?foo=bar') + self.assertEquals(response.status_code, 200) + self.assertEquals(len(self.raven.events), 1) + + event = self.raven.events.pop(0) + + assert 'sentry.interfaces.Message' in event + assert 'request' in event diff --git a/pool/shard001/Python/0014755_test_api.py b/pool/shard001/Python/0014755_test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..716bb4e39770a22654f2f23be4d8a1603ace7164 --- /dev/null +++ b/pool/shard001/Python/0014755_test_api.py @@ -0,0 +1,98 @@ +from datetime import timedelta as td + +from django.conf import settings +from django.conf.urls.defaults import url, patterns, include + +from drawquest.api_cache import cached_api +from drawquest.tests.tests_helpers import (CanvasTestCase, create_content, create_user, create_group, + create_comment, create_staff, + create_quest, create_current_quest, create_quest_comment, + fake_api_request) +from drawquest.api_decorators import api_decorator +from drawquest.apps.quest_comments.models import QuestComment +from drawquest.apps.drawquest_auth.models import User +from canvas.exceptions import ServiceError, ValidationError +from canvas import util +from canvas.models import Visibility +from services import Services, override_service + + +class TestProfile(CanvasTestCase): + def after_setUp(self): + self.user = create_user() + + def test_bio(self): + bio = 'my new bio' + self.api_post('/api/user/change_profile', {'bio': bio}, user=self.user) + self.assertEqual(self.api_post('/api/user/profile', {'username': self.user.username})['bio'], bio) + + def test_realtime_sync(self): + resp = self.api_post('/api/realtime/sync', user=self.user) + self.assertAPISuccess(resp) + self.assertTrue(self.user.redis.activity_stream_channel.channel in resp['channels']) + + def test_create_share_url_for_channel_via_api(self): + cmt = create_quest_comment() + result = self.api_post('/api/share/create_for_channel', + {'comment_id': cmt.id, 'channel': 'testing'}, user=self.user) + self.assertAPISuccess(result) + url = result['share_url'] + rmatch = '/s/1j' + self.assertEqual(url[url.rfind(rmatch):], rmatch) + + def test_heavy_state_sync(self): + state = self.api_post('/api/heavy_state_sync', user=self.user) + self.assertAPISuccess(state) + self.assertEqual(state['user_profile']['user']['username'], self.user.username) + + +class TestFlags(CanvasTestCase): + def test_auto_moderation_from_flags(self): + cmt = create_quest_comment() + + for i in range(1, settings.AUTO_MODERATE_FLAGGED_COMMENTS_THRESHOLD + 1): + resp = self.api_post('/api/comment/flag', {'comment_id': cmt.id}) + + cmt = QuestComment.all_objects.get(pk=cmt.pk) + getattr(self, 'assert' + str(i == settings.AUTO_MODERATE_FLAGGED_COMMENTS_THRESHOLD))( + cmt.visibility == Visibility.DISABLED) + + self.assertTrue(cmt.id in [qc.id for qc in QuestComment.unjudged_flagged()]) + + def test_self_flag(self): + cmt = create_quest_comment() + resp = self.api_post('/api/comment/flag', {'comment_id': cmt.id}, user=cmt.author) + + +class TestCache(CanvasTestCase): + def after_setUp(self): + urls = patterns('') + self.api = api_decorator(urls) + + def _api(self, api_func, data={}): + return util.loads(api_func(fake_api_request('', data=data)).content) + + def test_cache_hit(self): + i = [0] + + @self.api('test_cache') + @cached_api(td(days=2), key='test_cache') + def test_cache(request): + i[0] += 1 + return {'i': i[0]} + + for _ in range(2): + print self._api(test_cache) + self.assertEqual(self._api(test_cache)['i'], 1) + + def test_uncached(self): + i = [0] + + @self.api('test_uncached') + def test_cache(request): + i[0] += 1 + return {'i': i[0]} + + for j in range(1, 2): + self.assertEqual(self._api(test_cache)['i'], j) + diff --git a/pool/shard001/Python/0014756_stripe.py b/pool/shard001/Python/0014756_stripe.py new file mode 100644 index 0000000000000000000000000000000000000000..7608f2b5b31b9fa214636ff07f8469fa3b66f5ac --- /dev/null +++ b/pool/shard001/Python/0014756_stripe.py @@ -0,0 +1,78 @@ +import urllib, urllib2, base64, json +from urlparse import urlparse, urlunparse + +class Stripe(object): + """API for Stripe Payment.""" + + api_url = "https://api.stripe.com" + api_version = "v1" + + def __init__(self, api_key, password = ""): + self.api_key = api_key + self.password = password + + def getRequest(self, action, data=None): + request = urllib2.Request(self._createApiUrl(action, data)) + return self._sendRequest(request) + + def postRequest(self, action, data): + request = urllib2.Request(self._createApiUrl(action)) + self._formatData(data) + request.add_data(urllib.urlencode(data)) + return self._sendRequest(request) + + def _formatData(self, data): + formatters = { + 'dict': self._formatInnerDict, + } + + for key in data.keys(): + try: + formatters.get(data[key].__class__.__name__)(data, key) + except TypeError: + continue + print data + + def _formatInnerDict(self, data, key): + for k, v in data[key].iteritems(): + data["{}[{}]".format(key, k)] = v + data.pop(key) + + def _createApiUrl(self, action, data = None): + url = urlparse(self.__class__.api_url) + api_path = "{}/{}/{}".format(url.path, self.__class__.api_version, action) + + api_query = "" + if data is not None: + api_query = urllib.urlencode(data) + + api_url = urlunparse(( + url.scheme, + url.netloc, + api_path, + url.params, + api_query, + url.fragment, + )) + return api_url + + def _sendRequest(self, request): + opener = urllib2.build_opener() + opener.addheaders = [ + ("Content-type", "application/x-www-form-urlencoded"), + ("Accept", "text/plain"), + ("Authorization", "Basic {}".format(self._createAuthHeader())), + ] + + try: + response = opener.open(request, timeout=3) + return json.loads(response.read()) + except urllib2.URLError, e: + error = json.loads(e.read())["error"] + print "Failed to load {} - {}:{}".format(request.get_full_url(), error["type"], error["message"]) + return None + + + def _createAuthHeader(self): + return base64.urlsafe_b64encode("{}:{}".format(self.api_key, self.password)) + diff --git a/pool/shard001/Python/0014757_config_entries.py b/pool/shard001/Python/0014757_config_entries.py new file mode 100644 index 0000000000000000000000000000000000000000..b21991a84791805939e7db10e6f50ff44aeb1c2f --- /dev/null +++ b/pool/shard001/Python/0014757_config_entries.py @@ -0,0 +1,287 @@ +"""Http views to control the config manager.""" +import aiohttp.web_exceptions +import voluptuous as vol + +from homeassistant import config_entries, data_entry_flow +from homeassistant.auth.permissions.const import CAT_CONFIG_ENTRIES +from homeassistant.components import websocket_api +from homeassistant.components.http import HomeAssistantView +from homeassistant.exceptions import Unauthorized +from homeassistant.helpers.data_entry_flow import ( + FlowManagerIndexView, + FlowManagerResourceView, +) +from homeassistant.loader import async_get_config_flows + + +async def async_setup(hass): + """Enable the Home Assistant views.""" + hass.http.register_view(ConfigManagerEntryIndexView) + hass.http.register_view(ConfigManagerEntryResourceView) + hass.http.register_view(ConfigManagerFlowIndexView(hass.config_entries.flow)) + hass.http.register_view(ConfigManagerFlowResourceView(hass.config_entries.flow)) + hass.http.register_view(ConfigManagerAvailableFlowView) + + hass.http.register_view( + OptionManagerFlowIndexView(hass.config_entries.options.flow) + ) + hass.http.register_view( + OptionManagerFlowResourceView(hass.config_entries.options.flow) + ) + + hass.components.websocket_api.async_register_command(config_entries_progress) + hass.components.websocket_api.async_register_command(system_options_list) + hass.components.websocket_api.async_register_command(system_options_update) + + return True + + +def _prepare_json(result): + """Convert result for JSON.""" + if result["type"] != data_entry_flow.RESULT_TYPE_FORM: + return result + + import voluptuous_serialize + + data = result.copy() + + schema = data["data_schema"] + if schema is None: + data["data_schema"] = [] + else: + data["data_schema"] = voluptuous_serialize.convert(schema) + + return data + + +class ConfigManagerEntryIndexView(HomeAssistantView): + """View to get available config entries.""" + + url = "/api/config/config_entries/entry" + name = "api:config:config_entries:entry" + + async def get(self, request): + """List available config entries.""" + hass = request.app["hass"] + + results = [] + + for entry in hass.config_entries.async_entries(): + handler = config_entries.HANDLERS.get(entry.domain) + supports_options = ( + # Guard in case handler is no longer registered (custom compnoent etc) + handler is not None + # pylint: disable=comparison-with-callable + and handler.async_get_options_flow + != config_entries.ConfigFlow.async_get_options_flow + ) + results.append( + { + "entry_id": entry.entry_id, + "domain": entry.domain, + "title": entry.title, + "source": entry.source, + "state": entry.state, + "connection_class": entry.connection_class, + "supports_options": supports_options, + } + ) + + return self.json(results) + + +class ConfigManagerEntryResourceView(HomeAssistantView): + """View to interact with a config entry.""" + + url = "/api/config/config_entries/entry/{entry_id}" + name = "api:config:config_entries:entry:resource" + + async def delete(self, request, entry_id): + """Delete a config entry.""" + if not request["hass_user"].is_admin: + raise Unauthorized(config_entry_id=entry_id, permission="remove") + + hass = request.app["hass"] + + try: + result = await hass.config_entries.async_remove(entry_id) + except config_entries.UnknownEntry: + return self.json_message("Invalid entry specified", 404) + + return self.json(result) + + +class ConfigManagerFlowIndexView(FlowManagerIndexView): + """View to create config flows.""" + + url = "/api/config/config_entries/flow" + name = "api:config:config_entries:flow" + + async def get(self, request): + """Not implemented.""" + raise aiohttp.web_exceptions.HTTPMethodNotAllowed("GET", ["POST"]) + + # pylint: disable=arguments-differ + async def post(self, request): + """Handle a POST request.""" + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") + + # pylint: disable=no-value-for-parameter + return await super().post(request) + + def _prepare_result_json(self, result): + """Convert result to JSON.""" + if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: + return super()._prepare_result_json(result) + + data = result.copy() + data["result"] = data["result"].entry_id + data.pop("data") + return data + + +class ConfigManagerFlowResourceView(FlowManagerResourceView): + """View to interact with the flow manager.""" + + url = "/api/config/config_entries/flow/{flow_id}" + name = "api:config:config_entries:flow:resource" + + async def get(self, request, flow_id): + """Get the current state of a data_entry_flow.""" + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") + + return await super().get(request, flow_id) + + # pylint: disable=arguments-differ + async def post(self, request, flow_id): + """Handle a POST request.""" + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") + + # pylint: disable=no-value-for-parameter + return await super().post(request, flow_id) + + def _prepare_result_json(self, result): + """Convert result to JSON.""" + if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: + return super()._prepare_result_json(result) + + data = result.copy() + data["result"] = data["result"].entry_id + data.pop("data") + return data + + +class ConfigManagerAvailableFlowView(HomeAssistantView): + """View to query available flows.""" + + url = "/api/config/config_entries/flow_handlers" + name = "api:config:config_entries:flow_handlers" + + async def get(self, request): + """List available flow handlers.""" + hass = request.app["hass"] + return self.json(await async_get_config_flows(hass)) + + +class OptionManagerFlowIndexView(FlowManagerIndexView): + """View to create option flows.""" + + url = "/api/config/config_entries/options/flow" + name = "api:config:config_entries:option:flow" + + # pylint: disable=arguments-differ + async def post(self, request): + """Handle a POST request. + + handler in request is entry_id. + """ + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") + + # pylint: disable=no-value-for-parameter + return await super().post(request) + + +class OptionManagerFlowResourceView(FlowManagerResourceView): + """View to interact with the option flow manager.""" + + url = "/api/config/config_entries/options/flow/{flow_id}" + name = "api:config:config_entries:options:flow:resource" + + async def get(self, request, flow_id): + """Get the current state of a data_entry_flow.""" + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") + + return await super().get(request, flow_id) + + # pylint: disable=arguments-differ + async def post(self, request, flow_id): + """Handle a POST request.""" + if not request["hass_user"].is_admin: + raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") + + # pylint: disable=no-value-for-parameter + return await super().post(request, flow_id) + + +@websocket_api.require_admin +@websocket_api.websocket_command({"type": "config_entries/flow/progress"}) +def config_entries_progress(hass, connection, msg): + """List flows that are in progress but not started by a user. + + Example of a non-user initiated flow is a discovered Hue hub that + requires user interaction to finish setup. + """ + connection.send_result( + msg["id"], + [ + flw + for flw in hass.config_entries.flow.async_progress() + if flw["context"]["source"] != config_entries.SOURCE_USER + ], + ) + + +@websocket_api.require_admin +@websocket_api.async_response +@websocket_api.websocket_command( + {"type": "config_entries/system_options/list", "entry_id": str} +) +async def system_options_list(hass, connection, msg): + """List all system options for a config entry.""" + entry_id = msg["entry_id"] + entry = hass.config_entries.async_get_entry(entry_id) + + if entry: + connection.send_result(msg["id"], entry.system_options.as_dict()) + + +@websocket_api.require_admin +@websocket_api.async_response +@websocket_api.websocket_command( + { + "type": "config_entries/system_options/update", + "entry_id": str, + vol.Optional("disable_new_entities"): bool, + } +) +async def system_options_update(hass, connection, msg): + """Update config entry system options.""" + changes = dict(msg) + changes.pop("id") + changes.pop("type") + entry_id = changes.pop("entry_id") + entry = hass.config_entries.async_get_entry(entry_id) + + if entry is None: + connection.send_error( + msg["id"], websocket_api.const.ERR_NOT_FOUND, "Config entry not found" + ) + return + + hass.config_entries.async_update_entry(entry, system_options=changes) + connection.send_result(msg["id"], entry.system_options.as_dict()) diff --git a/pool/shard001/Python/0014763_plugin.py b/pool/shard001/Python/0014763_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a2511542c66be5c7f6d1ec2d305fb2502d02aa --- /dev/null +++ b/pool/shard001/Python/0014763_plugin.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +''' + :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` + :copyright: © 2015-2018 by the SaltStack Team, see AUTHORS for more details. + :license: Apache 2.0, see LICENSE for more details. + + + pytest_logging.plugin + ~~~~~~~~~~~~~~~~~~~~~ +''' +# pylint: disable=protected-access,redefined-outer-name + +# Import python libs +from __future__ import absolute_import +import os +import shutil +import logging +from functools import partial + +# Import py libs +import py + +# Import pytest libs +import pytest +from _pytest.pathlib import Path +try: + from _pytest.monkeypatch import MonkeyPatch +except ImportError: + from _pytest.monkeypatch import monkeypatch as MonkeyPatch + +from pytest_tempdir import hookspec + +log = logging.getLogger('pytest.tempdir') + + +def pytest_addhooks(pluginmanager): + ''' + Register our new hooks + ''' + pluginmanager.add_hookspecs(hookspec) + + +def pytest_addoption(parser): + ''' + Add CLI options to py.test + ''' + group = parser.getgroup('tempdir', 'Temporary Directory Options') + group.addoption('--tempdir-basename', + default=None, + help='The predictable temporary directory base name. ' + 'Defaults to the current directory name if not ' + 'passed as a CLI parameter and if not defined ' + 'using the tempdir_basename session scoped fixture. ' + 'If the temporary directory exists when the test ' + 'session starts, IT WILL BE WIPED!') + group.addoption('--tempdir-no-clean', + default=False, + action='store_true', + help='Disable the removal of the created temporary directory') + + +def pytest_report_header(config): + ''' + return a string to be displayed as header info for terminal reporting. + ''' + return 'tempdir: {0}'.format(config._tempdir.strpath) + + +class TempDir(object): + def __init__(self, config): + self.config = config + self._prepare() + + def _prepare(self): + self.counters = {} + basename = None + cli_tempdir_basename = self.config.getvalue('tempdir_basename') + if cli_tempdir_basename is not None: + basename = cli_tempdir_basename + else: + # Let's see if we have a pytest_tempdir_basename hook implementation + basename = self.config.hook.pytest_tempdir_basename() + if basename is None: + # If by now, basename is still None, use the current directory name + basename = os.path.basename(py.path.local().strpath) # pylint: disable=no-member + mpatch = MonkeyPatch() + + temproot = self.config.hook.pytest_tempdir_temproot() + if not isinstance(temproot, Path): + temproot = py.path.local(temproot) + + # Let's get the full real path to the tempdir + tempdir = temproot.join(basename).realpath() + if tempdir.exists(): + # If it exists, it's a stale tempdir. Remove it + log.warning('Removing stale tempdir: %s', tempdir.strpath) + shutil.rmtree(tempdir.strpath, ignore_errors=True) + # Make sure the tempdir is created + tempdir.ensure(dir=True) + # Store a reference the tempdir for cleanup purposes when ending the test + # session + mpatch.setattr(self.config, '_tempdir', self, raising=False) + # Register the cleanup actions + self.config._cleanup.extend([ + mpatch.undo, + self._clean_up_tempdir + ]) + self.tempdir = tempdir + + def _clean_up_tempdir(self): + ''' + Clean up temporary directory + ''' + if self.config.getvalue('--tempdir-no-clean') is False: + log.debug('Cleaning up the tempdir: %s', self.tempdir.strpath) + try: + shutil.rmtree(self.tempdir.strpath, ignore_errors=True) + except py.error.ENOENT: # pylint: disable=no-member + pass + else: + log.debug('No cleaning up tempdir: %s', self.tempdir.strpath) + + def mkdir(self, path, use_existing=False): + abspath = self.tempdir.join(path) + if abspath not in self.counters: + self.counters[abspath] = 0 + while True: + newdir = self.tempdir.join('{0}{1}'.format(path, self.counters[abspath])) + if newdir.exists() and use_existing is False: + self.counters[abspath] += 1 + continue + log.debug('New Dir: %s', newdir) + return newdir.ensure(dir=True) + + def __getattribute__(self, name): + try: + return object.__getattribute__(self, name) + except AttributeError: + return getattr(self.tempdir, name) + + +def pytest_configure(config): + ''' + Configure the tempdir + ''' + # Prep tempdir + TempDir(config) + + +@pytest.mark.trylast +def pytest_tempdir_temproot(): + return py.path.local.get_temproot() # pylint: disable=no-member + + +@pytest.fixture(scope='session') +def tempdir(request): + ''' + tmpdir pytest fixture + ''' + return request.config._tempdir diff --git a/pool/shard001/Python/0014766_proxy_tests.py b/pool/shard001/Python/0014766_proxy_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..b3606bc3913616e2ccabba60475c3a972f874062 --- /dev/null +++ b/pool/shard001/Python/0014766_proxy_tests.py @@ -0,0 +1,55 @@ +import unittest + +from contesto import config +try: + from mock import Mock, patch +except ImportError: + from unittest.mock import Mock, patch +import os +from contesto.basis import test_case +from contesto.basis.test_case import ContestoTestCase +from contesto.core.driver_mixin import SeleniumDriverMixin + + +class ProxyInDesireCapabilitiesTestCase(unittest.TestCase): + proxy_host = "http://localhost:9091" + + def setUp(self): + config.add_config_file(os.path.abspath(os.path.dirname(__file__)) + "/data/config/dc_with_proxy.ini") + + def test_proxy_adding_in_desired_capabilities_with_config(self): + driver = SeleniumDriverMixin() + driver_settings = getattr(config, driver.driver_section) + desired_capabilities = driver._form_desired_capabilities(driver_settings) + ContestoTestCase.desired_capabilities = desired_capabilities + with patch.object(test_case.BMPClient, '__init__', return_value=None): + test_case.BMPClient.proxy = self.proxy_host + ContestoTestCase._connect_to_proxy() + + proxy_params = { + 'proxy': { + 'proxyType': 'MANUAL', + 'sslProxy': self.proxy_host, + 'httpProxy': self.proxy_host + } + } + self.assertDictEqual(ContestoTestCase.desired_capabilities['proxy'], proxy_params['proxy']) + + def tearDown(self): + config.browsermobproxy['enabled'] = 0 + + +class ProxyDisabledInDesireCapabilitiesTestCase(unittest.TestCase): + proxy_host = "http://localhost:9091" + + def test_proxy_disabled_in_desired_capabilities_by_default(self): + driver = SeleniumDriverMixin() + driver_settings = getattr(config, driver.driver_section) + desired_capabilities = driver._form_desired_capabilities(driver_settings) + ContestoTestCase.desired_capabilities = desired_capabilities + with patch.object(test_case.BMPClient, '__init__', return_value=None): + test_case.BMPClient.proxy = self.proxy_host + ContestoTestCase._connect_to_proxy() + + self.assertEqual(None, ContestoTestCase.desired_capabilities.get('proxy', None), + ContestoTestCase.desired_capabilities.get('proxy')) diff --git a/pool/shard001/Python/0014771_celery.py b/pool/shard001/Python/0014771_celery.py new file mode 100644 index 0000000000000000000000000000000000000000..fba97da0c3e7aed8b46eddf148d5f22929c8f090 --- /dev/null +++ b/pool/shard001/Python/0014771_celery.py @@ -0,0 +1,21 @@ +from __future__ import absolute_import, unicode_literals +import os +from celery import Celery + +# set the default Django settings module for the 'celery' program. +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rps.settings') + +app = Celery('rps') + +# Using a string here means the worker doesn't have to serialize +# the configuration object to child processes. +# - namespace='CELERY' means all celery-related configuration keys +# should have a `CELERY_` prefix. +app.config_from_object('django.conf:settings', namespace='CELERY') + +# Load task modules from all registered Django app configs. +app.autodiscover_tasks() + +@app.task(bind=True) +def debug_task(self): + print('Request: {0!r}'.format(self.request)) diff --git a/pool/shard001/Python/0014786_0089_auto_20160212_1018.py b/pool/shard001/Python/0014786_0089_auto_20160212_1018.py new file mode 100644 index 0000000000000000000000000000000000000000..65176339ca6bbbe0f10ac334693870cd7945a134 --- /dev/null +++ b/pool/shard001/Python/0014786_0089_auto_20160212_1018.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('lizard_efcis', '0088_auto_20160120_1511'), + ] + + operations = [ + migrations.AlterModelOptions( + name='meetstatus', + options={'ordering': ['index'], 'verbose_name': 'Locatiestatus', 'verbose_name_plural': 'Locatiestatus'}, + ), + migrations.RemoveField( + model_name='locatie', + name='bio_status', + ), + migrations.DeleteModel( + name='BioStatus', + ), + migrations.RemoveField( + model_name='locatie', + name='fc_status', + ), + migrations.DeleteModel( + name='FCStatus', + ), + migrations.AlterField( + model_name='locatie', + name='meet_status', + field=models.ForeignKey(related_name='locaties', verbose_name='locatiestatus', blank=True, to='lizard_efcis.MeetStatus', null=True), + preserve_default=True, + ), + ] diff --git a/pool/shard001/Python/0014787_export_saved_model_tpu_lib_tf1_test.py b/pool/shard001/Python/0014787_export_saved_model_tpu_lib_tf1_test.py new file mode 100644 index 0000000000000000000000000000000000000000..653535aa3b75576fa73662c3fc3ea2d257908107 --- /dev/null +++ b/pool/shard001/Python/0014787_export_saved_model_tpu_lib_tf1_test.py @@ -0,0 +1,71 @@ +# Copyright 2019 The TensorFlow Authors. 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. +# ============================================================================== +"""Test for object detection's TPU exporter.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import unittest + +from absl.testing import parameterized +import numpy as np +import tensorflow.compat.v1 as tf + +from object_detection.tpu_exporters import export_saved_model_tpu_lib +from object_detection.utils import tf_version + +flags = tf.app.flags +FLAGS = flags.FLAGS + + +def get_path(path_suffix): + return os.path.join(tf.resource_loader.get_data_files_path(), 'testdata', + path_suffix) + + +@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only test.') +class ExportSavedModelTPUTest(tf.test.TestCase, parameterized.TestCase): + + @parameterized.named_parameters( + ('ssd', get_path('ssd/ssd_pipeline.config'), 'image_tensor', True, 20), + ('faster_rcnn', + get_path('faster_rcnn/faster_rcnn_resnet101_atrous_coco.config'), + 'image_tensor', True, 20)) + def testExportAndLoad(self, + pipeline_config_file, + input_type='image_tensor', + use_bfloat16=False, + repeat=1): + + input_placeholder_name = 'placeholder_tensor' + export_dir = os.path.join(FLAGS.test_tmpdir, 'tpu_saved_model') + if tf.gfile.Exists(export_dir): + tf.gfile.DeleteRecursively(export_dir) + ckpt_path = None + export_saved_model_tpu_lib.export(pipeline_config_file, ckpt_path, + export_dir, input_placeholder_name, + input_type, use_bfloat16) + + inputs = np.random.rand(256, 256, 3) + tensor_dict_out = export_saved_model_tpu_lib.run_inference_from_saved_model( + inputs, export_dir, input_placeholder_name, repeat) + for k, v in tensor_dict_out.items(): + tf.logging.info('{}: {}'.format(k, v)) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard001/Python/0014788_balloon_lung.py b/pool/shard001/Python/0014788_balloon_lung.py new file mode 100644 index 0000000000000000000000000000000000000000..0da6b35301c54371de7abd3093f090747af9181b --- /dev/null +++ b/pool/shard001/Python/0014788_balloon_lung.py @@ -0,0 +1,66 @@ +import numpy as np + +from deluca.lung.core import LungEnv + + +def PropValve(x): # copied from Controller.__SimulatedPropValve + y = 3 * x + flow_new = 1.0 * (np.tanh(0.03 * (y - 130)) + 1) + return np.clip(flow_new, 0.0, 1.72) + + +def Solenoid(x): # copied from Controller.__SimulatedSolenoid + if x > 0: + return x / x + else: + return x * 0.0 + + +# balloon physics vent ported from Cohen lab's repository +# Sources: +# https://github.com/CohenLabPrinceton/ventilator-Dev/blob/master/sandbox/HOWTO_RunController.ipynb +# https://github.com/CohenLabPrinceton/ventilator-Dev/blob/master/vent/controller/control_module.py +class BalloonLung(LungEnv): + def __init__(self, min_volume=6, PEEP=5, PC=40, RP=1, leak=False, **kwargs): + # dynamics hyperparameters + self.min_volume = min_volume + self.PC = PC + self.RP = RP + self.P0 = 0.0 + self.leak = leak + self.PEEP = PEEP + + self.r0 = (3 * self.min_volume / (4 * np.pi)) ** (1 / 3) + # reset states + self.reset() + + def reset(self): + super().reset() + # keep volume as the only free parameter + self.volume = self.min_volume + self.compute_aux_states() + + def compute_aux_states(self): + # compute all other state vars, which are just functions of volume + r = (3 * self.volume / (4 * np.pi)) ** (1 / 3) + self.pressure = self.P0 + self.PC * (1 - (self.r0 / r) ** 6) / (self.r0 ** 2 * r) + + def step(self, u_in, u_out): + # 2-dimensional action per timestep: PIP/PEEP voltages + flow = np.clip(PropValve(u_in), 0, 2) * self.RP + if self.pressure > self.PEEP: + flow = flow - np.clip(Solenoid(u_out), 0, 2) * 0.05 * self.pressure + + # update by flow rate + self.volume = self.volume + flow * self.dt + + # simulate leakage + if self.leak: + RC = 5 + s = self.dt / (RC + self.dt) + self.volume = self.volume + s * (self.min_volume - self.volume) + + # compute and record state + self.compute_aux_states() + + return self.pressure diff --git a/pool/shard001/Python/0014799_grep_AS.py b/pool/shard001/Python/0014799_grep_AS.py new file mode 100644 index 0000000000000000000000000000000000000000..32681c242f3aa762888666a7493e4a3c55baa73b --- /dev/null +++ b/pool/shard001/Python/0014799_grep_AS.py @@ -0,0 +1,19 @@ +import argparse +import sys + +parser = argparse.ArgumentParser() +parser.add_argument("blt") +parser.add_argument("asn") +args = parser.parse_args() + + +with open(args.blt, "r") as f: + for line in f: + res = line.split("|") + if len(res) == 6: #"withdraw" + if res[4] == args.asn: + sys.stdout.write(line) + continue + as_path = res[6] + if args.asn in as_path.split(" "): + sys.stdout.write(line) diff --git a/pool/shard001/Python/0014802_test_main.py b/pool/shard001/Python/0014802_test_main.py new file mode 100644 index 0000000000000000000000000000000000000000..534a1e6d32e30651170e1441e722ee29e45bfd7b --- /dev/null +++ b/pool/shard001/Python/0014802_test_main.py @@ -0,0 +1,84 @@ +from __future__ import division +import os +import json +from textwrap import dedent +import nose.tools as nt +from .. import main + + +def test_params(): + + try: + with open("params.py", "w") as fid: + fid.write(dedent(""" + foo = dict(bar='hello world', + resp_keys=["a", "b"], + fmri_resp_keys=["1", "2"], + monitor_name="laptop", + fmri_monitor_name="scanner") + """)) + + p = main.Params("foo") + assert p.bar == "hello world" + + p.set_by_cmdline(["-s", "cj", "-debug"]) + assert p.subject == "cj" + assert p.debug + assert not p.fmri + assert p.resp_keys == ["a", "b"] + assert p.monitor_name == "laptop" + + p.to_json("params.json") + assert os.path.exists("params.json") + with open("params.json") as fid: + archive = json.load(fid) + assert archive["subject"] == "cj" + assert archive["debug"] + + p.set_by_cmdline(["-fmri"]) + assert p.resp_keys == ["1", "2"] + assert p.monitor_name == "scanner" + + finally: + for f in ["params.py", "params.pyc", "params.json"]: + if os.path.exists(f): + os.remove(f) + + +def test_categorical(): + + # Very simple tests + sample = main.categorical([.5, .5]) + assert sample in [0, 1] + + sample = main.categorical([1, 0]) + nt.assert_equal(sample, 0) + + +def test_subject_state(): + + subj = "cj" + state1 = main.subject_specific_state(subj) + state2 = main.subject_specific_state(subj) + assert state1.rand() == state2.rand() + state3 = main.subject_specific_state("danny") + assert state1.rand() != state3.rand() + + +def test_archive_old_version(): + + orig = "test_file.txt" + new = "test_file_1.txt" + text = "my secret service codename is 'flamingo'" + try: + with open(orig, "w") as fid: + fid.write(text) + main.archive_old_version(orig) + + assert os.path.exists(new) + moved_text = open(new).read().strip() + assert text == moved_text + finally: + for f in [orig, new]: + if os.path.exists(f): + os.remove(f) diff --git a/pool/shard001/Python/0014803_template.py b/pool/shard001/Python/0014803_template.py new file mode 100644 index 0000000000000000000000000000000000000000..668db81661963fd1dade586d8c331b93ab628195 --- /dev/null +++ b/pool/shard001/Python/0014803_template.py @@ -0,0 +1,122 @@ +""" +Allows the creation of a sensor that breaks out state_attributes. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sensor.template/ +""" +import logging + +from homeassistant.components.sensor import ENTITY_ID_FORMAT +from homeassistant.const import ( + ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, + ATTR_ENTITY_ID, MATCH_ALL) +from homeassistant.exceptions import TemplateError +from homeassistant.helpers.entity import Entity, generate_entity_id +from homeassistant.helpers import template +from homeassistant.helpers.event import track_state_change +from homeassistant.util import slugify + +_LOGGER = logging.getLogger(__name__) +CONF_SENSORS = 'sensors' + + +# pylint: disable=unused-argument +def setup_platform(hass, config, add_devices, discovery_info=None): + """Setup the template sensors.""" + sensors = [] + if config.get(CONF_SENSORS) is None: + _LOGGER.error("Missing configuration data for sensor platform") + return False + + for device, device_config in config[CONF_SENSORS].items(): + if device != slugify(device): + _LOGGER.error("Found invalid key for sensor.template: %s. " + "Use %s instead", device, slugify(device)) + continue + + if not isinstance(device_config, dict): + _LOGGER.error("Missing configuration data for sensor %s", device) + continue + + friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) + unit_of_measurement = device_config.get(ATTR_UNIT_OF_MEASUREMENT) + state_template = device_config.get(CONF_VALUE_TEMPLATE) + if state_template is None: + _LOGGER.error( + "Missing %s for sensor %s", CONF_VALUE_TEMPLATE, device) + continue + + entity_ids = device_config.get(ATTR_ENTITY_ID, MATCH_ALL) + + sensors.append( + SensorTemplate( + hass, + device, + friendly_name, + unit_of_measurement, + state_template, + entity_ids) + ) + if not sensors: + _LOGGER.error("No sensors added") + return False + add_devices(sensors) + return True + + +class SensorTemplate(Entity): + """Representation of a Template Sensor.""" + + # pylint: disable=too-many-arguments + def __init__(self, hass, device_id, friendly_name, unit_of_measurement, + state_template, entity_ids): + """Initialize the sensor.""" + self.hass = hass + self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, device_id, + hass=hass) + self._name = friendly_name + self._unit_of_measurement = unit_of_measurement + self._template = state_template + self._state = None + + self.update() + + def template_sensor_state_listener(entity, old_state, new_state): + """Called when the target device changes state.""" + self.update_ha_state(True) + + track_state_change(hass, entity_ids, + template_sensor_state_listener) + + @property + def name(self): + """Return the name of the sensor.""" + return self._name + + @property + def state(self): + """Return the state of the sensor.""" + return self._state + + @property + def unit_of_measurement(self): + """Return the unit_of_measurement of the device.""" + return self._unit_of_measurement + + @property + def should_poll(self): + """No polling needed.""" + return False + + def update(self): + """Get the latest data and update the states.""" + try: + self._state = template.render(self.hass, self._template) + except TemplateError as ex: + if ex.args and ex.args[0].startswith( + "UndefinedError: 'None' has no attribute"): + # Common during HA startup - so just a warning + _LOGGER.warning(ex) + return + self._state = None + _LOGGER.error(ex) diff --git a/pool/shard001/Python/0014805_notify.py b/pool/shard001/Python/0014805_notify.py new file mode 100644 index 0000000000000000000000000000000000000000..6744973d4b3f790d4d9827516dd46951f836d767 --- /dev/null +++ b/pool/shard001/Python/0014805_notify.py @@ -0,0 +1,46 @@ +# -*- coding: utf8 -*- + +import argparse +import json + +from sh import curl + +from zabbix_kato.formatter import color + + +URL = 'https://{host}/rooms/{room_id}/simple' + +parser = argparse.ArgumentParser() +parser.add_argument('room_id') +parser.add_argument('--message', type=argparse.FileType('r'), default='-') +parser.add_argument('--host', dest='host', default='api.kato.im') +parser.add_argument('--trigger_status', default='PROBLEM') +parser.add_argument('--trigger_severity', type=int, default=2) + + +def send(host, room_id, message, trigger_status, trigger_severity): + print(curl( + URL.format(host=host, room_id=room_id), + d=json.dumps({ + 'from': 'zabbix', + 'renderer': 'markdown', + 'text': message, + 'color': color(trigger_status, trigger_severity) + }), + H='Content-type: application/json' + )) + + +def main(): + args = parser.parse_args() + send( + args.host, + args.room_id, + args.message.read(), + args.trigger_status, + args.trigger_severity + ) + + +if __name__ == '__main__': + main() diff --git a/pool/shard001/Python/0014808_main.py b/pool/shard001/Python/0014808_main.py new file mode 100644 index 0000000000000000000000000000000000000000..043fbc7b4b1d36df35accb9af1bfcc8579afb29e --- /dev/null +++ b/pool/shard001/Python/0014808_main.py @@ -0,0 +1,168 @@ +from flask import request,abort,render_template,redirect,url_for,flash,current_app +import arrow +import logging +from flask_security import current_user +import validators +from functools import wraps +from dateutil import tz + + +from unifispot.core.app import UnifispotModule +from unifispot.utils.translation import _l,_n,_ +from unifispot.core.const import * +from unifispot.core.models import Wifisite,Client,Landingpage +from unifispot.core.guestutils import validate_track,init_track,redirect_guest,\ + guestlog_warn,guestlog_info,guestlog_error,\ + guestlog_debug,guestlog_exception,\ + assign_guest_entry,validate_loginauth_usage,\ + get_loginauth_validator,handle_override,\ + loginauth_check_relogin + +from unifispot.core.baseviews import SiteModuleAPI +from .models import Phoneconfig,Phoneauth +from .forms import PhoneConfigForm,generate_phoneform,PhoneOverrideForm + + + +module = UnifispotModule('phone','login', __name__, template_folder='templates') + + + + +class PhoneConfigAPI(SiteModuleAPI): + + def get_form_obj(self): + return PhoneConfigForm() + + def get_name(self): + return self.__class__.__name__ + + def get_modal_obj(self): + return Phoneconfig + + def get_config_template(self): + return 'module_config_phone.html' + +PhoneConfigAPI.register(module, route_base='/s//phone/config') + +#----------------guest related +def get_login_config(wifisite,guesttrack): + '''This method needs to be added to all login plugins + Called by redirec_guest when rendering multi landing page + return loginconfig object for the current login method + + ''' + #get and validated phoneconfig + phoneconfig = Phoneconfig.query.filter_by(siteid=wifisite.id).first() + if not phoneconfig: + guestlog_warn('empty phoneconfig, creating default one',wifisite,guesttrack) + phoneconfig = Phoneconfig() + phoneconfig.siteid = wifisite.id + client = Client.query.get(wifisite.client_id) + phoneconfig.account_id = client.account_id + phoneconfig.save() + return phoneconfig + + +def check_device_relogin(wifisite,guesttrack,loginconfig): + '''This method needs to be added to all login plugins + Called by redirec_guest when rendering multi landing page + return True if the given device can be logged in successfully + + ''' + return loginauth_check_relogin(wifisite,guesttrack,Phoneauth,loginconfig) + + +def get_multilanding_html(wifisite,guesttrack): + '''This method needs to be added to all login plugins + Called by redirec_guest when rendering multi landing page + return HTML for buttons or otherwise that needs to be rendered + on the multilanding.html page + + ''' + loginurl = url_for('unifispot.modules.phone.guest_login', + trackid=guesttrack.trackid) + return '''

+ + '''%loginurl+_('Login with Phonenumber')+ ''' +

''' + + +def validate_phoneconfig(f): + '''Decorator for validating phoneconfig detials. + It injects phoneconfigobjects in kwargs + + ''' + @wraps(f) + def decorated_function(*args, **kwargs): + wifisite = kwargs.get('wifisite') + guesttrack = kwargs.get('guesttrack') + #get the function name used + fname = f.func_name + #check if site is configured for phonelogin + if not wifisite.check_login_en('auth_phone'): + guestlog_warn('trying to access phone_login for non configured site',wifisite,guesttrack) + abort(404) + #get and validated phoneconfig + phoneconfig = Phoneconfig.query.filter_by(siteid=wifisite.id).first() + if not phoneconfig: + guestlog_warn('empty phoneconfig, creating default one',wifisite,guesttrack) + phoneconfig = Phoneconfig() + phoneconfig.siteid = wifisite.id + client = Client.query.get(wifisite.client_id) + phoneconfig.account_id = client.account_id + phoneconfig.save() + kwargs['phoneconfig'] = phoneconfig + return f(*args, **kwargs) + return decorated_function + + +@module.route('/phone/guest/',methods = ['GET', 'POST']) +@validate_track +@validate_phoneconfig +@get_loginauth_validator(Phoneauth,'phoneconfig','phone','auth_phone') +def guest_login(trackid,guesttrack,wifisite,guestdevice,phoneconfig,loginauth): + ''' Function to called if the site is configured with phone login + + ''' + + #show the configured landing page + phone_form = generate_phoneform(phoneconfig) + if phone_form.validate_on_submit(): + #assign a guest based on form + newguest = assign_guest_entry(wifisite,guesttrack,form=phone_form) + #create new auth + loginauth.populate_auth_details(phoneconfig) + loginauth.reset() + loginauth.state = LOGINAUTH_FIRST + loginauth.save() + #update guesttrack + guesttrack.state = GUESTTRACK_POSTLOGIN + guesttrack.loginauthid = loginauth.id + guesttrack.updatestat('auth_phone',1) + #update guestdevice + guestdevice.guestid = newguest.id + guestdevice.save() + #update guest + newguest.demo = guesttrack.demo + newguest.devices.append(guestdevice) + newguest.save() + guestlog_debug('phone_login new guest track ID:%s'%newguest.id,wifisite,guesttrack) + return redirect_guest(wifisite,guesttrack) + + landingpage = Landingpage.query.filter_by(siteid=wifisite.id).first() + return render_template('guest/%s/phone_landing.html'%wifisite.template,\ + wifisite=wifisite,landingpage=landingpage,phone_form=phone_form, + trackid=trackid) + +@module.route('/phone/override/',methods = ['GET', 'POST']) +@validate_track +@validate_phoneconfig +def guest_override(trackid,guesttrack,wifisite,guestdevice,phoneconfig): + ''' Function to called if the guest have exceeded daily/monthly limit + + ''' + + return handle_override(guesttrack,wifisite,guestdevice,phoneconfig, + Phoneauth,PhoneOverrideForm,'limit_override.html', + 'auth_phone') diff --git a/pool/shard001/Python/0014812_init__.py b/pool/shard001/Python/0014812_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b89b307db9e8c592a3cdc27a9f848015ad6549b --- /dev/null +++ b/pool/shard001/Python/0014812_init__.py @@ -0,0 +1,238 @@ +""" +Support for Envisalink devices. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/envisalink/ +""" +import asyncio +import logging + +import voluptuous as vol + +from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv +from homeassistant.const import EVENT_HOMEASSISTANT_STOP, CONF_TIMEOUT +from homeassistant.helpers.entity import Entity +from homeassistant.helpers.discovery import async_load_platform +from homeassistant.helpers.dispatcher import async_dispatcher_send + +REQUIREMENTS = ['pyenvisalink==3.8'] + +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'envisalink' + +DATA_EVL = 'envisalink' + +CONF_CODE = 'code' +CONF_EVL_HOST = 'host' +CONF_EVL_KEEPALIVE = 'keepalive_interval' +CONF_EVL_PORT = 'port' +CONF_EVL_VERSION = 'evl_version' +CONF_PANEL_TYPE = 'panel_type' +CONF_PANIC = 'panic_type' +CONF_PARTITIONNAME = 'name' +CONF_PARTITIONS = 'partitions' +CONF_PASS = 'password' +CONF_USERNAME = 'user_name' +CONF_ZONEDUMP_INTERVAL = 'zonedump_interval' +CONF_ZONENAME = 'name' +CONF_ZONES = 'zones' +CONF_ZONETYPE = 'type' + +DEFAULT_PORT = 4025 +DEFAULT_EVL_VERSION = 3 +DEFAULT_KEEPALIVE = 60 +DEFAULT_ZONEDUMP_INTERVAL = 30 +DEFAULT_ZONETYPE = 'opening' +DEFAULT_PANIC = 'Police' +DEFAULT_TIMEOUT = 10 + +SIGNAL_ZONE_UPDATE = 'envisalink.zones_updated' +SIGNAL_PARTITION_UPDATE = 'envisalink.partition_updated' +SIGNAL_KEYPAD_UPDATE = 'envisalink.keypad_updated' + +ZONE_SCHEMA = vol.Schema({ + vol.Required(CONF_ZONENAME): cv.string, + vol.Optional(CONF_ZONETYPE, default=DEFAULT_ZONETYPE): cv.string}) + +PARTITION_SCHEMA = vol.Schema({ + vol.Required(CONF_PARTITIONNAME): cv.string}) + +CONFIG_SCHEMA = vol.Schema({ + DOMAIN: vol.Schema({ + vol.Required(CONF_EVL_HOST): cv.string, + vol.Required(CONF_PANEL_TYPE): + vol.All(cv.string, vol.In(['HONEYWELL', 'DSC'])), + vol.Required(CONF_USERNAME): cv.string, + vol.Required(CONF_PASS): cv.string, + vol.Optional(CONF_CODE): cv.string, + vol.Optional(CONF_PANIC, default=DEFAULT_PANIC): cv.string, + vol.Optional(CONF_ZONES): {vol.Coerce(int): ZONE_SCHEMA}, + vol.Optional(CONF_PARTITIONS): {vol.Coerce(int): PARTITION_SCHEMA}, + vol.Optional(CONF_EVL_PORT, default=DEFAULT_PORT): cv.port, + vol.Optional(CONF_EVL_VERSION, default=DEFAULT_EVL_VERSION): + vol.All(vol.Coerce(int), vol.Range(min=3, max=4)), + vol.Optional(CONF_EVL_KEEPALIVE, default=DEFAULT_KEEPALIVE): + vol.All(vol.Coerce(int), vol.Range(min=15)), + vol.Optional( + CONF_ZONEDUMP_INTERVAL, + default=DEFAULT_ZONEDUMP_INTERVAL): vol.Coerce(int), + vol.Optional( + CONF_TIMEOUT, + default=DEFAULT_TIMEOUT): vol.Coerce(int), + }), +}, extra=vol.ALLOW_EXTRA) + +SERVICE_CUSTOM_FUNCTION = 'invoke_custom_function' +ATTR_CUSTOM_FUNCTION = 'pgm' +ATTR_PARTITION = 'partition' + +SERVICE_SCHEMA = vol.Schema({ + vol.Required(ATTR_CUSTOM_FUNCTION): cv.string, + vol.Required(ATTR_PARTITION): cv.string, +}) + + +async def async_setup(hass, config): + """Set up for Envisalink devices.""" + from pyenvisalink import EnvisalinkAlarmPanel + + conf = config.get(DOMAIN) + + host = conf.get(CONF_EVL_HOST) + port = conf.get(CONF_EVL_PORT) + code = conf.get(CONF_CODE) + panel_type = conf.get(CONF_PANEL_TYPE) + panic_type = conf.get(CONF_PANIC) + version = conf.get(CONF_EVL_VERSION) + user = conf.get(CONF_USERNAME) + password = conf.get(CONF_PASS) + keep_alive = conf.get(CONF_EVL_KEEPALIVE) + zone_dump = conf.get(CONF_ZONEDUMP_INTERVAL) + zones = conf.get(CONF_ZONES) + partitions = conf.get(CONF_PARTITIONS) + connection_timeout = conf.get(CONF_TIMEOUT) + sync_connect = asyncio.Future(loop=hass.loop) + + controller = EnvisalinkAlarmPanel( + host, port, panel_type, version, user, password, zone_dump, + keep_alive, hass.loop, connection_timeout) + hass.data[DATA_EVL] = controller + + @callback + def login_fail_callback(data): + """Handle when the evl rejects our login.""" + _LOGGER.error("The Envisalink rejected your credentials") + if not sync_connect.done(): + sync_connect.set_result(False) + + @callback + def connection_fail_callback(data): + """Network failure callback.""" + _LOGGER.error("Could not establish a connection with the Envisalink") + if not sync_connect.done(): + sync_connect.set_result(False) + + @callback + def connection_success_callback(data): + """Handle a successful connection.""" + _LOGGER.info("Established a connection with the Envisalink") + if not sync_connect.done(): + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, + stop_envisalink) + sync_connect.set_result(True) + + @callback + def zones_updated_callback(data): + """Handle zone timer updates.""" + _LOGGER.debug("Envisalink sent a zone update event. Updating zones...") + async_dispatcher_send(hass, SIGNAL_ZONE_UPDATE, data) + + @callback + def alarm_data_updated_callback(data): + """Handle non-alarm based info updates.""" + _LOGGER.debug("Envisalink sent new alarm info. Updating alarms...") + async_dispatcher_send(hass, SIGNAL_KEYPAD_UPDATE, data) + + @callback + def partition_updated_callback(data): + """Handle partition changes thrown by evl (including alarms).""" + _LOGGER.debug("The envisalink sent a partition update event") + async_dispatcher_send(hass, SIGNAL_PARTITION_UPDATE, data) + + @callback + def stop_envisalink(event): + """Shutdown envisalink connection and thread on exit.""" + _LOGGER.info("Shutting down Envisalink") + controller.stop() + + async def handle_custom_function(call): + """Handle custom/PGM service.""" + custom_function = call.data.get(ATTR_CUSTOM_FUNCTION) + partition = call.data.get(ATTR_PARTITION) + controller.command_output(code, partition, custom_function) + + controller.callback_zone_timer_dump = zones_updated_callback + controller.callback_zone_state_change = zones_updated_callback + controller.callback_partition_state_change = partition_updated_callback + controller.callback_keypad_update = alarm_data_updated_callback + controller.callback_login_failure = login_fail_callback + controller.callback_login_timeout = connection_fail_callback + controller.callback_login_success = connection_success_callback + + _LOGGER.info("Start envisalink.") + controller.start() + + result = await sync_connect + if not result: + return False + + # Load sub-components for Envisalink + if partitions: + hass.async_create_task(async_load_platform( + hass, 'alarm_control_panel', 'envisalink', { + CONF_PARTITIONS: partitions, + CONF_CODE: code, + CONF_PANIC: panic_type + }, config + )) + hass.async_create_task(async_load_platform( + hass, 'sensor', 'envisalink', { + CONF_PARTITIONS: partitions, + CONF_CODE: code + }, config + )) + if zones: + hass.async_create_task(async_load_platform( + hass, 'binary_sensor', 'envisalink', { + CONF_ZONES: zones + }, config + )) + + hass.services.async_register(DOMAIN, + SERVICE_CUSTOM_FUNCTION, + handle_custom_function, + schema=SERVICE_SCHEMA) + + return True + + +class EnvisalinkDevice(Entity): + """Representation of an Envisalink device.""" + + def __init__(self, name, info, controller): + """Initialize the device.""" + self._controller = controller + self._info = info + self._name = name + + @property + def name(self): + """Return the name of the device.""" + return self._name + + @property + def should_poll(self): + """No polling needed.""" + return False diff --git a/pool/shard001/Python/0014815_user_interest_taxonomy_type.py b/pool/shard001/Python/0014815_user_interest_taxonomy_type.py new file mode 100644 index 0000000000000000000000000000000000000000..f95424283b81085e97354f9febd61dfcfd39d1b0 --- /dev/null +++ b/pool/shard001/Python/0014815_user_interest_taxonomy_type.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v9.enums", + marshal="google.ads.googleads.v9", + manifest={"UserInterestTaxonomyTypeEnum",}, +) + + +class UserInterestTaxonomyTypeEnum(proto.Message): + r"""Message describing a UserInterestTaxonomyType. + """ + + class UserInterestTaxonomyType(proto.Enum): + r"""Enum containing the possible UserInterestTaxonomyTypes.""" + UNSPECIFIED = 0 + UNKNOWN = 1 + AFFINITY = 2 + IN_MARKET = 3 + MOBILE_APP_INSTALL_USER = 4 + VERTICAL_GEO = 5 + NEW_SMART_PHONE_USER = 6 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pool/shard001/Python/0014817_test_payment_advice_batch.py b/pool/shard001/Python/0014817_test_payment_advice_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..a833ac6763140864ecb7d142bc45e8e6514bac7c --- /dev/null +++ b/pool/shard001/Python/0014817_test_payment_advice_batch.py @@ -0,0 +1,37 @@ +# -*- coding:utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo.addons.l10n_in_hr_payroll.tests.common import TestPaymentAdviceBase + + +class TestPaymentAdviceBatch(TestPaymentAdviceBase): + + def test_00_payment_advice_batch_flow(self): + # I want to generate a payslip from Payslip Batch. + payslip_run = self.PayslipRun.create({ + 'name': 'Payslip Batch' + }) + + # I create record for generating the Payslip for Payslip Batch. + payslip_employee = self.PayslipEmployee.create({ + 'employee_ids': [(4, self.rahul_emp.id)] + }) + + # I generate the payslip by clicking on Generate button wizard. + payslip_employee.with_context(active_id=payslip_run.id).compute_sheet() + + # I check that the Payslip Batch is in "Draft" + self.assertEqual(payslip_run.state, 'draft') + + # Now I close Payslip Batch + payslip_run.write({'state': 'close'}) + + # check that the Payslip Batch is "Close" + self.assertEqual(payslip_run.state, 'close') + + # I create Advice from Payslip Batch using Create Advice button + payslip_run.create_advice() + + # I check for Advice is created from Payslip Batch + advice_ids = self.Advice.search([('batch_id', '=', payslip_run.id)]) + self.assertTrue(bool(advice_ids), "Advice is not created from Payslip Batch.") diff --git a/pool/shard001/Python/0014822_summary_v1_image_op_test.py b/pool/shard001/Python/0014822_summary_v1_image_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..da5d2307b06cc74e6e8e1d8bd2a26ce6f33ec5e0 --- /dev/null +++ b/pool/shard001/Python/0014822_summary_v1_image_op_test.py @@ -0,0 +1,113 @@ +# Copyright 2015 The TensorFlow Authors. 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. +# ============================================================================== +"""Tests for summary V1 image op.""" + +import numpy as np + +from tensorflow.core.framework import summary_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.ops import image_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test +from tensorflow.python.summary import summary + + +class SummaryV1ImageOpTest(test.TestCase): + + def _AsSummary(self, s): + summ = summary_pb2.Summary() + summ.ParseFromString(s) + return summ + + def _CheckProto(self, image_summ, shape): + """Verify that the non-image parts of the image_summ proto match shape.""" + # Only the first 3 images are returned. + for v in image_summ.value: + v.image.ClearField("encoded_image_string") + expected = "\n".join(""" + value { + tag: "img/image/%d" + image { height: %d width: %d colorspace: %d } + }""" % ((i,) + shape[1:]) for i in range(3)) + self.assertProtoEquals(expected, image_summ) + + @test_util.run_deprecated_v1 + def testImageSummary(self): + for depth in (1, 3, 4): + for positive in False, True: + with self.session(graph=ops.Graph()) as sess: + shape = (4, 5, 7) + (depth,) + bad_color = [255, 0, 0, 255][:depth] + # Build a mostly random image with one nan + const = np.random.randn(*shape).astype(np.float32) + const[0, 1, 2] = 0 # Make the nan entry not the max + if positive: + const = 1 + np.maximum(const, 0) + scale = 255 / const.reshape(4, -1).max(axis=1) + offset = 0 + else: + scale = 127 / np.abs(const.reshape(4, -1)).max(axis=1) + offset = 128 + adjusted = np.floor(scale[:, None, None, None] * const + offset) + const[0, 1, 2, depth // 2] = np.nan + + # Summarize + summ = summary.image("img", const) + value = self.evaluate(summ) + self.assertEqual([], summ.get_shape()) + image_summ = self._AsSummary(value) + + # Decode the first image and check consistency + image = image_ops.decode_png(image_summ.value[0] + .image.encoded_image_string).eval() + self.assertAllEqual(image[1, 2], bad_color) + image[1, 2] = adjusted[0, 1, 2] + self.assertAllClose(image, adjusted[0], rtol=2e-5, atol=2e-5) + + # Check the rest of the proto + self._CheckProto(image_summ, shape) + + @test_util.run_deprecated_v1 + def testImageSummaryUint8(self): + np.random.seed(7) + for depth in (1, 3, 4): + with self.session(graph=ops.Graph()) as sess: + shape = (4, 5, 7) + (depth,) + + # Build a random uint8 image + images = np.random.randint(256, size=shape).astype(np.uint8) + tf_images = ops.convert_to_tensor(images) + self.assertEqual(tf_images.dtype, dtypes.uint8) + + # Summarize + summ = summary.image("img", tf_images) + value = self.evaluate(summ) + self.assertEqual([], summ.get_shape()) + image_summ = self._AsSummary(value) + + # Decode the first image and check consistency. + # Since we're uint8, everything should be exact. + image = image_ops.decode_png(image_summ.value[0] + .image.encoded_image_string).eval() + self.assertAllEqual(image, images[0]) + + # Check the rest of the proto + self._CheckProto(image_summ, shape) + + +if __name__ == "__main__": + test.main() diff --git a/pool/shard001/Python/0014824_recommendALS_users2items.py b/pool/shard001/Python/0014824_recommendALS_users2items.py new file mode 100644 index 0000000000000000000000000000000000000000..63918f0647222d17c534befe90360dfcefd8a158 --- /dev/null +++ b/pool/shard001/Python/0014824_recommendALS_users2items.py @@ -0,0 +1,87 @@ +""" +By Diogo Nicolau + +Recommendation engine based on Spark mllib ALS +Recommends a list of users to every item in the dataset + +Input: + - csv dataset; + - csv id -> user_hash; + - csv id -> app_names; + - number of recommendations per item +Output: + - recommendation files in the following format: + "item1",("user_reco1",score),("user_reco2",score) ... + "item2",("user_reco1",score),("user_reco2",score) ... + +""" + +from pyspark import SparkContext, SparkConf +from pyspark.mllib.recommendation import ALS, Rating +import sys +import csv + + +def main(data_source, users_source, apps_source, output, number_recs): + + users_data = {} + with open(users_source) as csvfile: + reader = csv.reader(csvfile) + for row in reader: + users_data[int(row[0])] = row[1] + + apps_data = {} + with open(apps_source) as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + apps_data[int(row["id"])] = row["app"] + + # This should be changed if running on cluster + conf = SparkConf().setMaster("local[*]").setAppName("AptoideALS") + + sc = SparkContext(conf=conf) + sc.setLogLevel("OFF") + # Load and parse the data + data = sc.textFile(data_source) + ratings = data.map(lambda l: l.split(','))\ + .map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2]))).cache() + + # Build the recommendation model using Alternating Least Squares + seed = 5L + iterations = 10 + # Is a basic L2 Regularizer to reduce overfitting + regularization_parameter = 0.1 + # Number of features used to describe items + rank = 50 + # Is the confidence that we have that the user likes the item + alpha = 100.0 + + model = ALS.trainImplicit(ratings, + rank, + seed=seed, + iterations=iterations, + lambda_=regularization_parameter, + alpha=alpha) + + # Evaluate the model on training data + testdata = ratings.map(lambda p: (p[0], p[1])) + predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2])) + ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions) + MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean() + print("Mean Squared Error = " + str(MSE)) + + users_names = sc.broadcast(users_data) + apps_names = sc.broadcast(apps_data) + + def construct_string(x): + item = "\"{}\"".format(str(apps_names.value[x[0]])) + recs = [("\"{}\"".format(str(users_names.value[y[1]])), y[2]) for y in x[1]] + string = "{},{}".format(item, str(recs)) + return string.replace("[", "").replace("]", "").replace("\\", "").replace("'", "").replace(" ", "") + + recRDD = model.recommendUsersForProducts(int(number_recs)).map(construct_string) + + recRDD.saveAsTextFile(output) + +if __name__ == '__main__': + main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) diff --git a/pool/shard001/Python/0014831_APlainTasksCommon.py b/pool/shard001/Python/0014831_APlainTasksCommon.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7949735d7338feb5325bfe0d46698733873b06 --- /dev/null +++ b/pool/shard001/Python/0014831_APlainTasksCommon.py @@ -0,0 +1,102 @@ +# coding: utf-8 +import sublime, sublime_plugin +import itertools + +ST3 = int(sublime.version()) >= 3000 +if not ST3: + import locale + + +def get_all_projects_and_separators(view): + # because tmLanguage need \n to make background full width of window + # multiline headers are possible, thus we have to split em to be sure that + # one header == one line + projects = itertools.chain(*[view.lines(r) for r in view.find_by_selector('keyword.control.header.todo')]) + return sorted(list(projects) + + view.find_by_selector('meta.punctuation.separator.todo')) + + +class PlainTasksBase(sublime_plugin.TextCommand): + def run(self, edit, **kwargs): + settings = self.view.settings() + + self.taskpaper_compatible = settings.get('taskpaper_compatible', False) + if self.taskpaper_compatible: + self.open_tasks_bullet = self.done_tasks_bullet = self.canc_tasks_bullet = '-' + self.before_date_space = '' + else: + self.open_tasks_bullet = settings.get('open_tasks_bullet', u'☐') + self.done_tasks_bullet = settings.get('done_tasks_bullet', u'✔') + self.canc_tasks_bullet = settings.get('cancelled_tasks_bullet', u'✘') + self.before_date_space = settings.get('before_date_space', ' ') + + translate_tabs_to_spaces = settings.get('translate_tabs_to_spaces', False) + self.before_tasks_bullet_spaces = ' ' * settings.get('before_tasks_bullet_margin', 1) if not self.taskpaper_compatible and translate_tabs_to_spaces else '\t' + self.tasks_bullet_space = settings.get('tasks_bullet_space', ' ' if self.taskpaper_compatible or translate_tabs_to_spaces else '\t') + + self.date_format = settings.get('date_format', '(%y-%m-%d %H:%M)') + if settings.get('done_tag', True) or self.taskpaper_compatible: + self.done_tag = "@done" + self.canc_tag = "@cancelled" + else: + self.done_tag = "" + self.canc_tag = "" + + self.project_postfix = settings.get('project_tag', True) + self.archive_name = settings.get('archive_name', 'Archive:') + # org-mode style archive stuff + self.archive_org_default_filemask = u'{dir}{sep}{base}_archive{ext}' + self.archive_org_filemask = settings.get('archive_org_filemask', self.archive_org_default_filemask) + + if not ST3: + self.sys_enc = locale.getpreferredencoding() + self.runCommand(edit, **kwargs) + + +class PlainTasksEnabled(sublime_plugin.TextCommand): + def is_enabled(self): + return self.view.score_selector(0, "text.todo") > 0 + + is_visible = is_enabled + + +class PlainTasksFold(PlainTasksEnabled): + def exec_folding(self, visible_region): + self.view.unfold(sublime.Region(0, self.view.size())) + for i, d in enumerate(visible_region): + if not i: # beginning of document + self.folding(0, d.a - 1) + else: # all regions within + self.folding(visible_region[i-1].b + 1, d.a - 1) + if d: # ending of document + self.folding(d.b + 1, self.view.size()) + + def folding(self, start, end): + if start < end: + self.view.fold(sublime.Region(start, end)) + + def add_projects_and_notes(self, task_regions): + '''Context is important, if task has note and belongs to projects, make em visible''' + def add_note(region): + # refactor: method in ArchiveCommand + next_line_begins = region.end() + 1 + while self.view.scope_name(next_line_begins) == 'text.todo notes.todo ': + note = self.view.line(next_line_begins) + if note not in task_regions: + task_regions.append(note) + next_line_begins = self.view.line(next_line_begins).end() + 1 + + projects = [r for r in get_all_projects_and_separators(self.view) if r.a < task_regions[~0].a] + for d in reversed(task_regions): + add_note(d) + for p in reversed(projects): + # refactor: different implementation in ArchiveCommand + project_block = self.view.indented_region(p.end() + 1) + due_block = self.view.indented_region(d.begin()) + if all((p not in task_regions, project_block.contains(due_block))): + task_regions.append(p) + add_note(p) + if self.view.indented_region(p.begin()).empty(): + break + task_regions.sort() + return task_regions diff --git a/pool/shard001/Python/0014837_create_fpga.py b/pool/shard001/Python/0014837_create_fpga.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3ebeeb82563199911f80b92678f52255d03307 --- /dev/null +++ b/pool/shard001/Python/0014837_create_fpga.py @@ -0,0 +1,54 @@ +from django.forms import CharField +from django.forms import ModelChoiceField +from django.forms import ModelForm +from django.forms import TextInput + +from rc3e_manager.backend.models import Fpga +from rc3e_manager.backend.models import FpgaModel +from rc3e_manager.backend.models import Node +from rc3e_manager.backend.models import PciAddress + + +def create_pci_field(chars): + """ + A helper method to create the PCI fields in forms + :param chars: The amount of chars expected in the form + :return: A char field object for use in form classes + """ + return CharField( + min_length=chars, + max_length=chars, + widget=TextInput(attrs={'size': chars, }) + ) + + +class CreateFpgaForm(ModelForm): + """ + The CreateFpgaForm class + is a custom form class for adding FPGAs. + It allows for the input of the PCI addresses split into its component parts. + """ + + class Meta: + model = Fpga + fields = ['node', 'fpga_model'] + + node = ModelChoiceField( + queryset=Node.objects.all(), + ) + + fpga_model = ModelChoiceField( + queryset=FpgaModel.objects.all(), + ) + + device_pci_system = create_pci_field(PciAddress.SYSTEM_CHARS) + device_pci_bus = create_pci_field(PciAddress.BUS_CHARS) + device_pci_device = create_pci_field(PciAddress.DEVICE_CHARS) + device_pci_function = create_pci_field(PciAddress.FUNCTION_CHARS) + + node_pci_system = create_pci_field(PciAddress.SYSTEM_CHARS) + node_pci_bus = create_pci_field(PciAddress.BUS_CHARS) + node_pci_device = create_pci_field(PciAddress.DEVICE_CHARS) + node_pci_function = create_pci_field(PciAddress.FUNCTION_CHARS) + + # The actual setting of values will be handled by views.add_fpga diff --git a/pool/shard001/Python/0014839_test_console_auth_token.py b/pool/shard001/Python/0014839_test_console_auth_token.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc33086b0d3dc77106b9506223ceea9db75c0bb --- /dev/null +++ b/pool/shard001/Python/0014839_test_console_auth_token.py @@ -0,0 +1,165 @@ +# Copyright 2016 Intel Corp. +# Copyright 2016 Hewlett Packard Enterprise Development Company LP +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import copy +import mock + +from oslo_db.exception import DBDuplicateEntry +from oslo_utils.fixture import uuidsentinel +from oslo_utils import timeutils + +from nova import exception +from nova.objects import console_auth_token as token_obj +from nova.tests.unit import fake_console_auth_token as fakes +from nova.tests.unit.objects import test_objects + + +class _TestConsoleAuthToken(object): + + @mock.patch('nova.db.api.console_auth_token_create') + def test_authorize(self, mock_create): + # the expires time is calculated from the current time and + # a ttl value in the object. Fix the current time so we can + # test expires is calculated correctly as expected + self.addCleanup(timeutils.clear_time_override) + timeutils.set_time_override() + ttl = 10 + expires = timeutils.utcnow_ts() + ttl + + db_dict = copy.deepcopy(fakes.fake_token_dict) + db_dict['expires'] = expires + mock_create.return_value = db_dict + + create_dict = copy.deepcopy(fakes.fake_token_dict) + create_dict['expires'] = expires + del create_dict['id'] + del create_dict['created_at'] + del create_dict['updated_at'] + + expected = copy.deepcopy(fakes.fake_token_dict) + del expected['token_hash'] + del expected['expires'] + expected['token'] = fakes.fake_token + + obj = token_obj.ConsoleAuthToken( + context=self.context, + console_type=fakes.fake_token_dict['console_type'], + host=fakes.fake_token_dict['host'], + port=fakes.fake_token_dict['port'], + internal_access_path=fakes.fake_token_dict['internal_access_path'], + instance_uuid=fakes.fake_token_dict['instance_uuid'], + access_url_base=fakes.fake_token_dict['access_url_base'], + ) + with mock.patch('uuid.uuid4', return_value=fakes.fake_token): + token = obj.authorize(ttl) + + mock_create.assert_called_once_with(self.context, create_dict) + self.assertEqual(token, fakes.fake_token) + self.compare_obj(obj, expected) + + url = obj.access_url + expected_url = '%s?token=%s' % ( + fakes.fake_token_dict['access_url_base'], + fakes.fake_token) + self.assertEqual(expected_url, url) + + @mock.patch('nova.db.api.console_auth_token_create') + def test_authorize_duplicate_token(self, mock_create): + mock_create.side_effect = DBDuplicateEntry() + + obj = token_obj.ConsoleAuthToken( + context=self.context, + console_type=fakes.fake_token_dict['console_type'], + host=fakes.fake_token_dict['host'], + port=fakes.fake_token_dict['port'], + internal_access_path=fakes.fake_token_dict['internal_access_path'], + instance_uuid=fakes.fake_token_dict['instance_uuid'], + access_url_base=fakes.fake_token_dict['access_url_base'], + ) + + self.assertRaises(exception.TokenInUse, + obj.authorize, + 100) + + @mock.patch('nova.db.api.console_auth_token_create') + def test_authorize_instance_not_found(self, mock_create): + mock_create.side_effect = exception.InstanceNotFound( + instance_id=fakes.fake_token_dict['instance_uuid']) + + obj = token_obj.ConsoleAuthToken( + context=self.context, + console_type=fakes.fake_token_dict['console_type'], + host=fakes.fake_token_dict['host'], + port=fakes.fake_token_dict['port'], + internal_access_path=fakes.fake_token_dict['internal_access_path'], + instance_uuid=fakes.fake_token_dict['instance_uuid'], + access_url_base=fakes.fake_token_dict['access_url_base'], + ) + + self.assertRaises(exception.InstanceNotFound, + obj.authorize, + 100) + + @mock.patch('nova.db.api.console_auth_token_create') + def test_authorize_object_already_created(self, mock_create): + # the expires time is calculated from the current time and + # a ttl value in the object. Fix the current time so we can + # test expires is calculated correctly as expected + self.addCleanup(timeutils.clear_time_override) + timeutils.set_time_override() + ttl = 10 + expires = timeutils.utcnow_ts() + ttl + + db_dict = copy.deepcopy(fakes.fake_token_dict) + db_dict['expires'] = expires + mock_create.return_value = db_dict + + obj = token_obj.ConsoleAuthToken( + context=self.context, + console_type=fakes.fake_token_dict['console_type'], + host=fakes.fake_token_dict['host'], + port=fakes.fake_token_dict['port'], + internal_access_path=fakes.fake_token_dict['internal_access_path'], + instance_uuid=fakes.fake_token_dict['instance_uuid'], + access_url_base=fakes.fake_token_dict['access_url_base'], + ) + obj.authorize(100) + self.assertRaises(exception.ObjectActionError, + obj.authorize, + 100) + + @mock.patch('nova.db.api.console_auth_token_destroy_all_by_instance') + def test_clean_console_auths_for_instance(self, mock_destroy): + token_obj.ConsoleAuthToken.clean_console_auths_for_instance( + self.context, uuidsentinel.instance) + mock_destroy.assert_called_once_with( + self.context, uuidsentinel.instance) + + @mock.patch('nova.db.api.console_auth_token_destroy_expired_by_host') + def test_clean_expired_console_auths_for_host(self, mock_destroy): + token_obj.ConsoleAuthToken.clean_expired_console_auths_for_host( + self.context, 'fake-host') + mock_destroy.assert_called_once_with( + self.context, 'fake-host') + + +class TestConsoleAuthToken(test_objects._LocalTest, + _TestConsoleAuthToken): + pass + + +class TestRemoteConsoleAuthToken(test_objects._RemoteTest, + _TestConsoleAuthToken): + pass diff --git a/pool/shard001/Python/0014840_post_test.py b/pool/shard001/Python/0014840_post_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e30d2412cdbee9661704276c041e70bb62aff6c1 --- /dev/null +++ b/pool/shard001/Python/0014840_post_test.py @@ -0,0 +1,17 @@ +from unittest import TestCase +from post import Post + + +class PostTest(TestCase): + def test_create_post(self): + p = Post('Test', 'Test Content') + + self.assertEqual('Test', p.title) + self.assertEqual('Test Content', p.content) + + def test_json(self): + p = Post('Test', 'Test Content') + expected = {'title': 'Test', 'content': 'Test Content'} + + self.assertDictEqual(expected, p.json()) + diff --git a/pool/shard001/Python/0014843_campaign_customizer.py b/pool/shard001/Python/0014843_campaign_customizer.py new file mode 100644 index 0000000000000000000000000000000000000000..bffeae7e2acac6b7edec860be92f460943669a58 --- /dev/null +++ b/pool/shard001/Python/0014843_campaign_customizer.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# 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 proto # type: ignore + +from google.ads.googleads.v9.common.types import customizer_value +from google.ads.googleads.v9.enums.types import customizer_value_status + + +__protobuf__ = proto.module( + package="google.ads.googleads.v9.resources", + marshal="google.ads.googleads.v9", + manifest={"CampaignCustomizer",}, +) + + +class CampaignCustomizer(proto.Message): + r"""A customizer value for the associated CustomizerAttribute at + the Campaign level. + + Attributes: + resource_name (str): + Immutable. The resource name of the campaign customizer. + Campaign customizer resource names have the form: + + ``customers/{customer_id}/campaignCustomizers/{campaign_id}~{customizer_attribute_id}`` + campaign (str): + Immutable. The campaign to which the + customizer attribute is linked. + customizer_attribute (str): + Required. Immutable. The customizer attribute + which is linked to the campaign. + status (google.ads.googleads.v9.enums.types.CustomizerValueStatusEnum.CustomizerValueStatus): + Output only. The status of the campaign + customizer. + value (google.ads.googleads.v9.common.types.CustomizerValue): + Required. The value to associate with the + customizer attribute at this level. The value + must be of the type specified for the + CustomizerAttribute. + """ + + resource_name = proto.Field(proto.STRING, number=1,) + campaign = proto.Field(proto.STRING, number=2,) + customizer_attribute = proto.Field(proto.STRING, number=3,) + status = proto.Field( + proto.ENUM, + number=4, + enum=customizer_value_status.CustomizerValueStatusEnum.CustomizerValueStatus, + ) + value = proto.Field( + proto.MESSAGE, number=5, message=customizer_value.CustomizerValue, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pool/shard001/Python/0014850_test_management.py b/pool/shard001/Python/0014850_test_management.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa54a8795e757a23a179a03a277c48f9028c93a --- /dev/null +++ b/pool/shard001/Python/0014850_test_management.py @@ -0,0 +1,132 @@ +# Copyright 2015 Cloudbase Solutions Srl +# 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. + +""" +Test class for MSFT OCS ManagementInterface +""" + +import mock + +from ironic.common import boot_devices +from ironic.common import exception +from ironic.conductor import task_manager +from ironic.drivers.modules.msftocs import common as msftocs_common +from ironic.drivers.modules.msftocs import msftocsclient +from ironic.drivers import utils as drivers_utils +from ironic.tests.unit.conductor import mgr_utils +from ironic.tests.unit.db import base as db_base +from ironic.tests.unit.db import utils as db_utils +from ironic.tests.unit.objects import utils as obj_utils + +INFO_DICT = db_utils.get_test_msftocs_info() + + +class MSFTOCSManagementTestCase(db_base.DbTestCase): + def setUp(self): + super(MSFTOCSManagementTestCase, self).setUp() + mgr_utils.mock_the_extension_manager(driver='fake_msftocs') + self.info = INFO_DICT + self.node = obj_utils.create_test_node(self.context, + driver='fake_msftocs', + driver_info=self.info) + + def test_get_properties(self): + expected = msftocs_common.REQUIRED_PROPERTIES + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + self.assertEqual(expected, task.driver.get_properties()) + + @mock.patch.object(msftocs_common, 'parse_driver_info', autospec=True) + def test_validate(self, mock_drvinfo): + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + task.driver.power.validate(task) + mock_drvinfo.assert_called_once_with(task.node) + + @mock.patch.object(msftocs_common, 'parse_driver_info', autospec=True) + def test_validate_fail(self, mock_drvinfo): + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + mock_drvinfo.side_effect = exception.InvalidParameterValue('x') + self.assertRaises(exception.InvalidParameterValue, + task.driver.power.validate, + task) + + def test_get_supported_boot_devices(self): + expected = [boot_devices.PXE, boot_devices.DISK, boot_devices.BIOS] + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + self.assertEqual( + sorted(expected), + sorted(task.driver.management. + get_supported_boot_devices(task))) + + @mock.patch.object(msftocs_common, 'get_client_info', autospec=True) + def _test_set_boot_device_one_time(self, persistent, uefi, + mock_gci): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + mock_c = mock.MagicMock(spec=msftocsclient.MSFTOCSClientApi) + blade_id = task.node.driver_info['msftocs_blade_id'] + mock_gci.return_value = (mock_c, blade_id) + + if uefi: + drivers_utils.add_node_capability(task, 'boot_mode', 'uefi') + + task.driver.management.set_boot_device( + task, boot_devices.PXE, persistent) + + mock_gci.assert_called_once_with(task.node.driver_info) + mock_c.set_next_boot.assert_called_once_with( + blade_id, msftocsclient.BOOT_TYPE_FORCE_PXE, persistent, uefi) + + def test_set_boot_device_one_time(self): + self._test_set_boot_device_one_time(False, False) + + def test_set_boot_device_persistent(self): + self._test_set_boot_device_one_time(True, False) + + def test_set_boot_device_uefi(self): + self._test_set_boot_device_one_time(True, True) + + def test_set_boot_device_fail(self): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + self.assertRaises(exception.InvalidParameterValue, + task.driver.management.set_boot_device, + task, 'fake-device') + + @mock.patch.object(msftocs_common, 'get_client_info', autospec=True) + def test_get_boot_device(self, mock_gci): + expected = {'boot_device': boot_devices.DISK, 'persistent': None} + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + mock_c = mock.MagicMock(spec=msftocsclient.MSFTOCSClientApi) + blade_id = task.node.driver_info['msftocs_blade_id'] + mock_gci.return_value = (mock_c, blade_id) + force_hdd = msftocsclient.BOOT_TYPE_FORCE_DEFAULT_HDD + mock_c.get_next_boot.return_value = force_hdd + + self.assertEqual(expected, + task.driver.management.get_boot_device(task)) + mock_gci.assert_called_once_with(task.node.driver_info) + mock_c.get_next_boot.assert_called_once_with(blade_id) + + def test_get_sensor_data(self): + with task_manager.acquire(self.context, self.node.uuid, + shared=True) as task: + self.assertRaises(NotImplementedError, + task.driver.management.get_sensors_data, + task) diff --git a/pool/shard001/Python/0014851_model.py b/pool/shard001/Python/0014851_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c71537c4f6a6c98a8319fc441b234d393cb2aceb --- /dev/null +++ b/pool/shard001/Python/0014851_model.py @@ -0,0 +1,70 @@ +# -*- coding: UTF-8 -*- +"""Class definitions of media resources shared across all the modules within PyLSI. + +.. moduleauthor:: Dong Liu +""" +import json +from datetime import datetime + + +class MediaResource(object): + def __init__(self): + self.id = None + self.title = None + self.description = None + self.locator = None + self.keywords = [] + self.source = None + self.query_lod = None + self.query_context = None + self.created = None + self.author_name = None + self.author_uri = None + self.width = None + self.height = None + self.latitude = None + self.longitude = None + self.location_name = None + self.published = None + # 'crawled', 'enriched' + self.status = 'crawled' + + +class VideoTrack(MediaResource): + def __init__(self): + super(VideoTrack, self).__init__() + self.type = 'video' + self.thumbnail = None + self.duration = None + + +class Image(MediaResource): + def __init__(self): + super(Image, self).__init__() + self.type = 'image' + + +class VideoEncoder(json.JSONEncoder): + """The JSON encoder for video tracks.""" + def default(self, obj): + if isinstance(obj, VideoTrack): + prop_dict = obj.__dict__.copy() + del prop_dict['id'] + return prop_dict + elif isinstance(obj, datetime): + return obj.strftime('%Y-%m-%dT%H:%M:%S.000Z') + else: + return json.JSONEncoder.default(self, obj) + + +class ImageEncoder(json.JSONEncoder): + """The JSON encoder for images.""" + def default(self, obj): + if isinstance(obj, Image): + prop_dict = obj.__dict__.copy() + del prop_dict['id'] + return prop_dict + elif isinstance(obj, datetime): + return obj.strftime('%Y-%m-%dT%H:%M:%S.000Z') + else: + return json.JSONEncoder.default(self, obj) diff --git a/pool/shard001/Python/0014855_rewrite-to-add-election-to-memberships-in-test-data.py b/pool/shard001/Python/0014855_rewrite-to-add-election-to-memberships-in-test-data.py new file mode 100644 index 0000000000000000000000000000000000000000..444437934140b47f10fe95535845e43ff812a0c4 --- /dev/null +++ b/pool/shard001/Python/0014855_rewrite-to-add-election-to-memberships-in-test-data.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +from __future__ import unicode_literals + +import json +import os +import re +from os.path import dirname, join +from tempfile import NamedTemporaryFile + +# We're switching to storing an 'election' attribute on each candidate +# membership that would be associated with a 'standing_in' value, but +# the old test data doesn't have such attributes. This script will +# rewrite all the test data to include these values. + +# The test data is all for the 2015 UK general election at the time of +# writing, so this just hardcodes the conditions for the '2010' and +# '2015' elections. + +# The original data wasn't necessarily indented consistently or had +# dictionary entries sorted by key, so this also fixes that in the +# test data. + +test_data_dir = join(dirname(__file__), '..', 'candidates', 'example-popit-data') + +def find_memberships_lists(data): + membership_lists = [] + if isinstance(data, list): + for item in data: + membership_lists += find_memberships_lists(item) + elif isinstance(data, dict): + if 'memberships' in data: + membership_lists.append(data['memberships']) + for item in data.values(): + membership_lists += find_memberships_lists(item) + return membership_lists + +def update_memberships_list(memberships): + for m in memberships: + if m.get('role', '') == 'Candidate': + start_date = m['start_date'] + end_date = m['end_date'] + if start_date == '2005-05-06' and end_date == '2010-05-06': + m['election'] = '2010' + elif start_date == '2010-05-07' and end_date == '9999-12-31': + m['election'] = '2015' + else: + message = "Error: Couldn't find election for {0}" + raise Exception(message.format( + json.dumps(m, indent=4, sort_keys=True) + )) + +def rewrite_json_file(json_filename): + with open(json_filename) as f: + data = json.load(f) + for membership_list in find_memberships_lists(data): + update_memberships_list(membership_list) + data_str = json.dumps(data, indent=2, sort_keys=True) + # The json library outputs with trailing whitespace in some versions + # strip that before writing out the file again: + data_str = re.sub(r'(?ms)\s+$', '', data_str) + with NamedTemporaryFile('w', dir=test_data_dir, delete=False) as ntf: + ntf.write(data_str) + os.rename(ntf.name, json_filename) + +for leafname in os.listdir(test_data_dir): + if not leafname.endswith('.json'): + continue + rewrite_json_file(join(test_data_dir, leafname)) diff --git a/pool/shard001/Python/0014857_test_find_deptid.py b/pool/shard001/Python/0014857_test_find_deptid.py new file mode 100644 index 0000000000000000000000000000000000000000..98e24824dba9094c8d99f8c0e8cb1658d8253da7 --- /dev/null +++ b/pool/shard001/Python/0014857_test_find_deptid.py @@ -0,0 +1,38 @@ +""" + test_find_deptid.py -- from a deptid dictionary, find deptids and return + their URIs. + + Version 0.1 MC 2013-12-28 + -- Initial version. Make a dictionary and make a dictionary with + debug=True +""" + +__author__ = "Michael Conlon" +__copyright__ = "Copyright 2013, University of Florida" +__license__ = "BSD 3-Clause license" +__version__ = "0.1" + +import vivotools as vt +from datetime import datetime + +print datetime.now(),"Start" +print datetime.now(),"Making deptid dictionary" +deptid_dictionary = vt.make_deptid_dictionary(debug=True) +print datetime.now(),"deptid dictionary has ",len(deptid_dictionary),"entries" +deptids = [ + "02001000", + "57000000", + "29680000", + "33100000", + "16010000", + "16020000", + "60100000", + "18300000", + "27000000", + "11040000" + ] +for deptid in deptids: + [found,uri] = vt.find_deptid(deptid,deptid_dictionary) + print str(found).ljust(5),deptid,uri + +print datetime.now(),"Finished" diff --git a/pool/shard001/Python/0014862_FunctionMetadata.py b/pool/shard001/Python/0014862_FunctionMetadata.py new file mode 100644 index 0000000000000000000000000000000000000000..3171e49ccbece574c4b17f216c004b3b7aaf7255 --- /dev/null +++ b/pool/shard001/Python/0014862_FunctionMetadata.py @@ -0,0 +1,164 @@ +from inspect import ismethod, getfullargspec +from collections import OrderedDict +from copy import copy + +from coalib.settings.DocumentationComment import DocumentationComment + + +class FunctionMetadata: + str_nodesc = "No description given." + str_optional = "Optional, defaults to '{}'." + + def __init__(self, + name, + desc="", + retval_desc="", + non_optional_params=None, + optional_params=None, + omit=frozenset()): + """ + Creates the FunctionMetadata object. + + :param name: The name of the function. + :param desc: The description of the function. + :param retval_desc: The retval description of the function. + :param non_optional_params: A dict containing the name of non optional + parameters as the key and a tuple of a + description and the python annotation. To + preserve the order, use OrderedDict. + :param optional_params: A dict containing the name of optional + parameters as the key and a tuple + of a description, the python annotation and + the default value. To preserve the order, + use OrderedDict. + :param omit: A set of parameters to omit. + """ + if non_optional_params is None: + non_optional_params = OrderedDict() + if optional_params is None: + optional_params = OrderedDict() + + self.name = name + self.desc = desc + self.retval_desc = retval_desc + self._non_optional_params = non_optional_params + self._optional_params = optional_params + self.omit = set(omit) + + def _filter_out_omitted(self, params): + """ + Filters out parameters that are to omit. This is a helper method for + the param related properties. + + :param params: The parameter dictionary to filter. + :return: The filtered dictionary. + """ + return OrderedDict(filter(lambda p: p[0] not in self.omit, + tuple(params.items()))) + + @property + def non_optional_params(self): + """ + Retrieves a dict containing the name of non optional parameters as the + key and a tuple of a description and the python annotation. Values that + are present in self.omit will be omitted. + """ + return self._filter_out_omitted(self._non_optional_params) + + @property + def optional_params(self): + """ + Retrieves a dict containing the name of optional parameters as the key + and a tuple of a description, the python annotation and the default + value. Values that are present in self.omit will be omitted. + """ + return self._filter_out_omitted(self._optional_params) + + def create_params_from_section(self, section): + """ + Create a params dictionary for this function that holds all values the + function needs plus optional ones that are available. + + :param section: The section to retrieve the values from. + :return: The params dictionary. + """ + params = {} + + for param in self.non_optional_params: + dummy, annotation = self.non_optional_params[param] + params[param] = self._get_param(param, section, annotation) + + for param in self.optional_params: + if param in section: + dummy, annotation, dummy = self.optional_params[param] + params[param] = self._get_param(param, section, annotation) + + return params + + @staticmethod + def _get_param(param, section, annotation): + if annotation is None: + annotation = lambda x: x + + try: + return annotation(section[param]) + except: + raise ValueError("Unable to convert parameter {} into type " + "{}.".format(repr(param), annotation)) + + @classmethod + def from_function(cls, func, omit=frozenset()): + """ + Creates a FunctionMetadata object from a function. Please note that any + variable argument lists are not supported. If you do not want the + first (usual named 'self') argument to appear please pass the method of + an actual INSTANCE of a class; passing the method of the class isn't + enough. Alternatively you can add "self" to the omit set. + + :param func: The function. If __metadata__ of the unbound function is + present it will be copied and used, otherwise it will be + generated. + :param omit: A set of parameter names that are to be ignored. + :return: The FunctionMetadata object corresponding to the given + function. + """ + if hasattr(func, "__metadata__"): + metadata = copy(func.__metadata__) + metadata.omit = omit + return metadata + + doc = func.__doc__ + if doc is None: + doc = "" + doc_comment = DocumentationComment.from_docstring(doc) + + non_optional_params = OrderedDict() + optional_params = OrderedDict() + + argspec = getfullargspec(func) + args = argspec.args if argspec.args is not None else () + defaults = argspec.defaults if argspec.defaults is not None else () + num_non_defaults = len(args) - len(defaults) + for i, arg in enumerate(args): + # Implicit self argument or omitted explicitly + if i < 1 and ismethod(func): + continue + + if i < num_non_defaults: + non_optional_params[arg] = ( + doc_comment.param_dict.get(arg, cls.str_nodesc), + argspec.annotations.get(arg, None)) + else: + optional_params[arg] = ( + doc_comment.param_dict.get(arg, cls.str_nodesc) + " (" + + cls.str_optional.format(str(defaults[i-num_non_defaults])) + + ")", + argspec.annotations.get(arg, None), + defaults[i-num_non_defaults]) + + return cls(name=func.__name__, + desc=doc_comment.desc, + retval_desc=doc_comment.retval_desc, + non_optional_params=non_optional_params, + optional_params=optional_params, + omit=omit) diff --git a/pool/shard001/Python/0014867_init__.py b/pool/shard001/Python/0014867_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac494b54ff9d7579bb48dbddde5913b56a4299fa --- /dev/null +++ b/pool/shard001/Python/0014867_init__.py @@ -0,0 +1,91 @@ + +from __future__ import print_function, absolute_import +import os, pydoc, io + +import numpy as np # noqa (API import) +import param + + +__version__ = str(param.version.Version(fpath=__file__, archive_commit="$Format:%h$", + reponame="holoviews")) + +from . import util # noqa (API import) +from .core import archive, config # noqa (API import) +from .core.boundingregion import BoundingBox # noqa (API import) +from .core.dimension import OrderedDict, Dimension # noqa (API import) +from .core.element import Element, Collator # noqa (API import) +from .core.layout import (Layout, NdLayout, Empty, # noqa (API import) + AdjointLayout) +from .core.ndmapping import NdMapping # noqa (API import) +from .core.options import (Options, Store, Cycle, # noqa (API import) + Palette, StoreOptions) +from .core.overlay import Overlay, NdOverlay # noqa (API import) +from .core.spaces import (HoloMap, Callable, DynamicMap, # noqa (API import) + GridSpace, GridMatrix) + +from .operation import Operation # noqa (API import) +from .element import * # noqa (API import) +from .element import __all__ as elements_list +from .util import (extension, renderer, output, opts, # noqa (API import) + render, save) +from .util.transform import dim # noqa (API import) + +# Suppress warnings generated by NumPy in matplotlib +# Expected to be fixed in next matplotlib release +import warnings +warnings.filterwarnings("ignore", + message="elementwise comparison failed; returning scalar instead") + +try: + import IPython # noqa (API import) + from .ipython import notebook_extension + extension = notebook_extension # noqa (name remapping) +except ImportError: + class notebook_extension(param.ParameterizedFunction): + def __call__(self, *args, **opts): # noqa (dummy signature) + raise Exception("IPython notebook not available: use hv.extension instead.") + +# A single holoviews.rc file may be executed if found. +for rcfile in [os.environ.get("HOLOVIEWSRC", ''), + os.path.abspath(os.path.join(os.path.split(__file__)[0], + '..', 'holoviews.rc')), + "~/.holoviews.rc", + "~/.config/holoviews/holoviews.rc"]: + filename = os.path.expanduser(rcfile) + if os.path.isfile(filename): + with io.open(filename, encoding='utf8') as f: + code = compile(f.read(), filename, 'exec') + try: + exec(code) + except Exception as e: + print("Warning: Could not load %r [%r]" % (filename, str(e))) + del f, code + break + del filename + +def help(obj, visualization=True, ansi=True, backend=None, + recursive=False, pattern=None): + """ + Extended version of the built-in help that supports parameterized + functions and objects. A pattern (regular expression) may be used to + filter the output and if recursive is set to True, documentation for + the supplied object is shown. Note that the recursive option will + only work with an object instance and not a class. + + If ansi is set to False, all ANSI color + codes are stripped out. + """ + backend = backend if backend else Store.current_backend + info = Store.info(obj, ansi=ansi, backend=backend, visualization=visualization, + recursive=recursive, pattern=pattern, elements=elements_list) + + msg = ("\nTo view the visualization options applicable to this " + "object or class, use:\n\n" + " holoviews.help(obj, visualization=True)\n\n") + if info: + print((msg if visualization is False else '') + info) + else: + pydoc.help(obj) + + +del absolute_import, io, np, os, print_function, pydoc, rcfile, warnings diff --git a/pool/shard001/Python/0014870_MorseWAV.py b/pool/shard001/Python/0014870_MorseWAV.py new file mode 100644 index 0000000000000000000000000000000000000000..d285b1028fa385d0b4cb1752ca18fe30a8b9e941 --- /dev/null +++ b/pool/shard001/Python/0014870_MorseWAV.py @@ -0,0 +1,62 @@ +import wave +import struct +import math + +def morse_conversion(message): + code = '' + units = 0 + for letter in message.upper(): + code += morse[letter] + '|' + return code.replace('|/|', '/') + +def wav(code): + frequency = 440 #Hz + framerate = 10000.00 #Hz + amp=8000.0 # amplitude + time_per_unit = 0.125 #seconds + + unit=[] + for x in range(int(math.ceil(time_per_unit * framerate))): #one full unit consists of time_per_unit*framerate frames + unit.append(math.sin(2*math.pi * frequency * ( x/framerate))) + empty = [0]*int(time_per_unit * framerate) + + file_list = [] + for char in code: + if char == '.': + for s in unit: + file_list.append(struct.pack('h', int(s*amp/2))) + elif char == '-': + for s in unit*3: + file_list.append(struct.pack('h', int(s*amp/2))) + elif char == '|': + for s in empty: + file_list.append(struct.pack('h', int(s*amp/2))) + elif char == '/': + for s in empty*5: #5, not 7, since I'm adding an empty before and after + file_list.append(struct.pack('h', int(s*amp/2))) + for s in empty: + file_list.append(struct.pack('h', int(s*amp/2))) + + wav_file=wave.open('morse.wav','w') + wav_file.setparams((1, 2, int(framerate), len(file_list), 'NONE', 'not compressed')) + print "Writing sines to file..." + i = 0 + for s in file_list: + i+=1 + if i % (len(file_list)/4)==0: + print int(math.ceil((1.0*i/len(file_list))*100)), '%' + wav_file.writeframes(s) + wav_file.close() + + +morse = { + 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', + 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', + 'S': '...', 'T': '-', 'U': '..--', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', + '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '......', '6': '-....', '7': '--...', + '8': '---..', '9': '----.', ' ': '/' +} + +message = raw_input('Enter a message: ') +print morse_conversion(message) +wav(morse_conversion(message)) \ No newline at end of file diff --git a/pool/shard001/Python/0014871_insert_data.py b/pool/shard001/Python/0014871_insert_data.py new file mode 100644 index 0000000000000000000000000000000000000000..082a3bdc81bde132ec34076d50d50e70bcfaabc5 --- /dev/null +++ b/pool/shard001/Python/0014871_insert_data.py @@ -0,0 +1,15 @@ +from ehp import * + +data = ''' ''' +html = Html() +dom = html.feed(data) + +font = Tag('font', {'color':'red'}) +font.append(Data('Data inserted!')) + +for ind in dom.find('em'): + ind.append(font) + +print(dom) + + diff --git a/pool/shard001/Python/0014876_choseninlineresulthandler.py b/pool/shard001/Python/0014876_choseninlineresulthandler.py new file mode 100644 index 0000000000000000000000000000000000000000..b5868572eb1880e600bfc52681ac022b0b02c753 --- /dev/null +++ b/pool/shard001/Python/0014876_choseninlineresulthandler.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# A library that provides a Python interface to the Telegram Bot API +# Copyright (C) 2015-2016 +# Leandro Toledo de Souza +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser Public License for more details. +# +# You should have received a copy of the GNU Lesser Public License +# along with this program. If not, see [http://www.gnu.org/licenses/]. +""" This module contains the ChosenInlineResultHandler class """ + +from .handler import Handler +from telegram import Update +from telegram.utils.deprecate import deprecate + + +class ChosenInlineResultHandler(Handler): + """ + Handler class to handle Telegram updates that contain a chosen inline + result. + + Args: + callback (function): A function that takes ``bot, update`` as + positional arguments. It will be called when the ``check_update`` + has determined that an update should be processed by this handler. + pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called + ``update_queue`` will be passed to the callback function. It will be the ``Queue`` + instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can + be used to insert updates. Default is ``False``. + pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called + ``job_queue`` will be passed to the callback function. It will be a ``JobQueue`` + instance created by the ``Updater`` which can be used to schedule new jobs. + Default is ``False``. + """ + + def __init__(self, callback, pass_update_queue=False, pass_job_queue=False): + super(ChosenInlineResultHandler, self).__init__(callback, + pass_update_queue=pass_update_queue, + pass_job_queue=pass_job_queue) + + def check_update(self, update): + return isinstance(update, Update) and update.chosen_inline_result + + def handle_update(self, update, dispatcher): + optional_args = self.collect_optional_args(dispatcher) + + return self.callback(dispatcher.bot, update, **optional_args) + + # old non-PEP8 Handler methods + m = "telegram.ChosenInlineResultHandler." + checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") + handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") diff --git a/pool/shard001/Python/0014878_urls.py b/pool/shard001/Python/0014878_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9606ca06bca4b80fc1c0ddab267c570d412b27 --- /dev/null +++ b/pool/shard001/Python/0014878_urls.py @@ -0,0 +1,65 @@ +from __future__ import absolute_import +from __future__ import unicode_literals +# from django.conf import settings +from django.conf.urls import url, include +# from django.conf.urls import * # * needed for 404 handler +# from django.views.generic import create_update #, list_detail +# from django.contrib import admin +import dorsale.views as dv + + +def makepatterns(mymodule, mymodels, urlpatterns=None): + if not urlpatterns: + urlpatterns = [] + + for mymodel in mymodels: + name = mymodel.__name__.lower() +# eco = { +# 'object_example': mymodel(), +# } +# if hasattr(mymodel, 'site'): +# from django.contrib.sites.models import Site +# eco['site'] = Site.objects.get_current + urlpatterns.append(url( + r'^' + name + r'/$', + dv.list_items, + {'app_name': mymodule, 'model_name': name}, + name='%s-%s-list' % (mymodule, name))) + urlpatterns.append(url( + r'^' + name + r'/(?P\d+)/$', + dv.show_item, + {'app_name': mymodule, 'model_name': name}, + name='%s-%s-display' % (mymodule, name))) + urlpatterns.append(url( + r'^' + name + r'/(?P\d+)/edit/$', + dv.edit_item, + {'app_name': mymodule, 'model_name': name}, + name='%s-%s-edit' % (mymodule, name))) + urlpatterns.append(url( + r'^' + name + r'/(?P\d+)/delete/$', + dv.delete_item, + {'app_name': mymodule, 'model_name': name}, + name='%s-%s-delete' % (mymodule, name))) + urlpatterns.append(url( + r'^' + name + '/new/$', + dv.new_item, + {'app_name': mymodule, 'model_name': name}, + name='%s-%s-new' % (mymodule, name))) +# urlpatterns.append(url(r'^'+name+r'/$', list_detail.object_list, { +# 'queryset': mymodel.objects.all(), +# 'template_name': 'list_items.html', +# 'paginate_by': int(getattr(mymodel, 'items_per_page', getattr(settings, 'ITEMS_PER_PAGE', 10))), +# 'extra_context': eco, +# }, name='%s-%s-list' % (mymodule, name))) +# urlpatterns.append(url(r'^'+name+r'/(?P\d+)/$', list_detail.object_detail, { +# 'queryset': mymodel.objects.all(), +# 'template_name': 'show_item.html', +# 'extra_context': eco, +# }, name='%s-%s-display' % (mymodule, name))) +# urlpatterns.append(url(r'^'+name+r'/(?P\d+)/edit/$', create_update.update_object, { +# 'model': mymodel, +# 'template_name': 'edit_item.html', +# 'extra_context': eco, +# }, name='%s-%s-edit' % (mymodule, name))) + + return urlpatterns diff --git a/pool/shard001/Python/0014880_incrementVersionName.py b/pool/shard001/Python/0014880_incrementVersionName.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c680716ad524c145541f0d18bbaacc738ab8e --- /dev/null +++ b/pool/shard001/Python/0014880_incrementVersionName.py @@ -0,0 +1,60 @@ +import fileinput +import sys +import os + +#input validation +if not sys.argv[2]: + print("Error: no position argument given", file = sys.stderr ) + +print("file is: " + sys.argv[1]) +print("position argument is: " + sys.argv[2]) + + +position = sys.argv[2] + +INCREMENT = 0 +OVERRIDE = 1 + + + +if position in ["M","m","p"]: + print(f"increment ({position})") + operation = INCREMENT +else: + print(f"override old version with ({position})") + operation = OVERRIDE + + +def increment(versionName, severity): + (major, minor, patch) = versionName.split('.') + if severity == 'M': + major = str(int(major) + 1) + minor = "0" + patch = "0" + elif position == 'm': + minor = str(int(minor) + 1) + patch = "0" + else: + patch = str(int(patch) + 1) + + versionNameIncremented = '.'.join((major, minor, patch)) + os.environ['NEW_VERSION_NAME'] = versionNameIncremented + return versionNameIncremented + + +for line in fileinput.input(files=(sys.argv[1]), inplace=True): + if line.find("android:versionName=") >= 0: + versionName = line.split('"')[1] + + if operation == INCREMENT: + newVersionName = increment(versionName, position) + else: + os.environ['NEW_VERSION_NAME'] = position + newVersionName = position + + line = line.replace(versionName, newVersionName) + print(line, end='') + +#save to file so we can use it later +with open("new_version_name.txt", "w") as f: + f.write(newVersionName) diff --git a/pool/shard001/Python/0014881_glove_index.py b/pool/shard001/Python/0014881_glove_index.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bc3473dbe9a6947a051d54af9b02c9f32ea845 --- /dev/null +++ b/pool/shard001/Python/0014881_glove_index.py @@ -0,0 +1,41 @@ +from indexing.abstract_index import AbstractIndex +import numpy as np + + +class GloveIndex(AbstractIndex): + + vectors = None + + def __init__(self, dimension): + self.dimension = dimension + AbstractIndex.__init__(self, None, dimension) + + self.vocab_size = self.get_vocab_size() + self.load_file() + + def retrieve_vector(self, index): + return self.get_all_vectors()[index] + + def get_all_vectors(self): + return self.vectors + + def get_file_string(self): + return "data/glove.6B/glove.6B." + str(self.dimension) + "d.txt" + + def get_vocab_size(self): + return sum(1 for _ in open(self.get_file_string(), encoding="utf8")) + + def load_file(self): + file_string = self.get_file_string() + counter = 0 + + self.vectors = np.empty((self.vocab_size+1, self.dimension), dtype=np.float32) + self.vectors[0] = 0 + + for line in open(file_string, encoding="utf8"): + counter += 1 + parts = line.strip().split(" ") + self.index(parts[0]) + self.vectors[counter] = parts[1:] + + self.freeze() \ No newline at end of file diff --git a/pool/shard001/Python/0014883_clean.py b/pool/shard001/Python/0014883_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..762c94067baa2ffacdef84ed6d6484f4980d826d --- /dev/null +++ b/pool/shard001/Python/0014883_clean.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- + +""" +file: clean.py + +Description: remove unwanted fields from a CoNLL-formatted input. + +author: Yoann Dupont + +MIT License + +Copyright (c) 2018 Yoann Dupont + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +import logging, codecs + +# measuring time laps +import time +from datetime import timedelta + +from .sem_module import SEMModule as RootModule + +from sem.misc import ranges_to_set, is_string +from sem.logger import default_handler, file_handler + +clean_info_logger = logging.getLogger("sem.clean_info") +clean_info_logger.addHandler(default_handler) + +class SEMModule(RootModule): + def __init__(self, to_keep, log_level="WARNING", log_file=None, **kwargs): + super(SEMModule, self).__init__(log_level=log_level, log_file=log_file, **kwargs) + + if is_string(to_keep): + self._allowed = to_keep.split(u",") # comma-separated named fields + else: + self._allowed = to_keep + + if len(self._allowed) == 0: + raise ValueError("No more data after cleaning !") + + def process_document(self, document, **kwargs): + """ + Cleans the sem.storage.corpus of a document, removing unwanted fields. + + Parameters + ---------- + document : sem.storage.Document + the document containing the corpus to clean. + ranges : str or list of int or list of str + if str: fields to remove will be induced + if list of int: each element in the list is the index of a field + to remove in corpus.fields + if list of string: the list of fields to remove + """ + + start = time.time() + + if self._log_file is not None: + clean_info_logger.addHandler(file_handler(self._log_file)) + clean_info_logger.setLevel(self._log_level) + + clean_info_logger.info(u'cleaning document') + + allowed = set(self._allowed) + fields = set(field for field in document.corpus.fields) + to_remove = fields - allowed + document.corpus.fields = self._allowed[:] + + if len(allowed - fields) > 0: + clean_info_logger.warn(u"the following fields are not present in document, this might cause an error sometime later: %s", u", ".join(allowed - fields)) + + indices = [entry.index for entry in document.corpus.fields] + for i in range(len(document.corpus.sentences)): + for j in range(len(document.corpus.sentences[i])): + document.corpus.sentences[i][j] = dict((a,document.corpus.sentences[i][j][a]) for a in allowed) + + laps = time.time() - start + clean_info_logger.info(u'done in {0}'.format(timedelta(seconds=laps))) + +def main(args): + """ + Cleans a CoNLL-formatted file, removing fields at given indices. + + Parameters + ---------- + args.infile : str + the name of the file to clean. + args.outfile : str + the name of the output file, where some columns have been removed. + args.ranges : str + the fields to remove. Fields is a coma-separated list of indices + or ranges of indices using a python format (ie: "lo:hi"). + """ + + if args.log_file is not None: + clean_info_logger.addHandler(file_handler(args.log_file)) + clean_info_logger.setLevel(args.log_level) + + ienc = args.ienc or args.enc + oenc = args.oenc or args.enc + + allowed = ranges_to_set(args.ranges, len(codecs.open(args.infile, "rU", ienc).readline().strip().split()), include_zero=True) + max_abs = 0 + for element in allowed: + element = abs(element) + (1 if element > 0 else 0) + max_abs = max(max_abs, element) + nelts = len(codecs.open(args.infile, "rU", ienc).readline().strip().split()) + + if nelts < max_abs: + clean_info_logger.error(u'asked to keep up to {0} field(s), yet only {1} are present in the "{2}"'.format(max_abs, nelts, args.infile)) + raise runtimeError(u'asked to keep up to {0} field(s), yet only {1} are present in the "{2}"'.format(max_abs, nelts, args.infile)) + + clean_info_logger.info(u'cleaning "{0}"'.format(args.infile)) + clean_info_logger.info(u'keeping columns: {0}'.format(u", ".join([str(s) for s in sorted(allowed)]))) + clean_info_logger.info(u'writing "{0}"'.format(args.outfile)) + + with codecs.open(args.outfile, "w", oenc) as O: + for line in codecs.open(args.infile, "rU", ienc): + line = line.strip().split() + if line != []: + tokens = [line[i] for i in range(len(line)) if i in allowed] + O.write(u"\t".join(tokens)) + O.write(u"\n") + + clean_info_logger.info(u'done') + + +import os.path +import sem + +_subparsers = sem.argument_subparsers + +parser = _subparsers.add_parser(os.path.splitext(os.path.basename(__file__))[0], description="Remove unwanted columns from CoNLL-formatted file.") + +parser.add_argument("infile", + help="The input file") +parser.add_argument("outfile", + help="The output file ") +parser.add_argument("ranges", + help="The ranges of indexes to keep in the file.") +parser.add_argument("--input-encoding", dest="ienc", + help="Encoding of the input (default: UTF-8)") +parser.add_argument("--output-encoding", dest="oenc", + help="Encoding of the input (default: UTF-8)") +parser.add_argument("--encoding", dest="enc", default="UTF-8", + help="Encoding of both the input and the output (default: UTF-8)") +parser.add_argument("-l", "--log", dest="log_level", choices=("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"), default="WARNING", + help="Increase log level (default: critical)") +parser.add_argument("--log-file", dest="log_file", + help="The name of the log file") diff --git a/pool/shard001/Python/0014884_closest_point_on_mesh.py b/pool/shard001/Python/0014884_closest_point_on_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..e94f07a653238f31c5dd4763c51642d2767725b2 --- /dev/null +++ b/pool/shard001/Python/0014884_closest_point_on_mesh.py @@ -0,0 +1,84 @@ +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +import bpy +import mathutils +from mathutils import Vector +from bpy.props import FloatProperty, BoolProperty +from sverchok.node_tree import SverchCustomTreeNode +from sverchok.data_structure import (updateNode, second_as_first_cycle) + + +class SvPointOnMeshNode(bpy.types.Node, SverchCustomTreeNode): + ''' Point on Mesh ''' + bl_idname = 'SvPointOnMeshNode' + bl_label = 'Object ID Point on Mesh' + bl_icon = 'OUTLINER_OB_EMPTY' + + Mdist = FloatProperty(name='Max_Distance', default=10, update=updateNode) + mode = BoolProperty(name='for in points', default=False, update=updateNode) + mode2 = BoolProperty(name='for out points', default=True, update=updateNode) + + def sv_init(self, context): + si,so = self.inputs.new,self.outputs.new + si('StringsSocket', 'Objects') + si('VerticesSocket', "point").use_prop = True + si('StringsSocket', "max_dist").prop_name = "Mdist" + so('VerticesSocket', "Point_on_mesh") + so('VerticesSocket', "Normal_on_mesh") + so('StringsSocket', "FaceINDEX") + + def draw_buttons_ext(self, context, layout): + row = layout.row(align=True) + row.prop(self, "mode", text="In Mode") + row.prop(self, "mode2", text="Out Mode") + + def process(self): + o,p,md = self.inputs + P,N,I = self.outputs + Out,point,sm1,sm2 = [],p.sv_get()[0],self.mode,self.mode2 + obj = o.sv_get() + max_dist = second_as_first_cycle(obj, md.sv_get()[0]) + for i,i2 in zip(obj,max_dist): + if sm1: + Out.append([i.closest_point_on_mesh(i.matrix_local.inverted()*Vector(p), i2) for p in point]) + else: + Out.append([i.closest_point_on_mesh(p, i2) for p in point]) + if P.is_linked: + if sm2: + out =[] + for i,i2 in zip(obj,Out): + out.append([(i.matrix_world*i3[0])[:] for i3 in i2]) + P.sv_set(out) + else: + P.sv_set([[i2[0][:] for i2 in o] for o in Out]) + if N.is_linked: + N.sv_set([[i2[1][:] for i2 in o] for o in Out]) + if I.is_linked: + I.sv_set([[i2[2] for i2 in o] for o in Out]) + + def update_socket(self, context): + self.update() + + +def register(): + bpy.utils.register_class(SvPointOnMeshNode) + + +def unregister(): + bpy.utils.unregister_class(SvPointOnMeshNode) diff --git a/pool/shard001/Python/0014886_camshift.py b/pool/shard001/Python/0014886_camshift.py new file mode 100644 index 0000000000000000000000000000000000000000..d55c1ac76c647b95ccea2a0f1ca817dc32e72246 --- /dev/null +++ b/pool/shard001/Python/0014886_camshift.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python + +''' +Camshift tracker +================ + +This is a demo that shows mean-shift based tracking +You select a color objects such as your face and it tracks it. +This reads from video camera (0 by default, or the camera number the user enters) + +http://www.robinhewitt.com/research/track/camshift.html + +Usage: +------ + camshift.py [