prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# 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 tuskar.templates import namespace class NamespaceTests(unittest.TestCase): def test_apply_template_namespace(self): namespaced = namespace.apply_template_namespace('test-ns', 'test-name') self.assertEqual(namespaced, 'test-ns::test-name') self.assertTrue(namespace.matches_template_namespace('test-ns', namespaced)) def test_remove_template_namespace(self): stripped = namespace.remove_template_namespace('test-ns::test-name') self.assertEqual(stripped, 'test-name') def test_matches_template_namespace(self): value = 'test-ns::test-name' self.assertTrue(namespace.matches_template_namespace('test-ns', value)) self.assertFalse(namespace
.matches_template_namespace('fake', value)) def test_apply_resource_a
lias_namespace(self): namespaced = namespace.apply_resource_alias_namespace('compute') self.assertEqual(namespaced, 'Tuskar::compute') def test_remove_resource_alias_namespace(self): stripped = namespace.remove_resource_alias_namespace( 'Tuskar::controller') self.assertEqual(stripped, 'controller')
ent = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) self.instance_service.get_instance_from_instance_id = Mock(return_value=None) result = self.instance_service.attach_nic_to_net(openstack_session=self.openstack_session, net_id='test_net_id', instance_id='test_instance_id',
logger=self.mock_logger) self.assertEqual(result, None) def test_attach_nic_to_net_failure_exception(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) mock_instance = Mock() mock_instance.interfa
ce_attach = Mock(side_effect=Exception) with self.assertRaises(Exception) as context: result = self.instance_service.attach_nic_to_net(openstack_session=self.openstack_session, net_id='test_net_id', instance_id='test_instance_id', logger=self.mock_logger) self.assertTrue(context) def test_detach_nic_from_net_success(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) mock_instance = Mock() self.instance_service.get_instance_from_instance_id = Mock(return_value=mock_instance) mock_iface_detach_result = Mock() mock_instance.interface_detach = Mock(return_value=mock_iface_detach_result) result = self.instance_service.detach_nic_from_instance(openstack_session=self.openstack_session, instance_id='test_instance_id', port_id='test_port_id', logger=self.mock_logger) mock_instance.interface_detach.assert_called_with('test_port_id') self.assertEqual(result, True) def test_detach_nic_from_net_failure(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) mock_instance = Mock() self.instance_service.get_instance_from_instance_id = Mock(return_value=mock_instance) mock_instance.interface_detach = Mock(side_effect=Exception) result = self.instance_service.detach_nic_from_instance(openstack_session=self.openstack_session, instance_id='test_instance_id', port_id='test_port_id', logger=self.mock_logger) self.assertEqual(result, False) def test_attach_floating_ip(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) test_external_nw_id = 'ext-net-id' test_floating_ip = '4.3.2.1' test_net_label = 'test-net' mock_net_obj = Mock() mock_net_obj.to_dict = Mock(return_value={'id': test_external_nw_id, 'label': test_net_label}) mock_client.networks.list = Mock(return_value=[mock_net_obj]) mock_floating_ip_obj = Mock() mock_floating_ip_obj.ip = test_floating_ip mock_client.floating_ips.create = Mock(return_value=mock_floating_ip_obj) mock_instance = Mock() mock_instance.add_floating_ip = Mock() result = self.instance_service.attach_floating_ip(openstack_session=self.openstack_session, instance=mock_instance, floating_ip=test_floating_ip, logger=self.mock_logger) mock_instance.add_floating_ip.assert_called_with(test_floating_ip) self.assertEqual(result, True) def test_detach_floating_ip(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) mock_floating_ip = '1.2.3.4' mock_instance = Mock() self.instance_service.get_instance_from_instance_id = Mock(return_value=mock_instance) mock_instance.remove_floating_ip = Mock() self.instance_service.detach_floating_ip(openstack_session=self.openstack_session, instance=mock_instance, floating_ip=mock_floating_ip, logger=self.mock_logger) mock_instance.remove_floating_ip.assert_called_with(mock_floating_ip) def test_get_instance_mgmt_net_name_success(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) test_net_id = 'test_net_id' test_cp_resource_model = Mock() test_cp_resource_model.qs_mgmt_os_net_uuid = test_net_id mock_net_obj = Mock() mock_net_obj.to_dict = Mock(return_value={'id': test_net_id, 'label': 'test_returned_net'}) mock_client.networks = Mock() mock_client.networks.list = Mock(return_value=[mock_net_obj]) result = self.instance_service.get_instance_mgmt_network_name(instance=Mock(), openstack_session=self.openstack_session, cp_resource_model=test_cp_resource_model) self.assertEqual(result, 'test_returned_net') def test_get_instance_mgmt_net_name_fail(self): mock_client = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client) test_net_id = 'test_net_id' test_cp_resource_model = Mock() test_cp_resource_model.qs_mgmt_os_net_uuid = test_net_id test_net_id_1 = 'test_net_id_1' mock_net_obj = Mock() mock_net_obj.to_dict = Mock(return_value={'id': test_net_id_1, 'label': 'test_returned_net'}) mock_client.networks = Mock() mock_client.networks.list = Mock(return_value=[mock_net_obj]) result = self.instance_service.get_instance_mgmt_network_name(instance=Mock(), openstack_session=self.openstack_session, cp_resource_model=test_cp_resource_model) self.assertEqual(result, None) def test_instance_create_error_state(self): test_name = 'test' CloudshellDriverHelper.get_uuid = Mock(return_value='1234') test_uniq_name = 'test-1234' mock_client2 = Mock() test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client2) # mock_client.Client = Mock(return_vaule=mock_client2) mock_image = Mock() mock_flavor = Mock() mock_client2.images.find = Mock(return_value=mock_image) mock_client2.flavors.find = Mock(return_value=mock_flavor) mock_cp_resource_model = Mock() mock_cp_resource_model.qs_mgmt_os_net_uuid = '1234' mock_cancellation_context = Mock() mock_client2.servers = Mock() mocked_inst = Mock() mock_client2.servers.create = Mock(return_value=mocked_inst) mock_qnet_dict = {'net-id': mock_cp_resource_model.qs_mgmt_os_net_uuid} self.instance_service.instance_waiter = Mock() self.instance_service.instance_waiter.wait = Mock(side_effect=InstanceErrorStateException) with self.assertRaises(InstanceErrorStateException): result = self.instance_service.create_instance(openstack_session=self.openstack_session, name=test_name,
# # Alignak 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 Alignak. If not, see <http://www.gnu.org/licenses/>. # # # This file incorporates work covered by the following copyright and # permission notice: # # Copyright (C) 2009-2014: # Hartmut Goebel, h.goebel@goebel-consult.de # Grégory Starck, g.starck@gmail.macros_command # Sebastien Coavoux, s.coavoux@free.fr # Jean Gabes, naparuba@gmail.macros_command # Zoran Zaric, zz@zoranzaric.de # Gerhard Lausser, gerhard.lausser@consol.de # This file is part of Shinken. # # Shinken 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. # # Shinken is distributed in the hope that i
t 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 Shinken. If not, see <http://www.gnu.org/licenses/>. # # This file is used to test reading and processing of config files # import pytest fro
m .alignak_test import * from alignak.macroresolver import MacroResolver from alignak.commandcall import CommandCall class MacroResolverTester(object): def get_hst_svc(self): svc = self._scheduler.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0") hst = self._scheduler.hosts.find_by_name("test_host_0") return (svc, hst) def test_resolv_simple(self): """Test a simple macro resolution :return: """ # These are macros built from a variable declare in alignak.ini file # ; Some macros for the tests # $alignak_test_macro=test macro # _alignak_test_macro2=test macro 2 result = self.mr.resolve_simple_macros_in_string("$ALIGNAK_TEST_MACRO$", [], None, None, None) assert result == "test macro" result = self.mr.resolve_simple_macros_in_string("$ALIGNAK_TEST_MACRO2$", [], None, None, None) assert result == "test macro 2" # These are macros read from a pack. section of the alignak.ini configuration result = self.mr.resolve_simple_macros_in_string("$SMTP_SERVER$", [], None, None, None) assert result == "your_smtp_server_address" result = self.mr.resolve_simple_macros_in_string("$MAIL_FROM$", [], None, None, None) assert result == "alignak@monitoring" # This is a macro built from a variable that is a string result = self.mr.resolve_simple_macros_in_string("$ALIGNAK$", [], None, None, None) assert result == "My Alignak" # This is a macro built from a variable that is a list of strings result = self.mr.resolve_simple_macros_in_string("$ALIGNAK_CONFIG$", [], None, None, None) assert isinstance(result, string_types) expected = "[%s]" % ','.join(self.alignak_env.cfg_files) assert result == expected # This is a macro built from a dynamic variable result = self.mr.resolve_simple_macros_in_string("$MAINCONFIGFILE$", [], None, None, None) assert result == os.path.abspath(os.path.join(self._test_dir, self.setup_file)) result = self.mr.resolve_simple_macros_in_string("$MAINCONFIGDIR$", [], None, None, None) assert result == os.path.abspath(os.path.join(self._test_dir, './cfg')) # This is an empty macro -> '' result = self.mr.resolve_simple_macros_in_string("$COMMENTDATAFILE$", [], None, None, None) assert result == "" # This is a macro built from an Alignak variable - because the variable is prefixed with _ # The macro name is built from the uppercased variable name without the leading # and trailing underscores: _dist -> $DIST$ result = self.mr.resolve_simple_macros_in_string("$DIST$", [], None, None, None) assert result == "/tmp" # Alignak variable interpolated from %(var) is available as a macro result = self.mr.resolve_simple_macros_in_string("$DIST_ETC$", [], None, None, None) assert result == "/tmp/etc/alignak" # # Alignak "standard" variable is not available as a macro # # Empty value ! todo: Perharps should be changed ? # Sometimes the user is defined to alignak for test purpose and it remans set to this value! # result = self.mr.resolve_simple_macros_in_string("$USER$", [], None, None, None) # assert result == "" def test_resolv_simple_command(self): """Test a simple command resolution :return: """ (svc, hst) = self.get_hst_svc() data = [hst, svc] macros_command = self.mr.resolve_command(svc.check_command, data, self._scheduler.macromodulations, self._scheduler.timeperiods) assert macros_command == "plugins/test_servicecheck.pl --type=ok --failchance=5% " \ "--previous-state=OK --state-duration=0 " \ "--total-critical-on-host=0 --total-warning-on-host=0 " \ "--hostname test_host_0 --servicedesc test_ok_0" # @pytest.mark.skip(reason="A macro remains valued where all should be reset to default!") def test_args_macro(self): """ Test ARGn macros :return: """ print("Initial test macros: %d - %s" % (len(self._scheduler.pushed_conf.__class__.macros), self._scheduler.pushed_conf.__class__.macros)) print(" - : %s" % (self._scheduler.pushed_conf.__class__.properties['$USER1$'])) print(" - : %s" % (self._scheduler.pushed_conf.properties['$USER1$'])) print(" - : %s" % (getattr(self._scheduler.pushed_conf, '$USER1$', None))) for key in self._scheduler.pushed_conf.__class__.macros: key = self._scheduler.pushed_conf.__class__.macros[key] if key: value = getattr(self._scheduler.pushed_conf.properties, key, '') print(" - %s : %s" % (key, self._scheduler.pushed_conf.properties[key])) if value: print("- %s = %s" % (key, value)) (svc, hst) = self.get_hst_svc() data = [hst, svc] # command_with_args is defined with 5 arguments as: # $PLUGINSDIR$/command -H $HOSTADDRESS$ -t 9 -u -c $ARG1$ # -a $ARG2$ $ARG3$ $ARG4$ and the last is $ARG5$. # No arguments are provided - will be valued as empty strings dummy_call = "command_with_args" cc = CommandCall({"commands": self._arbiter.conf.commands, "command_line": dummy_call}, parsing=True) macros_command = self.mr.resolve_command(cc, data, self._scheduler.macromodulations, self._scheduler.timeperiods) # todo: Test problem is here! # Whereas we should get: assert macros_command == 'plugins/command -H 127.0.0.1 -t 9 -u -c -a and the last is .' # We get: # assert macros_command == '/var/lib/shinken/libexec/command -H 127.0.0.1 -t 9 -u -c -a and the last is .' # Outside the test env, everything is ok ! Because some tests executed before the macro # do not have the correct value! # Extra arguments are provided - will be ignored dummy_call = "command_with_args!arg_1!arg_2!arg_3!arg_4!arg_5!extra argument" cc = CommandCall({"commands": self._arbiter.conf.commands, "command_line": dummy_call}, parsing=True) macros_command = self.mr.resolve_command(cc, data, self._scheduler.macromodulations, self._sche
# Version 4.0 import csv import sys count = 10 offset = 0 if len(sys.argv) >= 3: count = int(sys.argv[1]) offset = int(sys.argv[2]) - 1 start = offset*count start = 1 if start==
0 else start end = start + count r = csv.reader(sys.stdin) rows = [] i = 0 for l in r: rows.append(l[:1] + l[start:end]) i = i + 1 if(i > 1): csv.wri
ter(sys.stdout).writerows(rows)
c language governing permissions and # limitations under the License. import re import sys import logging from threading import Thread, Lock, Event try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty from ncclient.xml_ import * from ncclient.capabilities import Capabilities from ncclient.transport.errors import TransportError, SessionError, SessionCloseError from ncclient.transport.notify import Notification logger = logging.getLogger('ncclient.transport.session') class Session(Thread): "Base class for use by transport protocol implementations." def __init__(self, capabilities): Thread.__init__(self) self.setDaemon(True) self._listeners = set() self._lock = Lock() self.setName('session') self._q = Queue() self._notification_q = Queue() self._client_capabilities = capabilities self._server_capabilities = None # yet self._id = None # session-id self._timeout = None self._connected = False # to be set/cleared by subclass implementation logger.debug('%r created: client_capabilities=%r' % (self, self._client_capabilities)) self._device_handler = None # Should be set by child class def _dispatch_message(self, raw): try: root = parse_root(raw) except Exception as e: device_handled_raw=self._device_handler.handle_raw_dispatch(raw) if isinstance(device_handled_raw, str): root = parse_root(device_handled_raw) elif isinstance(device_handled_raw, Exception): self._dispatch_error(device_handled_raw) return else: logger.error('error parsing dispatch message: %s' % e) return with self._lock: listeners = list(self._listeners) for l in listeners: logger.debug('dispatching message to %r: %s' % (l, raw)) l.callback(root, raw) # no try-except; fail loudly if you must! def _dispatch_error(self, err): with self._lock: listeners = list(self._listeners) for l in listeners: logger.debug('dispatching error to %r' % l) try: # here we can be more considerate with catching exceptions l.errback(err) except Exception as e: logger.warning('error dispatching to %r: %r' % (l, e)) def _post_connect(self): "Greeting stuff" init_event = Event() error = [None] # so that err_cb can bind error[0]. just how it is. # callbacks def ok_cb(id, capabilities): self._id = id self._server_capabilities = capabilities init_event.set() def err_cb(err): error[0] = err init_event.set() self.add_listener(NotificationHandler(self._notification_q)) listener = HelloHandler(ok_cb, err_cb) self.add_listener(listener) self.send(HelloHandler.build(self._client_capabilities, self._device_handler)) logger.debug('starting main loop') self.start() # we expect server's hello message if not init_event.wait(self._timeout): raise SessionCloseError("Session hello timeout") # received hello message or an error happened self.remove_listener(listener) if error[0]: raise error[0] #if ':base:1.0' not in self.server_capabilities: # raise MissingCapabilityError(':base:1.0') logger.info('initialized: session-id=%s | server_capabilities=%s' % (self._id, self._server_capabilities)) def add_listener(self, listener): """Register a listener that will be notified of incoming messages and errors. :type listener: :class:`SessionListener` """ logger.debug('installing listener %r' % listener) if not isinstance(listener, SessionListener): raise SessionError("Listener must be a SessionListener type") with self._lock: self._listeners.add(listener) def remove_listener(self, listener): """Unregister some listener; ignore if the listener was never registered. :type listener: :class:`SessionListener` """ logger.debug('discarding listener %r' % listener) with self._lock: self._listeners.discard(listener) def get_listener_instance(self, cls): """If a listener of the specified type is registered, returns the instance. :type cls: :class:`SessionListener` """ with self._lock: for listener in self._listeners: if isinstance(listener, cls): return listener def connect(self, *args, **kwds): # subclass implements raise NotImplementedError def run(self): # subclass implements raise NotImplementedError def send(self, message): """Send the supplied *message* (xml string) to NETCONF server.""" if not self.connected: raise TransportError('Not connected to NETCONF server') logger.debug('queueing %s' % message) self._q.put(message) def scp(self): raise NotImplementedError ### Properties def take_notification(self, block, timeout): try: return self._notification_q.get(block, timeout) except Empty: return None @property def connected(self): "Connection status of the session." return self._connected @property def client_capabilities(self): "Client's :class:`Capabilities`" return self._client_capabilities @property def server_capabilities(self): "Server's :class:`Capabilities`" return self._server_capabilities @property def id(self): """A string representing the `session-id`. If the session has not been initialized it will be `None`""" return self._id class SessionListener(object): """Base class for :class:`Session` listeners, which are notified when a new NETCONF message is received or an error occurs. .. note:: Avoid time-intensive tasks in a callback's context. """
def callback(self, root, raw): """Called when a new XML document is received. The *root* argument allows the callback to determine whether it wants to further process the document. Here, *root* is a tuple of *(tag, attributes)* where *tag* is the qualified name of the
root element and *attributes* is a dictionary of its attributes (also qualified names). *raw* will contain the XML document as a string. """ raise NotImplementedError def errback(self, ex): """Called when an error occurs. :type ex: :exc:`Exception` """ raise NotImplementedError class HelloHandler(SessionListener): def __init__(self, init_cb, error_cb): self._init_cb = init_cb self._error_cb = error_cb def callback(self, root, raw): tag, attrs = root if (tag == qualify("hello")) or (tag == "hello"): try: id, capabilities = HelloHandler.parse(raw) except Exception as e: self._error_cb(e) else: self._init_cb(id, capabilities) def errback(self, err): self._error_cb(err) @staticmethod def build(capabilities, device_handler): "Given a list of capability URI's returns <hello> message XML string" if device_handler: # This is used as kwargs dictionary for lxml's Element() function. # Therefore the arg-name ("nsmap") is used as key here. xml_namespace_kwargs = { "nsmap" : device_handler.get_xml_base_namespace_dict() } else: xml_namespace_kwargs = {} hello = new_ele("hello", **xml_namespace_kwargs) caps = sub_ele(hello, "capabilities") def fun(uri): sub_ele(caps, "capability").text = uri #python3 changes if sys.version
from .__about__ import __version__ from .portworx import PortworxCheck __all__ = ['__version__', 'PortworxChe
ck']
# -*- coding: utf-8 -*- from __future__ import absolute_import import os from zeeko._build_helpers import get_utils_extension_args, get_zmq_extension_args, _generate_cython_extensions, pxd, get_package_data from astropy_helpers import setup_helpers utilities = [pxd("..utils.rc"), pxd("..utils.msg"), pxd("..utils.pthread"), pxd("..utils.lock"), pxd("..utils.condition"), pxd("..utils.clock")] base = [ pxd("..cyloop.throttle"), px
d("..cyloop.statemachine"), pxd(".snail"), pxd(".base")] dependencies = { 'base' : utilities + [ pxd("..cyloop.throttle") ], 'snail' : utilities + [ pxd("..cyloop.throttle"), pxd("..cyloop.statemachine") ], 'client' : utilities + base + [ pxd("..messages.receiver") ], 'server' : utilities + base + [ pxd("..messages.publish
er") ], } def get_extensions(**kwargs): """Get the Cython extensions""" extension_args = setup_helpers.DistutilsExtensionArgs() extension_args.update(get_utils_extension_args()) extension_args.update(get_zmq_extension_args()) extension_args['include_dirs'].append('numpy') package_name = __name__.split(".")[:-1] extensions = [e for e in _generate_cython_extensions(extension_args, os.path.dirname(__file__), package_name)] for extension in extensions: name = extension.name.split(".")[-1] if name in dependencies: extension.depends.extend(dependencies[name]) return extensions
#!/usr/bin/env python # Encoding: utf-8 # ----------------------------------------------------------------------------- # Project : Broken Promises # ----------------------------------------------------------------------------- # Author : Edouard Richard <edou4rd@gmail.com> # ----------------------------------------------------------------------------- # License : GNU General Public License # ----------------------------------------------------------------------------- # Creation : 28-Oct-2013 # Last mod : 27-Nov-2013 # ----------------------------------------------------------------------------- # This file is part of Broken Promises. # # Broken Promises 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. # # Broken Promises 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 Broken Promises. If not, see <http://www.gnu.org/licenses/>. from brokenpromises.operations import CollectArticles from bson.json_util import dumps import optparse import brokenpromises.channels import sys import reporter reporter.REPORTER.register(reporter.StderrReporter()) debug, trace, info, warning, error, fatal = reporter.bind("script_collect_articles") oparser = optparse.OptionParser(usage ="\n./%prog [options] year \n./%prog [options] year month\n./%prog [options] year month day") # oparser.add_option("-C", "--nocache", action="store_true", dest="nocache", # help = "Prevents from using the cache", default=False) oparser.add_option("-f", "--channelslistfile", action="store", dest="channels_file", help = "Use this that as channels list to use", default=None) oparser.add_option("-c", "--channels", action="store", dest="channels_list", help = "channels list comma separated", default=None) oparser.add_option("-s", "--storage", action="store_true", dest="storage", help = "Save the result with the default storage", default=False) oparser.add_option("-d", "--drop", action="store_true", dest="mongodb_drop", help = "drop the previous articles from database before", default=False) oparser.add_option("--force", action="store_true", dest="force_collect", help = "Force the scrap. If --storage is enable, the scrap could be escape b/c of a previous similar scrap", default=False) oparser.add_option("-o", "--output", action="store", dest="output_file", help = "Specify a file to write the export to. If you do n
ot specify a file name, the program writes data to standard output (e.g. stdout)", default=None) # Think to update the README.md file after modifying the options options, a
rgs = oparser.parse_args() assert len(args) > 0 and len(args) <= 3 if options.output_file: sys.stdout = open(options.output_file, 'a') channels = brokenpromises.channels.get_available_channels() if options.channels_file: with open(options.channels_file) as f: channels = [line.replace("\n", "") for line in f.readlines()] if options.channels_list: channels = options.channels_list.split(",") collector = CollectArticles(channels, *args, use_storage=options.storage, force_collect=options.force_collect) if options.mongodb_drop: collector.storage.get_database().drop_collection("articles") collector.storage.get_database().drop_collection("reports") results = collector.run() # OUTPUT print dumps([_.__dict__ for _ in results]).encode('utf-8') info("%d articles collected." % (len(results))) exit() # EOF
#/usr/bin/env python # -#- coding: utf-8 -#- # # contract/core/api.py - functions which simplify contract package feature access # # This file is part of OndALear collection of open source components # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Copyright (C) 2008 Amnon Janiv <amnon.janiv@ondalear.com> # # Initial version: 2008-02-01 # Author: Amnon Janiv <amnon.janiv@ondalear.com> """ .. module:: contract.core.api :synopsis: Contract core simplified feature access module Set of functions which simplify access to contract.core features. .. moduleauthor:: Amnon Janiv <amnon.janiv@ondalear.com> """ __revision__ = '$Id: $' __version__ = '0.0.1' from contract.core.package import BusContractCorePackageDescriptor import busxml.core.api def parse_file(file_name): """Parse an xml file containing contract object graph :p
aram file_name: XML file name. :type file_name: str. :returns: BusinessContractWorkspace -- contract object graph container. ""
" package_desc = BusContractCorePackageDescriptor.get_instance() root_obj = busxml.core.api.parse_file(file_name, package_desc) return root_obj def export_to_string(obj): """Export contract object graph to string :param obj: Contract object graph container. :type obj: BusinessContractWorkspace. :returns: unicode -- xml string with underlying contract information """ package_desc = BusContractCorePackageDescriptor.get_instance() buf = busxml.core.api.export_to_string(obj, package_desc) return buf
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils.init_weights import init_weights, normalized_columns_initializer from core.model import Model class A3CMlpConModel(Model): def __init__(self, args): super(A3CMlpConModel, self).__init__(args) # build model # 0. feature layers self.fc1 = nn.Linear(self.input_dims[0] * self.input_dims[1], self.hidden_dim) # NOTE: for pkg="gym" self.rl1 = nn.ReLU() self.fc2 = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl2 = nn.ReLU() self.fc3 = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl3 = nn.ReLU() self.fc4 = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl4 = nn.ReLU() self.fc1_v = nn.Linear(self.input_dims[0] * self.input_dims[1], self.hidden_dim) # NOTE: for pkg="gym" self.rl1_v = nn.ReLU() self.fc2_v = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl2_v = nn.ReLU() self.fc3_v = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl3_v = nn.ReLU() self.fc4_v = nn.Linear(self.hidden_dim, self.hidden_dim) self.rl4_v = nn.ReLU() # lstm if self.enable_lstm: self.lstm = nn.LSTMCell(self.hidden_dim, self.hidden_dim) self.lstm_v = nn.LSTMCell(self.hidden_dim, self.hidden_dim) # 1. policy output self.policy_5 = nn.Linear(self.hidden_dim, self.output_dims) self.policy_sig = nn.Linear(self.hidden_dim, self.output
_dims) self.softplus = nn.Softplus() # 2. value output self.value_5 = nn.Linear(self.hidden_dim, 1) self._reset() def _init_weights(self): self.apply(init_weights)
self.fc1.weight.data = normalized_columns_initializer(self.fc1.weight.data, 0.01) self.fc1.bias.data.fill_(0) self.fc2.weight.data = normalized_columns_initializer(self.fc2.weight.data, 0.01) self.fc2.bias.data.fill_(0) self.fc3.weight.data = normalized_columns_initializer(self.fc3.weight.data, 0.01) self.fc3.bias.data.fill_(0) self.fc4.weight.data = normalized_columns_initializer(self.fc4.weight.data, 0.01) self.fc4.bias.data.fill_(0) self.fc1_v.weight.data = normalized_columns_initializer(self.fc1_v.weight.data, 0.01) self.fc1_v.bias.data.fill_(0) self.fc2_v.weight.data = normalized_columns_initializer(self.fc2_v.weight.data, 0.01) self.fc2_v.bias.data.fill_(0) self.fc3_v.weight.data = normalized_columns_initializer(self.fc3_v.weight.data, 0.01) self.fc3_v.bias.data.fill_(0) self.fc4_v.weight.data = normalized_columns_initializer(self.fc4_v.weight.data, 0.01) self.fc4_v.bias.data.fill_(0) self.policy_5.weight.data = normalized_columns_initializer(self.policy_5.weight.data, 0.01) self.policy_5.bias.data.fill_(0) self.value_5.weight.data = normalized_columns_initializer(self.value_5.weight.data, 1.0) self.value_5.bias.data.fill_(0) self.lstm.bias_ih.data.fill_(0) self.lstm.bias_hh.data.fill_(0) self.lstm_v.bias_ih.data.fill_(0) self.lstm_v.bias_hh.data.fill_(0) def forward(self, x, lstm_hidden_vb=None): p = x.view(x.size(0), self.input_dims[0] * self.input_dims[1]) p = self.rl1(self.fc1(p)) p = self.rl2(self.fc2(p)) p = self.rl3(self.fc3(p)) p = self.rl4(self.fc4(p)) p = p.view(-1, self.hidden_dim) if self.enable_lstm: p_, v_ = torch.split(lstm_hidden_vb[0],1) c_p, c_v = torch.split(lstm_hidden_vb[1],1) p, c_p = self.lstm(p, (p_, c_p)) p_out = self.policy_5(p) sig = self.policy_sig(p) sig = self.softplus(sig) v = x.view(x.size(0), self.input_dims[0] * self.input_dims[1]) v = self.rl1_v(self.fc1_v(v)) v = self.rl2_v(self.fc2_v(v)) v = self.rl3_v(self.fc3_v(v)) v = self.rl4_v(self.fc4_v(v)) v = v.view(-1, self.hidden_dim) if self.enable_lstm: v, c_v = self.lstm_v(v, (v_, c_v)) v_out = self.value_5(v) if self.enable_lstm: return p_out, sig, v_out, (torch.cat((p,v),0), torch.cat((c_p, c_v),0)) else: return p_out, sig, v_out
n
= int(input()) s = input() letterlist = ['x', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] letter = {} for l in letterlist: letter[l] = 0 for i in range(n): if s[i:i+1] in letterlist: letter[s[i:i+1]] += 1 if letter['x'] > 0 and letter['0'] > 0: letter['0'] -= 1
del letter['x'] del letterlist[0] res = '0x' if any(c > 0 for c in letter.values()): letterlist.reverse() for l in letterlist: res += l*letter[l] print(res) else: print('No')
from django.apps import AppCo
nfig
class TorrentsConfig(AppConfig): name = 'torrents'
import sys import json def make_column_to_candidate_dict(header_row): my_dict = {} for colIndex, candidate in enumerate(header_row): my_dict[colIndex] = candidate.strip() return my_dict def return_candidates_in_order(row, col_to_candidate_dict): ballot = [] for i in range(0,len(row)): ballot.append([]) for colIndex, rank in enumerate(row): candidate = col_to_candidate_dict[colIndex] int_rank = int(rank) ballot[int_rank-1].append(candidate) ballot = filter(lambda x: len(x) > 0, ballot) return ballot def split_line(line): return line.split('\t') def convert_csv(filename): return convert_csv_to_php(filename) def convert_csv_to_json(filename): ballot_arrays = get_ballot_arrays(filename) objects = [] for ballot_array in ballot_arrays: ballot_object = {'count': 1, 'values': ballot_array} print(json.dumps(objects)) def convert_csv_to_php(filename): class_text = '' with open('TestScenarioHeader.php.fragment', 'r') as class_header: class_text += class_header.read() ballot_arrays = get_ballot_arrays(filename) class_text += generate_php(ballot_arrays) with open('TestScenarioFooter.php.fragment', 'r') as class_footer: class_text += class_footer.read().rstrip() print class_text def generate_php(ballot_arrays): ballots = [] for ballot in ballot_arrays: ballots.append(generate_one_ballot_php(ballot)) return ' return [\n' + ',\n'.join(ballots) + '\n ];\n' def generate_one_ballot_php(ballot): php = ' new NBallot(\n 1,\n' candidate_lists = [] for group in ballot: candidate_list = ' new CandidateList(\n' candidates = [] for candidate in group: candidates.append(' new Candidate("' + candidate + '")') candidate_list += ',\n'.join(candidates) candidate_list += '\n )' candidate_lists.append(candidate_list) php +=
',\n'.join(candidate_lists) php += '\n )' return php def get_ballot_arrays(filename): ballots = [] heade
r = True ids = False with open(filename, 'r') as csv: for line in csv.readlines(): row = split_line(line) if header: header = False ids = True elif ids: col_to_candidate_dict = make_column_to_candidate_dict(row) ids = False else: ballot = return_candidates_in_order(row, col_to_candidate_dict) ##print ballot ballots.append(ballot) return ballots if __name__ == '__main__': convert_csv(sys.argv[1])
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/structure/ta
tooine/shared_pillar_pristine_small_style_01.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN
MODIFICATIONS #### #### END MODIFICATIONS #### return result
#!/usr/bin/eny python #coding:utf-8 from gi.repository
import Gtk class ButtonWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title='Button Demo') self.set_border_width(10) hbox = Gtk.Box(spacing=6) self.add(hbox) button = Gtk.Button('Click M
e') button.connect('clicked', self.on_click_me_clicked) hbox.pack_start(button, True, True, 0) button = Gtk.Button(stock=Gtk.STOCK_OPEN) button.connect('clicked', self.on_open_clicked) hbox.pack_start(button, True, True, 0) button = Gtk.Button('_Close', use_underline=True) button.connect('clicked', self.on_close_clicked) hbox.pack_start(button, True, True, 0) def on_click_me_clicked(self, button): print '"click me" button was clicked' def on_open_clicked(self, button): print '"open" button was clicked' def on_close_clicked(self, button): print 'Closing application' Gtk.main_quit() wind = ButtonWindow() wind.connect('delete-event', Gtk.main_quit) wind.show_all() Gtk.main()
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2012 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## 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., or visit: http://www.gnu.org/. ## ## Author(s): Stoq Team <stoq-devel@async.com.br> ## import gtk import mock from stoqlib.database.runtime import get_current_branch from stoqlib.domain.transfer import TransferOrder from stoqlib.gui.test.uitestutils import GUITest from stoqlib.gui.wizards.stocktransferwizard import StockTransferWizard from stoqlib.lib.translation import stoqlib_gettext _ = stoqlib_gettext class TestStockTransferWizard(GUITest): @mock.patch('stoqlib.gui.wizards.stocktransferwizard.print_report') @mock.patch('stoqlib.gui.wizards.stocktransferwizard.yesno') def test_create(self, yesno, print_report): sellable = self.create_sellable(description=u"Product to transfer") self.create_storable(sellable.product, get_current_branch(self.store), stock=10) wizard = StockTransferWizard(self.store) self.assertNo
tSensitive(wizard, ['next_button']) self.check_wizard(wizard, 'wizard-stock-transfer-create') step = wizard.get_current_step() step.destination_branch.set_active(0) self.assertSensitive(wizard, ['next_button']) self.click(wizard.next_button) step = wizard.get_current_step() # adds sellable to step step.sellable_selected(sellable) step._add
_sellable() self.check_wizard(wizard, 'wizard-stock-transfer-products') module = 'stoqlib.gui.events.StockTransferWizardFinishEvent.emit' with mock.patch(module) as emit: with mock.patch.object(self.store, 'commit'): self.click(wizard.next_button) self.assertEquals(emit.call_count, 1) args, kwargs = emit.call_args self.assertTrue(isinstance(args[0], TransferOrder)) yesno.assert_called_once_with( _('Would you like to print a receipt for this transfer?'), gtk.RESPONSE_YES, 'Print receipt', "Don't print") self.assertEquals(print_report.call_count, 1)
""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports from lib2to3 import fixer_base from lib2to3.fixer_util import BlankLine, syms, token class FixItertoolsImports(fixer_base.BaseFix): PATTERN = """ import_from< 'from' 'itertools' 'import' imports=any > """ %(locals()) def transform(self, node, results): imports = results['imports'] if imports.type == syms.import_as_name or not imports.children: children = [imports] else: children = imports.children for child in children[::2]: if child.type == token.NAME: member = child.value name_node = child else: assert child.type == syms.import_as_name name_node = child.children[0] member_name = name_node.value if member_name in (u'imap', u'izip', u'ifilter'): child.value = None child.remove() elif member_name == u'ifilterfalse': node.changed() name_node.value = u'filterfalse' # Make sure the import statement is still sane children = imports.children[:] or [imports] remove_comma = True for child i
n children: if remove_comma and child.type == token.COMMA: child.remove() else: remove_comma ^= True if children[-1].type == token.COMMA: children[-1].remove() # If there are no impo
rts left, just get rid of the entire statement if not (imports.children or getattr(imports, 'value', None)) or \ imports.parent is None: p = node.prefix node = BlankLine() node.prefix = p return node
''' Created on Jun 29, 2016 @author: Thomas Adriaan Hellinger ''' import pytest from roodestem.voting_systems.voting_system import Result class TestResult:
def test_null_result_not_tolerated(self): with pytest.raises(TypeError): Result() def test_passed_multiple_winners(self): res = Result(winner=['a', 'b', 'c'
], tied=['b','c']) assert res == Result(tied=['a', 'b', 'c']) def test_passed_all_losers(self): res = Result(loser=['a', 'b', 'c']) assert res == Result(tied=['a', 'b', 'c']) def test_passed_all_winners(self): res = Result(winner=['a', 'b', 'c']) assert res == Result(tied=['a', 'b', 'c'])
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.status import HTTP_204_NO_CONTENT from users.serializers import UserSerializer from rest_framework.permissions import AllowAny from django.contrib.auth import login, logout from rest_framework.authentication import BaseAuthentication, SessionAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_framework.authtoken.serializers import AuthTokenSerializer from django.contrib.auth import login, logout from users.authent
ication import CustomBaseAuthentication class AuthLoginView(APIView): authentication_classes = (CustomBaseAuthentication, SessionAuthentication) def post(self, request): login(request,
request.user) return Response(status=HTTP_204_NO_CONTENT) class AuthLogoutView(APIView): def delete(self, request): logout(request) return Response(status=HTTP_204_NO_CONTENT) class UserRegisterView(APIView): permission_classes = (AllowAny,) authentication_classes = () # TODO: Remove def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') def _scrape_urls(html: str, base_url: str) -> List[str]: """Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, assuming that many consumers and many producers would be running at the same time, connected to one Redis instance, we would need to cache normalized versions or visited URIs without fragments (https://tools.ietf.org/html/rfc3986#section-3.5) so we don't fall into loops. For example two sites referencing each other. The cached entries could have time-to-live (Redis EXPIRE command), so we could refresh our knowledge about a site eventually. """ soup = BeautifulSoup(html, 'html.parser') href = 'href' return [urljoin(base_url, link.get(href)) for link in soup.find_all('a') if link.has_attr(href)] async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool): _log.info('Processing HTML from queue...') while True: try: html_payload = await redis_queue.pop(redis_pool) _log.info('Processing HTML from URL %s', html_payload.url) scraped_urls = _scrape_urls(html_payload.html, html_payload.url) _log.info('Scraped URIs from URL %s', html_payload.url) output_json = {html_payload.url: scraped_urls} # flush for anyone who is watching the stream print(json.dumps(output_json), flush=True) except redis_queue.QueueEmptyError: # wait for work to become available await asyncio.sleep(1) # prag
ma: no cover def main(): """Run the URL extractor (the consumer). """
app_cli.setup_logging() args_parser = app_cli.get_redis_args_parser( 'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those ' 'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}') args = args_parser.parse_args() loop = app_cli.get_event_loop() _log.info('Creating a pool of connections to Redis at %s:%d.', args.redis_host, args.redis_port) # the pool won't be closed explicitly, since the process needs to be terminated to stop anyway redis_pool = loop.run_until_complete( aioredis.create_pool((args.redis_host, args.redis_port))) loop.run_until_complete(_scrape_urls_from_queued_html(redis_pool)) if __name__ == '__main__': main()
from math import log def sort(a_list, base): """Sort the input list with the specified base, using Radix sort. This implementation assumes that the input list does not contain negative numbers. This algorithm is inspire
d from the Wikipedia implmentation of Radix sort. """ passes = int(log(max(a_list), base) + 1) items = a_list[:] for digit_index in xrange(passes): buckets = [[] for _ in xrange(base)] # Buckets
for sorted sublists. for item in items: digit = _get_digit(item, base, digit_index) buckets[digit].append(item) items = [] for sublists in buckets: items.extend(sublists) return items def _get_digit(number, base, digit_index): return (number // base ** digit_index) % base
.location) sys.exit(1) def progress_cmd(what, cmd): """Print cmd in a way a user could cut-and-paste to get the same effect""" progress(what) shell_text = "%s" % (" ".join(['"%s"' % x for x in cmd])) progress(shell_text) def run_cmd_blocking(what, cmd, quiet=False, check=False, **kw): if not quiet: progress_cmd(what, cmd) p = subprocess.Popen(cmd, **kw) ret = os.waitpid(p.pid, 0) _, sts = ret if check and sts != 0: progress("(%s) exited with code %d" % (what,sts,)) sys.exit(1) return ret def run_in_terminal_window(autotest, name, cmd): """Execute the run_in_terminal_window.sh command for cmd""" global windowID runme = [os.path.join(autotest, "run_in_terminal_window.sh"), name] runme.extend(cmd) progress_cmd("Run " + name, runme) if under_macos(): # on MacOS record the window IDs so we can close them later out = subprocess.Popen(runme, stdout=subprocess.PIPE).communicate()[0] import re p = re.compile('tab 1 of window id (.*)') windowID.append(p.findall(out)[0]) else: p = subprocess.Popen(runme) tracker_uarta = None # blemish def start_antenna_tracker(autotest, opts): """Compile and run the AntennaTracker, add tracker to mavproxy""" global tracker_uarta progress("Preparing antenna tracker") tracker_home = find_location_by_name(find_autotest_dir(), opts.tracker_location) vehicledir = os.path.join(autotest, "../../" + "AntennaTracker") tracker_frame_options = { "waf_target": _default_waf_target["AntennaTracker"], } do_build(vehicledir, opts, tracker_frame_options) tracker_instance = 1 os.chdir(vehicledir) tracker_uarta = "tcp:127.0.0.1:" + str(5760 + 10 * tracker_instance) exe = os.path.join(vehicledir, "AntennaTracker.elf") run_in_terminal_window(autotest, "AntennaTracker", ["nice", exe, "-I" + str(t
racker_instance), "--model=tracker", "--home=" + tracker_home]) def start_vehicle(binary, autotest, opts, stuff, loc): """Run the ArduPilot binary""" cmd_name = opts.vehicle cmd = [] if opts.valgrind: cmd_name += " (valgrind)" cmd.append("valgrind") if opts.gdb: cmd_name += " (gdb)" cmd.append("gdb") gdb_commands_file = tempfile.NamedTemporaryFile(delete=False) a
texit.register(os.unlink, gdb_commands_file.name) for breakpoint in opts.breakpoint: gdb_commands_file.write("b %s\n" % (breakpoint,)) gdb_commands_file.write("r\n") gdb_commands_file.close() cmd.extend(["-x", gdb_commands_file.name]) cmd.append("--args") if opts.strace: cmd_name += " (strace)" cmd.append("strace") strace_options = ['-o', binary + '.strace', '-s', '8000', '-ttt'] cmd.extend(strace_options) cmd.append(binary) cmd.append("-S") cmd.append("-I" + str(opts.instance)) cmd.extend(["--home", loc]) if opts.wipe_eeprom: cmd.append("-w") cmd.extend(["--model", stuff["model"]]) cmd.extend(["--speedup", str(opts.speedup)]) if opts.sitl_instance_args: cmd.extend(opts.sitl_instance_args.split(" ")) # this could be a lot better.. if opts.mavlink_gimbal: cmd.append("--gimbal") if "default_params_filename" in stuff: path = os.path.join(autotest, stuff["default_params_filename"]) progress("Using defaults from (%s)" % (path,)) cmd.extend(["--defaults", path]) run_in_terminal_window(autotest, cmd_name, cmd) def start_mavproxy(opts, stuff): """Run mavproxy""" # FIXME: would be nice to e.g. "mavproxy.mavproxy(....).run" rather than shelling out extra_cmd = "" cmd = [] if under_cygwin(): cmd.append("/usr/bin/cygstart") cmd.append("-w") cmd.append("/cygdrive/c/Program Files (x86)/MAVProxy/mavproxy.exe") else: cmd.append("mavproxy.py") if opts.hil: cmd.extend(["--load-module", "HIL"]) else: cmd.extend(["--master", mavlink_port]) if stuff["sitl-port"]: cmd.extend(["--sitl", simout_port]) # If running inside of a vagrant guest, then we probably want to forward our mavlink out to the containing host OS ports = [p + 10 * cmd_opts.instance for p in [14550,14551]] for port in ports: if os.path.isfile("/ardupilot.vagrant"): cmd.extend(["--out", "10.0.2.2:" + str(port)]) else: cmd.extend(["--out", "127.0.0.1:" + str(port)]) if opts.tracker: cmd.extend(["--load-module", "tracker"]) global tracker_uarta # tracker_uarta is set when we start the tracker... extra_cmd += "module load map; tracker set port %s; tracker start; tracker arm;" % (tracker_uarta,) if opts.mavlink_gimbal: cmd.extend(["--load-module", "gimbal"]) if "extra_mavlink_cmds" in stuff: extra_cmd += " " + stuff["extra_mavlink_cmds"] if opts.mavproxy_args: cmd.extend(opts.mavproxy_args.split(" ")) # this could be a lot better.. # compatibility pass-through parameters (for those that don't want # to use -C :-) for out in opts.out: cmd.extend(['--out', out]) if opts.map: cmd.append('--map') if opts.console: cmd.append('--console') if opts.aircraft is not None: cmd.extend(['--aircraft', opts.aircraft]) if len(extra_cmd): cmd.extend(['--cmd', extra_cmd]) local_mp_modules_dir = os.path.abspath( os.path.join(__file__, '..', '..', 'mavproxy_modules')) env = dict(os.environ) env['PYTHONPATH'] = local_mp_modules_dir + os.pathsep + env.get('PYTHONPATH', '') run_cmd_blocking("Run MavProxy", cmd, env=env) progress("MAVProxy exitted") # define and run parser parser = CompatOptionParser("sim_vehicle.py", epilog="eeprom.bin in the starting directory contains the parameters for your " \ "simulated vehicle. Always start from the same directory. It is "\ "recommended that you start in the main vehicle directory for the vehicle" \ "you are simulating, for example, start in the ArduPlane directory to " \ "simulate ArduPlane") parser.add_option("-v", "--vehicle", type='string', default=None, help="vehicle type (ArduPlane, ArduCopter or APMrover2)") parser.add_option("-f", "--frame", type='string', default=None, help="""set aircraft frame type for copters can choose +, X, quad or octa for planes can choose elevon or vtail""") parser.add_option("-C", "--sim_vehicle_sh_compatible", action='store_true', default=False, help="be compatible with the way sim_vehicle.sh works; make this the first option") parser.add_option("-H", "--hil", action='store_true', default=False, help="start HIL") group_build = optparse.OptionGroup(parser, "Build options") group_build.add_option("-N", "--no-rebuild", action='store_true', default=False, help="don't rebuild before starting ardupilot") group_build.add_option("-D", "--debug", action='store_true', default=False, help="build with debugging") group_build.add_option("-c", "--clean", action='store_true', default=False, help="do a make clean before building") group_build.add_option("-j", "--jobs", default=None, type='int', help="number of processors to use during build (default for waf : number of processor, for make : 1)") group_build.add_option("-b", "--build-target", default=None, type='string', help="override SITL build target") group_build.add_option("-s", "--build-system", default="waf", type='choice', choices=["make", "waf"], help="build system to use") group_build.add_option("", "--rebuild-on-failure", dest="rebuild_on_failure", action='store_true', default=False, help="if build fails, do not clean and rebuild") group_build.add_option("", "--waf-configure-arg", action="append", dest="waf_configure_args", type="string", default=[], help="extra arguments to pass to waf in its configure step") group_build.add_option("", "--waf-build-arg", action="append", dest="waf_build_args", type="string", default=[], help="extra argume
import urllib2 from lxml import etree #################################################################### # API #################################################################### class Scrape_Quora: regexpNS = "http://exslt.org/regular-expressions" @staticmethod def get_name(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) name = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/div/h1/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return name @staticmethod def get_url(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) URL = response.geturl() return URL @staticmethod def get_profile_picture_link(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) profile_picture_link = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/div/img/@data-src', namespaces={'re':Scrape_Quora.regexpNS})[0] return profile_picture_link @staticmethod def get_no_of_questions(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) no_of_questions = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Questions"]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return no_of_questions @staticmethod def get_no_of_answers(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) no_of_answers = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Answers"]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return no_of_answers @staticmethod def get_no_of_followers(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = e
tree.parse(response, htmlparser) no_of_followers = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Followers "]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return no_of_followers @staticmethod def get_no_of_following(user_name):
url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) no_of_following = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Following "]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return no_of_following @staticmethod def get_no_of_edits(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response, htmlparser) no_of_edits = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Edits"]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0] return no_of_edits
f
rom .group_analysis import create_fsl_flame_wf, \ get_operation __all__ = ['create_fsl_flame_wf', \
'get_operation']
ue', 'blank': 'True'}), 'render_max_age': ('django.db.models.fields.IntegerField'
, [], {'null': 'True', 'blank': 'True'}), 'render_scheduled_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'render_started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'rendered_errors': ('django.db.models.fields.TextFiel
d', [], {'null': 'True', 'blank': 'True'}), 'rendered_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['teamwork.Team']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'zone_subnav_local_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'wiki.documentattachment': { 'Meta': {'object_name': 'DocumentAttachment'}, 'attached_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Document']"}), 'file': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['attachments.Attachment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [], {}) }, 'wiki.documentdeletionlog': { 'Meta': {'object_name': 'DocumentDeletionLog'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'locale': ('kuma.core.fields.LocaleField', [], {'default': "'en-US'", 'max_length': '7', 'db_index': 'True'}), 'reason': ('django.db.models.fields.TextField', [], {}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'wiki.documenttag': { 'Meta': {'object_name': 'DocumentTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'wiki.documentzone': { 'Meta': {'object_name': 'DocumentZone'}, 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'zones'", 'unique': 'True', 'to': "orm['wiki.Document']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'styles': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'url_root': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'wiki.editortoolbar': { 'Meta': {'object_name': 'EditorToolbar'}, 'code': ('django.db.models.fields.TextField', [], {'max_length': '2000'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_toolbars'", 'to': "orm['auth.User']"}), 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'wiki.helpfulvote': { 'Meta': {'object_name': 'HelpfulVote'}, 'anonymous_id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'poll_votes'", 'null': 'True', 'to': "orm['auth.User']"}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'poll_votes'", 'to': "orm['wiki.Document']"}), 'helpful': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user_agent': ('django.db.models.fields.CharField', [], {'max_length': '1000'}) }, 'wiki.localizationtag': { 'Meta': {'object_name': 'LocalizationTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'wiki.localizationtaggedrevision': { 'Meta': {'object_name': 'LocalizationTaggedRevision'}, 'content_object': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Revision']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.LocalizationTag']"}) }, 'wiki.relateddocument': { 'Meta': {'ordering': "['-in_common']", 'object_name': 'RelatedDocument'}, 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'related_from'", 'to': "orm['wiki.Document']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_common': ('django.db.models.fields.IntegerField', [], {}), 'related': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'related_to'", 'to': "orm['wiki.Document']"}) }, 'wiki.reviewtag': { 'Meta': {'object_name': 'ReviewTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'wiki.reviewtaggedrevision': { 'Meta': {'object_name': 'ReviewTaggedRevision'}, 'content_object': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Revision']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.ReviewTag']"}) }, 'wiki.revision': { 'Meta': {'object_name': 'Revision'}, 'based_on': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Revision']", 'null': 'True', 'blank': 'True'}), 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'content': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_revisions'", 'to': "orm['auth.User']"}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['wiki.Document']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'is_mindtouch_migration': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'keywords': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
self.assertTrue(r) @res_mock.patch_client def test_session_finished_migrating(self, client, mocked): lun = client.vnx.get_lun() r = client.session_finished(lun) self.assertFalse(r) @res_mock.patch_client def test_session_finished_not_existed(self, client, mocked): lun = client.vnx.get_lun() r = client.session_finished(lun) self.assertTrue(r) @res_mock.patch_client def test_migrate_lun_error(self, client, mocked): lun = client.vnx.get_lun() self.assertRaises(storops_ex.VNXMigrationError, client.migrate_lun, src_id=4, dst_id=5) lun.migrate.assert_called_with(5, storops.VNXMigrationRate.HIGH) @res_mock.patch_client def test_verify_migration(self, client, mocked): r = client.verify_migration(1, 2, 'test_wwn') self.assertTrue(r) @res_mock.patch_client def test_verify_migration_false(self, client, mocked): r = client.verify_migration(1, 2, 'fake_wwn') self.assertFalse(r) @res_mock.patch_client def test_cleanup_migration(self, client, mocked): client.cleanup_migration(1, 2) @res_mock.patch_client def test_get_lun_by_name(self, client, mocked): lun = client.get_lun(name='lun_name_test_get_lun_by_name') self.assertEqual(888, lun.lun_id) @res_mock.patch_client def test_delete_lun(self, client, mocked): client.delete_lun(mocked['lun'].name) @res_mock.patch_client def test_delete_smp(self, client, mocked): client.delete_lun(mocked['lun'].name) @res_mock.patch_client def test_delete_lun_not_exist(self, client, mocked): client.delete_lun(mocked['lun'].name) @res_mock.patch_client def test_delete_lun_exception(self, client, mocked): self.assertRaisesRegexp(storops_ex.VNXDeleteLunError, 'General lun delete error.', client.delete_lun, mocked['lun'].name) @res_mock.patch_client def test_enable_compression(self, client, mocked): lun_obj = mocked['lun'] client.enable_compression(lun_obj) lun_obj.enable_compression.assert_called_with(ignore_thresholds=True) @res_mock.patch_client def test_enable_compression_on_compressed_lun(self, client, mocked): lun_obj = mocked['lun'] client.enable_compression(lun_obj) @res_mock.patch_client def test_get_vnx_enabler_status(self, client, mocked): re = client.get_vnx_enabler_status() self.assertTrue(re.dedup_enabled) self.assertFalse(re.compression_enabled) self.assertTrue(re.thin_enabled) self.assertFalse(re.fast_enabled) self.assertTrue(re.snap_enabled) @res_mock.patch_client def test_lun_has_snapshot_true(self, client, mocked): re = client.lun_has_snapshot(mocked['lun']) self.assertTrue(re) @res_mock.patch_client def test_lun_has_snapshot_false(self, client, mocked): re = client.lun_has_snapshot(mocked['lun']) self.assertFalse(re) @res_mock.patch_client def test_create_cg(self, client, mocked): cg = client.create_consistency_group('cg_name') self.assertIsNotNone(cg) @res_mock.patch_client def test_create_cg_already_existed(self, client, mocked): cg = client.create_consistency_group('cg_name_already_existed') self.assertIsNotNone(cg) @res_mock.patch_client def test_delete_cg(self, client, mocked): client.delete_consistency_group('deleted_name') @res_mock.patch_client def test_delete_cg_not_existed(self, client, mocked): client.delete_consistency_group('not_existed') @res_mock.patch_client def test_expand_lun(self, client, _ignore): client.expand_lun('lun', 10, poll=True) @res_mock.patch_client def test_expand_lun_not_poll(self, client, _ignore): client.expand_lun('lun', 10, poll=False) @res_mock.patch_client def test_expand_lun_already_expanded(self, client, _ignore): client.expand_lun('lun', 10) @unittest.skip("Skip until bug #1578986 is fixed") @utils.patch_sleep @res_mock.patch_client def test_expand_lun_not_ops_ready(self, client, _ignore, sleep_mock): self.assertRaises(storops_ex.VNXLunPreparingError, client.expand_lun, 'lun', 10) lun = client.vnx.get_lun() lun.expand.assert_called_once_with(10, ignore_thresholds=True) # Called twice lun.expand.assert_called_once_with(10, ignore_thresholds=True) @res_mock.patch_client def test_create_snapshot(self, client, _ignore): client.create_snapshot('lun_test_create_snapshot', 'snap_test_create_snapshot') lun = client.vnx.get_lun() lun.create_snap.assert_called_once_with('snap_test_create_snapshot', allow_rw=True, auto_delete=False) @res_mock.patch_client def test_create_snapshot_snap_name_exist_error(self, client, _ignore): client.create_snapshot('lun_name', 'snapshot_name') @res_mock.patch_client def test_delete_snapshot(self, client, _ignore): client.delete_snapshot('snapshot_name') @res_mock.patch_client def test_delete_snapshot_delete_attached_error(self, client, _ignore): self.assertRaises(storops_ex.VNXDeleteAttachedSnapError, client.delete_snapshot, 'snapshot_name') @res_mock.patch_client def test_copy_snapshot(self, client, mocked): client.copy_snapshot('old_name', 'new_name') @res_mock.patch_client def test_create_mount_point(self, client, mocked): client.create_mount_point('lun_name', 'smp_name') @res_mock.patch_client def test_attach_mount_point(self, client, mocked): client.attach_snapshot('smp_name', 'snap_name') @res_mock.patch_client def test_detach_mount_point(self, client, mocked): client.detach_snapshot('smp_name') @res_mock.patch_client def test_modify_snapshot(self, client, mocked): client.modify_snapshot('snap_name', True, True) @res_mock.patch_client def test_create_cg_snapshot(self, client, mocked): snap = client.create_cg_snapshot('cg_snap_name', 'cg_name') self.assertIsNotNone(snap) @res_mock.patch_client def test_create_cg_snapshot_already_existed(self, client, mocked): snap = client.create_cg_snapshot('cg_snap_name', 'cg_name') self.assertIsNotNone(snap) @res_mock.patch_client def test_delete_cg_snapshot(self, client, mocked): client.delete_cg_snapshot(cg_snap_name='test_snap') @res_mock.patch_client def test_create_sg(self, client, mocked): client.create_storage_group('sg_name') @res_mock.patch_client def test_create_sg_name_in_use(self, client, mocked): self.assertRaisesRegexp(storops_ex.VNXStorageGroupNameInUseError, 'Storage group sg_name already exists. ' 'Message: ', client.create_storage_group('sg_name'
)) @res_mock.patch_client def test_get_storage_group(self, client, mocked): sg = client.get_storage_group('sg_name') self.assertEqual('sg_name', sg.name) @re
s_mock.patch_client def test_register_initiator(self, client, mocked): host = vnx_common.Host('host_name', ['host_initiator'], 'host_ip') client.register_initiator(mocked['sg'], host, {'host_initiator': 'port_1'}) @res_mock.patch_client def test_register_initiator_exception(self, client, mocked): host = vnx_common.Host('host_name', ['host_initiator'], 'host_ip') client.register_initiator(mocked['sg'], host, {'host_initiator': 'port_1'}) @res_mock.patch_client def test_ping_node(self, client, mocked): self.assertTrue(client.ping_node(mocke
#!/usr/bin/env python import sys import src.json_importing as I import src.data_training as T import src.data_cross_validation as V imp
ort src.extract_feature_multilabel as EML
if __name__ == '__main__': print('Hello, I am Trellearn') jsonFileName = sys.argv[1] cards = I.parseJSON(jsonFileName) X, Y, cv, mlb = EML.extract(cards) V.validateML(X, Y) exit(0)
/usr/share/pyshared/gwibber/lib/gtk/w
idgets.p
y
# CodeIgniter # http://codeigniter.com # # An open source application development framework for PHP # # This content is released under the MIT License (MIT) # # Copyright (c) 2014 - 2015, British Columbia Institute of Technology # # 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 PROVI
DED "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 ACTIO
N OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) # Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) # # http://opensource.org/licenses/MIT MIT License import re import copy from pygments.lexer import DelegatingLexer from pygments.lexers.web import PhpLexer, HtmlLexer __all__ = [ 'CodeIgniterLexer' ] class CodeIgniterLexer(DelegatingLexer): """ Handles HTML, PHP, JavaScript, and CSS is highlighted PHP is highlighted with the "startline" option """ name = 'CodeIgniter' aliases = [ 'ci', 'codeigniter' ] filenames = [ '*.html', '*.css', '*.php', '*.xml', '*.static' ] mimetypes = [ 'text/html', 'application/xhtml+xml' ] def __init__(self, **options): super(CodeIgniterLexer, self).__init__(HtmlLexer, PhpLexer, startinline=True)
import urllib.request, urllib.parse, urllib.error from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1 try: import json as simplejson except ImportError: try: import simplejson except ImportError: from django.utils import simplejson from social_auth.backends import ConsumerBasedOAuth, OAuthBackend, BaseOAuth2 from social_auth.utils import dsa_urlopen class RdioBaseBackend(OAuthBackend): def get_user_id(self, details, response): return response['key'] def get_user_details(self, response): return { 'username': response['username'], 'first_name': response['firstName'], 'last_name': response['lastName'], 'fullname': response['displayName'], }
class RdioOAuth1Backend(RdioBaseBackend): """Rdio OAuth authentication backend""" name = 'rdio-oauth1' EXTRA_DATA = [ ('key', 'rdio_id'), ('icon', 'rdio_icon_url'), ('url', 'rdio_profile_url'), ('username', 'rdio_username'), ('streamRegion', 'rdio_stream_region'), ] @clas
smethod def tokens(cls, instance): token = super(RdioOAuth1Backend, cls).tokens(instance) if token and 'access_token' in token: token = dict(tok.split('=') for tok in token['access_token'].split('&')) return token class RdioOAuth2Backend(RdioBaseBackend): name = 'rdio-oauth2' EXTRA_DATA = [ ('key', 'rdio_id'), ('icon', 'rdio_icon_url'), ('url', 'rdio_profile_url'), ('username', 'rdio_username'), ('streamRegion', 'rdio_stream_region'), ('refresh_token', 'refresh_token', True), ('token_type', 'token_type', True), ] class RdioOAuth1(ConsumerBasedOAuth): AUTH_BACKEND = RdioOAuth1Backend REQUEST_TOKEN_URL = 'http://api.rdio.com/oauth/request_token' AUTHORIZATION_URL = 'https://www.rdio.com/oauth/authorize' ACCESS_TOKEN_URL = 'http://api.rdio.com/oauth/access_token' RDIO_API_BASE = 'http://api.rdio.com/1/' SETTINGS_KEY_NAME = 'RDIO_OAUTH1_KEY' SETTINGS_SECRET_NAME = 'RDIO_OAUTH1_SECRET' def user_data(self, access_token, *args, **kwargs): """Return user data provided""" params = { 'method': 'currentUser', 'extras': 'username,displayName,streamRegion', } request = self.oauth_post_request(access_token, self.RDIO_API_BASE, params=params) response = dsa_urlopen(request.url, request.to_postdata()) json = '\n'.join(response.readlines()) try: return simplejson.loads(json)['result'] except ValueError: return None def oauth_post_request(self, token, url, params): """Generate OAuth request, setups callback url""" if 'oauth_verifier' in self.data: params['oauth_verifier'] = self.data['oauth_verifier'] request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params, http_method='POST') request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token) return request class RdioOAuth2(BaseOAuth2): AUTH_BACKEND = RdioOAuth2Backend AUTHORIZATION_URL = 'https://www.rdio.com/oauth2/authorize' ACCESS_TOKEN_URL = 'https://www.rdio.com/oauth2/token' RDIO_API_BASE = 'https://www.rdio.com/api/1/' SETTINGS_KEY_NAME = 'RDIO_OAUTH2_KEY' SETTINGS_SECRET_NAME = 'RDIO_OAUTH2_SECRET' SCOPE_VAR_NAME = 'RDIO2_PERMISSIONS' EXTRA_PARAMS_VAR_NAME = 'RDIO2_EXTRA_PARAMS' def user_data(self, access_token, *args, **kwargs): params = { 'method': 'currentUser', 'extras': 'username,displayName,streamRegion', 'access_token': access_token, } response = dsa_urlopen(self.RDIO_API_BASE, urllib.parse.urlencode(params)) try: return simplejson.load(response)['result'] except ValueError: return None # Backend definition BACKENDS = { 'rdio-oauth1': RdioOAuth1, 'rdio-oauth2': RdioOAuth2 }
from LSP.plugin.core.typing import Any, Callable from types import MethodType import weakref __all__ = ['weak_method'] # An implementation of weak method borrowed from sublime_lib [1] # # We need it to be able to weak reference bound methods as `weakref.WeakMethod` is not available in # 3.3 runtime. # # The reason this is necessary is explained in the documentation of `weakref.WeakMethod`: # > A custom ref subclass which simulates a weak reference to a bound method (i.e., a method defined # > on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak # > reference cannot keep hold of it. # # [1] https://github.com/SublimeText/sublime_lib/blob/master/st3/sublime_lib/_util/weak_method.py def weak_method(method: Callable) -> Callable: assert isinstance(method, MethodType) self_ref = weakref.ref(method.__self__) function_ref = weakref.ref(method.__func__) def wrapped(*args: Any,
**kwargs: Any) -> Any: self = self_ref() fu
nction = function_ref() if self is None or function is None: print('[lsp_utils] Error: weak_method not called due to a deleted reference', [self, function]) return return function(self, *args, **kwargs) return wrapped
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ """ A placeholder for math functionality that is not implemented in SciPy. """ import warnings warnings.warn("Module is deprecated.", DeprecationWarning) import numpy def is_monotonic(array): """ Does the array increase monotonically? >>> is_monotonic(array((1, 2, 3, 4))) True >>> is_monotonic(array((1, 2, 3, 0, 5))) False This may not be the desired response but: >>> is_monotonic(array((1))) False """ try: min_increment = numpy.amin(array[1:] - array[:-1]) if min_increment >= 0: return True except Exception: return False return False; def brange(min_value, max_value, increment): """ Returns an inclusive version of arange(). The usual arange() give
s: >>> arange(1, 4, 1) array([1, 2, 3]) However brange() returns: >>> brange(1, 4, 1) array([ 1., 2., 3., 4.]) """ return numpy.arange(min_value, max_value + increment / 2.0, increment) def norm(mean, std): """ Returns a single random value from a normal distribution. """ return numpy.random.normal(mean, std) def discrete_std (counts, bin_centers): """ Returns a standard deviation from binned data. """ mean = numpy.sum(counts * bin_centers)/numpy.su
m(counts) return numpy.sqrt((numpy.sum((counts-mean)**2))/len(counts))
#!/usr/bin/env python # Copyright 2016 Battelle Energy Alliance, 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. """ Converts a recipe given in a .cfg file into a full bash shell script which would be similar to what CIVET would end up running. """ from __future__ import unicode_literals, absolute_import import argparse, sys, os import re from RecipeReader import RecipeReader def read_script(filename): top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) script_file = os.path.join(top_dir, filename) with open(script_file, "r") as f: out = f.read() return out def step_functions(recipe): step_cmds = '' for step in recipe["steps"]: step_cmds += "function step_%s\n{\n" % step["position"] for key, value in step["environment"].items(): step_cmds += write_env(key, value, " local") step_cmds += ' local step_name="%s"\n' % step["name"] step_cmds += ' local step_position="%s"\n' % step["position"] script = read_script(step["script"]) for l in script.split('\n'): if l.strip(): step_cmds += ' %s\n' % l else: step_cmds += "\n" step_cmds += "}\nexport -f step_%s\n\n" % step["position"] step_cmds += "function step_exit()\n" step_cmds += '{\n' step_cmds += ' if bash -c $1; then\n' step_cmds += ' printf "\\n$1 passed\\n\\n"\n' step_cmds += ' elif [ "$2" == "True" ]; then\n' step_cmds += ' printf "\\n$1 failed. Aborting\\n\\n"\n' step_cmds += ' exit 1\n' step_cmds += ' else\n' step_cmds += ' printf "\\n$1 failed but continuing\\n\\n"\n' step_cmds += ' fi\n' step_cmds += '}\n\n' # now write out all the functions for step in recipe["steps"]: step_cmds += "step_exit step_%s %s\n" % (step["position"], step["abort_on_failure"]) return step_cmds def write_env(key, value, prefix="export"): return '%s %s="%s"\n' % (prefix, key, re.sub("^BUILD_ROOT", "$BUILD_ROOT", value)) def recipe_to_bash(recipe, base_repo, base_branch, base_sha, head_repo, head_branch, head_sha, pr, push, manual, build_root, moose_jobs, args): script = "#!/bin/bash\n" script += '# Generated by: %s %s\n' % (__file__, ' '.join(args)) script += '# Script for job %s\n' % recipe["filename"] script += '# It is a good idea to redirect stdin, ie "./script.sh < /dev/null"\n' script += '# Be sure to have the proper modules loaded as well.\n' script += '\n\n' script += 'module list\n' script += 'export BUILD_ROOT="%s"\n' % build_root script += 'export MOOSE_JOBS="%s"\n' % moose_jobs script += '\n\n' script += 'export CIVET_RECIPE_NAME="%s"\n' % recipe["name"] script += 'export CIVET_BASE_REPO="%s"\n' % base_repo script += 'export CIVET_BASE_SSH_URL="%s"\n' % base_repo script += 'export CIVET_BASE_REF="%s"\n' % base_branch script += 'export CIVET_BASE_SHA="%s"\n' % base_sha script += 'export CIVET_HEAD_REPO="%s"\n' % head_repo script += 'export CIVET_HEAD_REF="%s"\n' % head_branch script += 'export CIVET_HEAD_SHA="%s"\n' % head_sha script += 'export CIVET_HEAD_SSH_URL="%s"\n' % head_repo script += 'export CIVET_JOB_ID="1"\n' cause_str = "" if pr: cause_str = "Pull Request" elif push: cause_str = "Push" elif manual: cause_str = "Manual" script += 'export CIVET_EVENT_CAUSE="%s"\n' % cause_str script += '\n\n' for source in recipe["global_sources"]: s = read_script(source) script += "# %s\n%s\n" % (source, s) script += "\n\n" for key, value in recipe["global_env"].items(): script += write_env(key, value) script += "\n\n" script += step_functions(recipe) return script def convert_recipe(args): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--recipe", dest="recipe", help="The recipe file to convert.", required=True) parser.add_argument("--output", dest="output", help="Where to write the script to") parser.add_argument("--build-root", dest="build_root", default="/tmp/", help="Where to set BUILD_ROOT") parser.add_argument("--num-jobs", dest="num_jobs", default="4", help="What to set MOOSE_JOBS to") parser.add_argument("--head", nargs=3, dest="head", help="Head repo to work on. Format is: repo branch sha", required=True) parser.add_argument("--base", nargs=3, dest="base", help="Base repo to work on. Format is: repo branch sha", required=True) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--pr", action="store_true") group.add_argument("--push", action="store_true") group.add_argument("--manual", action="store_true") parsed = parser.parse_args(args) dirname = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(dirname) # RecipeReader takes a relative path from the base repo directory real_path = os.path.realpath(parsed.recipe) rel_path = os.path.relpath(rea
l_path, parent_dir) try: reader = RecipeReader(parent_dir, rel_path) recipe = reader.read() except Exception as e: print("Recipe '%s' is not valid: %s" % (real_path, e)) return 1 try: script = recipe_to_bash(recipe, base_repo=parsed.base[0], base_branch=parsed.base[1], base_sha=parsed.base[2], head_repo=parsed.head[0], head_branch=parsed.head[1],
head_sha=parsed.head[2], pr=parsed.pr, push=parsed.push, manual=parsed.manual, build_root=parsed.build_root, moose_jobs=parsed.num_jobs, args=args, ) if parsed.output: with open(parsed.output, "w") as f: f.write(script) else: print(script) except Exception as e: print("Failed to convert recipe: %s" % e) return 1 if __name__ == "__main__": convert_recipe(sys.argv[1:])
""" Test multiword commands ('platform' in this case). """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * class MultiwordCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @no_debug_info_test def test_ambiguous_subcommand(self): self.expect("platform s", error=True, substrs=["ambiguous command 'platform s'. Possible completions:", "\tselect\n", "\tshell\n", "\tsettings\n"]) @no_debug_info_test def test_empty_
subcommand(self): self.expect("platform \"\"", error=True, substrs=["Need to specify a non-empty subcommand."]) @no_debug_info_test def test_help(self): # <multiword> help brings up help. self.expect("platform help", substrs=["Commands to manage and create platforms.",
"Syntax: platform [", "The following subcommands are supported:", "connect", "Select the current platform"])
#!/usr/bin/env python3 # # Copyright (c) 2015-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 governin
g permissions and # limitations under the License. # # # @file #
A Happy command line utility that tests Weave Ping among Weave nodes. # # The command is executed by instantiating and running WeavePing class. # from __future__ import absolute_import from __future__ import print_function import getopt import sys import set_test_path from happy.Utils import * import WeavePing if __name__ == "__main__": options = WeavePing.option() try: opts, args = getopt.getopt(sys.argv[1:], "ho:s:c:tuwqp:i:a:e:n:CE:T:", ["help", "origin=", "server=", "count=", "tcp", "udp", "wrmp", "interval=", "quiet", "tap=", "case", "case_cert_path=", "case_key_path="]) except getopt.GetoptError as err: print(WeavePing.WeavePing.__doc__) print(hred(str(err))) sys.exit(hred("%s: Failed server parse arguments." % (__file__))) for o, a in opts: if o in ("-h", "--help"): print(WeavePing.WeavePing.__doc__) sys.exit(0) elif o in ("-q", "--quiet"): options["quiet"] = True elif o in ("-t", "--tcp"): options["tcp"] = True elif o in ("-u", "--udp"): options["udp"] = True elif o in ("-w", "--wrmp"): options["wrmp"] = True elif o in ("-o", "--origin"): options["client"] = a elif o in ("-s", "--server"): options["server"] = a elif o in ("-c", "--count"): options["count"] = a elif o in ("-i", "--interval"): options["interval"] = a elif o in ("-p", "--tap"): options["tap"] = a elif o in ("-C", "--case"): options["case"] = True elif o in ("-E", "--case_cert_path"): options["case_cert_path"] = a elif o in ("-T", "--case_key_path"): options["case_key_path"] = a else: assert False, "unhandled option" if len(args) == 1: options["origin"] = args[0] if len(args) == 2: options["client"] = args[0] options["server"] = args[1] cmd = WeavePing.WeavePing(options) cmd.start()
#!/usr/bin/env python # -*- coding: utf-8 -*- debug = True REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 0 REDIS_PASSWORD
= '820AEC1BFC5D2C71E06CBF947A3A6191' GUAVA_API_URL = 'http
://localhost:5000'
from sklearn.tree import DecisionTreeClassifier # weak classifier # decision tr
ee (max depth = 2) using scikit-learn class WeakClassifier: # initialize def __init__(self): self.clf = DecisionTreeClassifier(max_depth = 2) # train on dataset (X, y) with distribution weight w def fit(self, X, y, w): self.clf.fit(X, y, sample_weight = w) # predict def predict(self, X): retu
rn self.clf.predict(X)
import time from prometheus_client import Counter, Histogram from prometheus_client import start_http_server from flask import request FLASK_REQUEST_LATENCY = Histogram('flask_request_latency_seconds', 'Flask Request Latency', ['method', 'endpoint']) FLASK_REQUEST_COUNT = Counter('flask_request_count', 'Flask Request Count', ['method', 'endpoint', 'http_status']) def before_request(): request.start_time = time.time() def after_request(response): request_latency = time.time() - request.start_time FLASK_REQUEST_LATENCY.labels(request.method, request.path).observe(request_latency) FLASK_REQUEST_COUNT.labels(request.method, request.path, response.status_code).inc() return response def monitor(app, port=8000, addr=''): app.
before_request(before_request) app.after_request(after_request) start_http_server(port, addr) if __name__ == '__main__': from flask import Flask app = Flask(__name__) monitor(app, p
ort=8000) @app.route('/') def index(): return "Hello" # Run the application! app.run()
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the to
p-level COPYRIGHT file for details. # # SPD
X-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRrcov(RPackage): """rrcov: Scalable Robust Estimators with High Breakdown Point""" homepage = "https://cloud.r-project.org/package=rrcov" url = "https://cloud.r-project.org/src/contrib/rrcov_1.4-7.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/rrcov" version('1.4-7', sha256='cbd08ccce8b583a2f88946a3267c8fc494ee2b44ba749b9296a6e3d818f6f293') depends_on('r@2.10:', type=('build', 'run')) depends_on('r-robustbase@0.92.1:', type=('build', 'run')) depends_on('r-mvtnorm', type=('build', 'run')) depends_on('r-lattice', type=('build', 'run')) depends_on('r-cluster', type=('build', 'run')) depends_on('r-pcapp', type=('build', 'run'))
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible """ Model for testing arithmetic expressions. """ from django.db import models @python_2_unicode_compatible class Number(models.Model): integer = models.BigI
ntegerField(db_column='the_integer') float = models
.FloatField(null=True, db_column='the_float') def __str__(self): return '%i, %.3f' % (self.integer, self.float) class Experiment(models.Model): name = models.CharField(max_length=24) assigned = models.DateField() completed = models.DateField() start = models.DateTimeField() end = models.DateTimeField() class Meta: ordering = ('name',) def duration(self): return self.end - self.start
import socket import os RUN_IN_TOPOLOGY = False TOPOLOGY_FROM_RESOURCE_SERVER = False HOSTNAME_1 = HOSTNAME_2 = HOSTNAME_3 = socket.get
hostname() USE_SSL = False ICAT_HOSTNAME = socket.gethostname() PREEXISTING_ADMIN_PASSWORD = 'rods' # TODO: allow for arbitrary number of remote zones class FEDERATION(object): LOCAL_IRODS_VERSION = (4, 2, 0) REMOTE_IRODS_VERSION = (4, 2, 0) RODSUSER_NAME_PASSWORD_LIST = [('zonehopper', '53CR37')] RODSADMIN_NAME_PASSWORD_LIST = [] IRODS_DIR = '/var/lib/irods/iRODS' LOCAL_ZONE = 'dev' REMOTE_ZONE = 'buntest'
REMOTE_HOST = 'buntest' REMOTE_RESOURCE = 'demoResc' REMOTE_VAULT = '/var/lib/irods/iRODS/Vault' TEST_FILE_SIZE = 4*1024*1024 LARGE_FILE_SIZE = 64*1024*1024 TEST_FILE_COUNT = 300 MAX_THREADS = 16
1, 0, 'Loan Template', None, 1], ['loan_xls_output', 'Loan Output', 'string', None, 'S:\\Prime Brokerage (PB)\\Tools\\Stock Loan Collateral\\ExcelUpload - Cash Entry YYYYMMDD.xlsm', 1, 0, 'Loan Output', None, 1], ['ss_bb_output', 'SS/BB Output', 'string', None, 'S:\\Prime Brokerage (PB)\\Tools\\Stock Loan Collateral\\ss_bb_trd_YYYYMMDD.xlsx', 1, 0, 'SS/BB Output', None, 1], ['base_ccy', 'Base Ccy', 'string', None, 'HKD', 1, 0, 'Base Ccy', None, 1]] def question_marks(st): question_marks = '?' for i in range(0, len(st.split(','))-1): question_marks = question_marks + ",?" return question_marks def db_cur(source = ":memory:"): # sqlite3.register_adapter(decimal.Decimal, adapt_decimal) # sqlite3.register_converter("DECTEXT", convert_decimal) conn = sqlite3.connect(source, detect_types=sqlite3.PARSE_DECLTYPES) conn.row_factory = sqlite3.Row cur = conn.cursor() return conn, cur def create_tbl(cur, tbl_name, header, arr = None, index_arr = None): cur.execute("""select count(*) FROM sqlite_master WHERE type='table' AND name = '%s' """ % (tbl_name)) tbl_exists = cur.fetchone() if tbl_exists[0] == 0: cur.execute("CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " );") if index_arr is not None: for index in index_arr: cur.execute("CREATE INDEX " + tbl_name + "_" + index + " ON " + tbl_name + " (" + index + ");") if arr is not None: cur.executemany("INSERT INTO " + tbl_name + " VALUES ("+question_marks(header)+")", arr) return def getTRSUnderlying(acm_ins): acm_und_ins = None bbticker = "" for acm_leg in acm_ins.Legs(): if acm_leg.PayLeg() == False: acm_und_ins = acm_leg.FloatRateReference() break return acm_und_ins def getUndInstrumentBBTicker(acm_ins): bbticker = '' acm_und_ins = getTRSUnderlying(acm_ins) if acm_und_ins != None: for aliase in acm_und_ins.Aliases(): if aliase.Type().Name() == 'BB_TICKER': bbticker = aliase.Alias().strip() break return bbticker def getGroupTradeRef(external_ref): groupTradeRef = None strSql = """ select trdnbr, t.time from trade t, instrument i, party a, party c, portfolio pf, leg l, instrument u where t.insaddr = i.insaddr and i.instype = 'TotalReturnSwap' and t.status not in ('Void', 'Simulated') and t.acquirer_ptynbr = a.ptynbr and t.counterparty_ptynbr = c.ptynbr and t.prfnbr = pf.prfnbr and add_info(t, 'External Reference') = '%s' and i.insaddr = l.insaddr and l.float_rate = u.insaddr order by t.time, trdnbr """ % (external_ref) print strSql res = ael.asql(strSql) columns, buf = res for table in buf: for row in table: groupTradeRef = row[0] break return groupTradeRef def getFirstTRS(external_ref, und_insaddr): strSql = """select i.insid from trade t, instrument i, leg l where i.insaddr = t.insaddr and i.instype = 'TotalReturnSwap' and t.status not in ('Void', 'Simulated') and add_info(t, 'External Reference') = '%s' and i.insaddr = l.insaddr and l.payleg = 'No' and l.type = 'Total Return' and add_info(t, 'Trd Pos Closed') ~= 'Yes' and l.float_rate = %s and t.trdnbr = t.trx_trdnbr""" % (external_ref, str(und_insaddr)) #print strSql rs = ael.asql(strSql) columns, buf = rs insid = '' for table in buf: for row in table: insid = str(row[0]).strip() break if insid == '': return None acm_ins = acm.FInstrument[insid] return acm_ins def getTotalTradeQuantity(external_ref, und_insaddr, asofdate): acm_ins = getFirstTRS(external_ref, und_insaddr) if acm_ins == None: return None #print "instrument='%s' and status <> 'Void' and status <> 'Simulated'" % acm_ins.Name() #acm_trds = acm.FTrade.Select("instrument='%s' and status <> 'Void' and status <> 'Simulated' and tradeTime <= '%s'" % (acm_ins.Name(), asofdate.add_days(1))) acm_trds = acm.FTrade.Select("instrument='%s' and status <> 'Void' and status <> 'Simulated' and tradeTime < '%s'" % (acm_ins.Name(), asofdate.add_days(1))) acm_trd = None if acm_trds != None: for acm_trd in acm_trds: if acm_trd.TrxTrade() != None: if acm_trd.Oid() == acm_trd.TrxTrade().Oid(): break else: return None total_quantity = 0.0 if acm_trd.TrxTrade() == None: if acm_trd.Status() not in ('Void', 'Simulated'): total_quantity = total_quantity + acm_trd.Quantity() return abs(total_quantity) else: return None elif acm_trd.Oid() == acm_trd.TrxTrade().Oid(): if acm_trd.Status() not in ('Void', 'Simulated'): total_quantity = total_quantity + acm_trd.Quantity() # find all other trade #acm_trs_trds = acm.FTrade.Select("trxTrade=%s and tradeTime <= '%s'" % (acm_trd.Oid(), asofdate.add_days(1))) acm_trs_trds = acm.FTrade.Select("trxTrade=%s and tradeTime < '%s'" % (acm_trd.Oid(), asofdate.add_days(1))) for acm_trs_trd in acm_trs_trds: # add this to handle tradeTime lag 8 hours from gmt ael_trd_date = ael.date(str(acm_trs_trd.TradeTime())[0:10]) if ael_trd_date >= asofdate.add_days(1): continue if acm_trs_trd.Oid() != acm_trs_trd.TrxTrade().Oid() and \ acm_trs_trd.Status() not in ('Void', 'Simulated') and \ acm_trs_trd.Instrument().InsType() == 'TotalReturnSwap': total_quantity = total_quantity + acm_trs_trd.Quantity() #print total_quantity ''' if total_quantity == 0.0: return None else: return abs(total_quantity) ''' return -total_quantity else: return -total_quantity def getUnderlyingPrice(dt, ael_und_ins, currclspricemkt, histclspricemkt): try: if dt == ael.date_today(): cls_price = ael_und_ins.used_price(dt, ael_und_ins.curr.insid, 'Last', 0, currclspricemkt) else: cls_price = ael_und_ins.used_price(dt, ael_und_ins.curr.insid, 'Close', 0, histclspricemkt) except: #cls_price = ael_und_ins.used_price(dt, ael_und_ins.curr.insid, 'Last', 0, currclspricemkt) cls_price = 0.0 return cls_price def csv_to_arr(csv_file, start=0, has_header=True, delim=',', encoding='utf-8'): arr = [] reader
= [] if "http" in csv_file: response = requests.get(csv_file) text = response.content.decode(encoding) else: text = open(csv_file, 'rU') reader = csv.reader(text, delimiter=delim) arr = list(reader) arr = list(zip(*arr)) arr = [x for x in arr if any(x)] arr = list(zip(*arr))
header = "" if has_header: header = ','.join(arr[start]) arr = arr[start+1:] return re.sub(r"[\*\.#/\$%\"\(\)& \_-]", "", header), arr else: return arr[start:] return def getFx(dt, fm_ccy, to_ccy, currclspricemkt, histclspricemkt): if fm_ccy == 'CNY': fm_ccy = 'CNH' if to_ccy == 'CNY': to_ccy = 'CNH' ins_fm_ccy = ael.Instrument[fm_ccy] ins_to_ccy = ael.Instrument[to_ccy] ins_usd = ael.Instrument['USD'] try: if dt == ael.date_today(): #fx_rate = ins_fm_ccy.used_price(dt, ins_to_ccy.insid, 'Last', 0, currclspricemkt) fm_usd_rate = ins_fm_ccy.used_p
from gbdxtools im
port Interface gbdx = None def go(): print(gbdx.task_registry.list()) print(gbdx.task_registry.get_definition('HelloGBDX')) if __name__ == "__main__": gbdx = Interface() go
()
"""This module provides the main functionality of cfbackup """ from __future__ import print_function import sys import argparse import json import CloudFlare # https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records class CF_DNS_Records(object): """ commands for zones manipulation """ def __init__(self, ctx): self._ctx = ctx def run(self): """ run - entry point for DNS records manipulations """ cmd = self._ctx.command if cmd == "show": self.show() else: sys.exit("Command " + cmd + " not implemened for zones") def show(self): """Show CF zones""" # print("Show DSN records") try: records = self._all_records() except CloudFlare.exceptions.CloudFlareAPIError as e: exit('/zones %d %s - api call failed' % (e, e)) if not self._ctx.pretty: print(json.dumps(records, indent=4)) return records_by_type = {} types = {} for rec in records: if not records_by_type.get(rec["type"]): types[rec["type"]] = 0 records_by_type[rec["type"]] = [] types[rec["type"]] += 1 records_by_type[rec["type"]].append(rec) for t in sorted(list(types)): for rec in records_by_type[t]: # print(json.dumps(rec, indent=4)) print("Type: {}".format(rec["type"])) print("Name: {}".format(rec["name"])) print("Content: {}".format(rec["content"])) print("TTL: {}{}".format( rec["ttl"], " (auto)" if str(rec["ttl"]) == "1" else "", )) print("Proxied: {}".format(rec["proxied"])) print("Auto: {}".format(rec["meta"]["auto_added"])) print("") print("") print("-------------------") print("Records stat:") print("-------------------") print("{0: <11} {1: >4}".format("<type>", "<count>")) for t in sorted(list(types)): print("{0: <11} {1: >4}".format(t, types[t])) print("-------------------") print("{0: <11} {1: >4}".format("Total:", len(records))) def _all_records(self): cf = CloudFlare.CloudFlare() zones = cf.zones.get(params={'name': self._ctx.zone_name, 'per_page': 1}) if len(zones) == 0: exit('No zones found') zone_id = zones[0]['id'] cf_raw = CloudFlare.CloudFlare(raw=True) page = 1 records = [] while True: raw_results = cf_raw.zones.dns_records.get( zone_id, params={'per_page':100, 'page':page}, ) total_pages = raw_results['result_info']['total_pages'] result = raw_results['result'] for rec in result: records.append(rec) if page == total_pages: break page += 1 return records # https://api.cloudflare.com/#zone-list-zones class CF_Zones(object): """ commands for zones manipulation """ def __init__(self, ctx): self._ctx = ctx def run(self): """ run - entry point for zones manipulations """ cmd = self._ctx.command if cmd == "show": self.show() else: sys.exit("Command " + cmd + " not implemened for zones") def show(self): """Show CF zones""" # print("Show cf zones") try: zones = self._all_zones() except CloudFlare.exceptions.CloudFlareAPIError as e: exit('/zones %d %s - api call failed' % (e, e)) if not self._ctx.pretty: print(json.dumps(zones, indent=4)) return for z in zones:
print("Zone: {0: <16} NS: {1}".format( z["name"], z["name_servers"][0], )) for ns in z["name
_servers"][1:]: print(" {0: <16} {1}".format("", ns)) def _all_zones(self): cf = CloudFlare.CloudFlare(raw=True) if self._ctx.zone_name: raw_results = cf.zones.get(params={ 'name': self._ctx.zone_name, 'per_page': 1, 'page': 1, }) return raw_results['result'] page = 1 domains = [] while True: raw_results = cf.zones.get(params={'per_page':5, 'page':page}) total_pages = raw_results['result_info']['total_pages'] zones = raw_results['result'] for z in zones: domains.append(z) if page == total_pages: break page += 1 return domains COMMANDS = [ "show", # "restore" ] OBJECT_ENTRYPOINT = { "zones": CF_Zones, "dns": CF_DNS_Records, } def main(): """Main entry""" parser = argparse.ArgumentParser( prog="cfbackup", description='Simple Cloudflare backup tool.', ) parser.add_argument( "command", choices=[x for x in COMMANDS], help="command", ) subparsers = parser.add_subparsers( help='Object of command', dest="object" ) parser_zones = subparsers.add_parser("zones") parser_zones.add_argument( "--pretty", action='store_true', help="show user friendly output", ) parser_zones.add_argument( "-z", "--zone-name", help="optional zone name", ) parser_dns = subparsers.add_parser("dns") parser_dns.add_argument( "-z", "--zone-name", required=True, help="required zone name", ) parser_dns.add_argument( "--pretty", action='store_true', help="show user friendly output", ) args = parser.parse_args() OBJECT_ENTRYPOINT[args.object](args).run()
#!/usr/bin/env python #-*- coding: utf-8 -*- # # Documents # """ Documents """ from __future__ import
absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals i
mport os import inspect from . import pyarduino this_file_path = os.path.abspath(inspect.getfile(inspect.currentframe())) def get_plugin_path(): this_folder_path = os.path.dirname(this_file_path) plugin_path = os.path.dirname(this_folder_path) return plugin_path def get_packages_path(): plugin_path = get_plugin_path() packages_path = os.path.dirname(plugin_path) return packages_path def get_stino_user_path(): packages_path = get_packages_path() user_path = os.path.join(packages_path, 'User') stino_user_path = os.path.join(user_path, 'Stino') return stino_user_path def get_preset_path(): plugin_path = get_plugin_path() preset_path = os.path.join(plugin_path, 'preset') return preset_path def get_user_preset_path(): stino_user_path = get_stino_user_path() preset_path = os.path.join(stino_user_path, 'preset') return preset_path def get_user_menu_path(): stino_user_path = get_stino_user_path() preset_path = os.path.join(stino_user_path, 'menu') return preset_path def get_settings(): settings = pyarduino.base.settings.get_arduino_settings() return settings def get_arduino_info(): arduino_info = pyarduino.arduino_info.get_arduino_info() return arduino_info def get_i18n(): i18n = pyarduino.base.i18n.I18N() return i18n
'''MobileNetV2 in PyTorch. See the paper "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" for more details. ''' import torch import torch.nn as nn import torch.nn.functional as F class Block(nn.Module): '''expand + depthwise + pointwise''' def __init__(self, in_planes, out_planes, expansion, stride): super(Block, self).__init__() self.stride = stride planes = expansion * in_planes self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, groups=planes, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False) self.bn3 = nn.BatchNorm2d(out_planes) self.shortcut = nn.Sequential() if stride == 1 and in_planes != out_planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_planes), ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out = out + self.shortcut(x) if self.stride==1 else out return out class MobileNetV2(nn.Module): # (expansion, out_planes, num_blocks, stride) cfg = [(1, 16, 1, 1), (6, 24, 2, 1), # NOTE: change stride 2 -> 1 for CIFAR10 (6, 32, 3, 2), (6, 64, 4, 2), (6, 96, 3, 1), (6, 160, 3, 2), (6, 320, 1, 1)] def __init__(self, num_classes=10): super(MobileNetV2, self).__init__() # NOTE: change conv1 stride 2 -> 1 for CIFAR10 self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(32) self.layers = self._make_layers(in_planes=32) self.conv2 = nn.Conv2d(320, 1280, kernel_size=1, stride=1, padding=0, bias=False) self.bn2 = nn.BatchNorm2d(1280) self.linear = n
n.Linear(1280, num_classes) def _make_layers(self, in_planes): layers = [] for expansion, out_planes, num_blocks, stride in self.cfg: strides = [stride] + [1]*(num_blocks-1) for stride in strides: layers.append(Block(in_planes, out_planes, expansion, stride)) in_planes = o
ut_planes return nn.Sequential(*layers) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.layers(out) out = F.relu(self.bn2(self.conv2(out))) # NOTE: change pooling kernel_size 7 -> 4 for CIFAR10 out = F.avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def test(): net = MobileNetV2() x = torch.randn(2,3,32,32) y = net(x) print(y.size()) # test()
# # 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 logging import os import stat import subprocess import sys import time import yaml class ConfigurationError(Exception): pass def configure_waf_haproxy_cp(logger, run_dir, mgmt_ip, haproxy_cp_ip): sh_file = "{}/waf_set_haproxy_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S")) logger.debug("Creating script file %s", sh_file) with open(sh_file, "w") as f: f.write(r'''#!/usr/bin/expect -f set login "centos" set addr {mgmt_ip} set pw "centos" set retry 0 set max 20 while {{ $retry < $max }} {{ sleep 5 spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $login@$addr set timeout 10 expect "yes/no" {{ send "yes\r" expect "*?assword:" {{ send "$pw\r"; break }} }} "*?assword:" {{ send "$pw\r"; break }} set retry [ expr $retry+1 ] if {{ $retry == $m
ax }} {{ puts "Configuration timed out." exit 1 }} }} expect "]$ " send "sudo su\r" expect "]# " send "echo \"<VirtualHost *:80>\r" send " AddDefaultCharset UTF-8\r" send " ProxyPreserveHost On\r" send " ProxyRequests off\r" send " ProxyVia Off\r" send " ProxyPass / http://{haproxy_cp_ip}:5000/\r" send " ProxyPassReverse / http://{haproxy_cp_ip}:5000/\r" send " </VirtualHost>\" > /etc/httpd/conf.d/waf_proxy.conf\r" expect "]# " send "echo \"<IfModule mod
_security2.c>\r" send " IncludeOptional modsecurity.d/owasp-modsecurity-crs/modsecurity_crs_10_setup.conf\r" send " IncludeOptional modsecurity.d/owasp-modsecurity-crs/base_rules/*.conf\r\r" send " SecRuleEngine On\r" send " SecRequestBodyAccess On\r" send " SecResponseBodyAccess On\r" send " SecDebugLog /var/log/httpd/modsec-debug.log\r" send " SecDebugLogLevel 3\r" send "</IfModule>\" > /etc/httpd/conf.d/mod_security.conf\r" expect "]# " send "systemctl stop httpd\r" expect "]# " send "systemctl start httpd\r" expect "]# " '''.format(mgmt_ip=mgmt_ip, haproxy_cp_ip=haproxy_cp_ip)) os.chmod(sh_file, stat.S_IRWXU) rc = subprocess.call(sh_file, shell=True) if rc != 0: raise ConfigurationError("HAProxy add waf config failed: {}".format(rc)) def configure_haproxy_add_waf(logger, run_dir, haproxy_mgmt_ip, waf_cp_ip, waf_server_name): sh_file = "{}/haproxy_add_waf_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S")) logger.debug("Creating script file %s", sh_file) with open(sh_file, "w") as f: f.write(r'''#!/usr/bin/expect -f set login "centos" set addr {mgmt_ip} set pw "centos" set retry 0 set max 20 while {{ $retry < $max }} {{ sleep 5 spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $login@$addr set timeout 10 expect "yes/no" {{ send "yes\r" expect "*?assword:" {{ send "$pw\r"; break }} }} "*?assword:" {{ send "$pw\r"; break }} set retry [ expr $retry+1 ] if {{ $retry == $max }} {{ puts "Configuration timed out." exit 1 }} }} expect "]$ " send "sudo su\r" expect "]# " send "grep \"server {waf_server_name} {waf_cp_ip}\" /etc/haproxy/haproxy.cfg && echo \"Already configured\" && exit 0\r" expect {{ "]$ " {{ exit }} "]# " }} send "sed -i \'s/\\(.*WAF list.*\\)/\\1\\n server {waf_server_name} {waf_cp_ip}:80 check/g\' /etc/haproxy/haproxy.cfg\r" expect "]# " send "systemctl reload haproxy\r" expect "]# " '''.format(mgmt_ip=haproxy_mgmt_ip, waf_cp_ip=waf_cp_ip, waf_server_name=waf_server_name)) os.chmod(sh_file, stat.S_IRWXU) rc = subprocess.call(sh_file, shell=True) if rc != 0: raise ConfigurationError("HAProxy add waf config failed: {}".format(rc)) def configure_haproxy_remove_waf(logger, run_dir, haproxy_mgmt_ip, waf_server_name): sh_file = "{}/haproxy_remove_httpd_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S")) logger.debug("Creating script file %s", sh_file) with open(sh_file, "w") as f: f.write(r'''#!/usr/bin/expect -f set login "centos" set addr {mgmt_ip} set pw "centos" set retry 0 set max 20 while {{ $retry < $max }} {{ sleep 5 spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $login@$addr set timeout 10 expect "yes/no" {{ send "yes\r" expect "*?assword:" {{ send "$pw\r"; break }} }} "*?assword:" {{ send "$pw\r"; break }} set retry [ expr $retry+1 ] if {{ $retry == $max }} {{ puts "Configuration timed out." exit 1 }} }} expect "]$ " send "sudo su\r" expect "]# " send "sed -i \'/server {waf_server_name}/d\' /etc/haproxy/haproxy.cfg\r" expect "]# " send "systemctl reload haproxy\r" expect "]# " '''.format(mgmt_ip=haproxy_mgmt_ip, waf_server_name=waf_server_name)) os.chmod(sh_file, stat.S_IRWXU) rc = subprocess.call(sh_file, shell=True) if rc != 0: raise ConfigurationError("HAProxy remove waf config failed: {}".format(rc)) def main(argv=sys.argv[1:]): try: parser = argparse.ArgumentParser() parser.add_argument("yaml_cfg_file", type=argparse.FileType('r')) parser.add_argument("--dry-run", action="store_true") parser.add_argument("--quiet", "-q", dest="verbose", action="store_false") args = parser.parse_args() run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift") if not os.path.exists(run_dir): os.makedirs(run_dir) log_file = "{}/rift_waf_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S")) logging.basicConfig(filename=log_file, level=logging.DEBUG) logger = logging.getLogger() ch = logging.StreamHandler() if args.verbose: ch.setLevel(logging.DEBUG) else: ch.setLevel(logging.INFO) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) except Exception as e: print("Got exception:{}".format(e)) raise try: dry_run = args.dry_run yaml_str = args.yaml_cfg_file.read() logger.debug("Input YAML file: %s", yaml_str) yaml_cfg = yaml.load(yaml_str) logger.debug("Input YAML cfg: %s", yaml_cfg) # Check if this is post scale out trigger def find_cp_ip(vnfr_list, vnfd_name, cp_name): for vnfr in vnfr_list: if vnfd_name in vnfr['name']: for cp in vnfr['connection_points']: logger.debug("Connection point: %s", format(cp)) if cp_name in cp['name']: return cp['ip_address'] raise ValueError("Could not find vnfd %s connection point %s", vnfd_name, cp_name) def find_mgmt_ip(vnfr_list, vnfd_name): for vnfr in vnfr_list: if vnfd_name in vnfr['name']: return vnfr['rw_mgmt_ip'] raise ValueError("Could not find vnfd %s mgmt ip", vnfd_name) def find_vnfr(vnfr_list, vnfd_name): for vnfr in vnfr_list: if vnfd_name in vnfr['name']: return vnfr raise ValueError("Could not find vnfd %s", vnfd_name) haproxy_cp_ip = find_cp_ip(yaml_cfg['vnfrs_others'], "haproxy_vnfd", "cp0") haproxy_mgmt_ip = find_mgmt_ip(yaml_cfg['vnfrs_others'], "haproxy_vnfd") waf_cp_ip = find_cp_ip(yaml_cfg['vnfrs_in_group'], "waf_vnfd", "cp0") waf_mgmt_ip = find_mgmt_ip(yaml_cfg['vnfrs_in_group'], "waf_vnfd") waf_vnfr = find_vnfr(yaml_cfg['vnfrs_in_gro
# Mostly from http://peterdowns.com/posts/first-time-with-pypi.html from distutils.core import setup setup( name = 'pmdp', packages = ['pmdp'], version = '0.3', description = 'A poor man\'s data pipeline', author = 'Dan Goldin', author_email = 'dangoldin@gmail.com', url = 'https://github.com/dangoldin/poor-mans-data-pipeline', download_url = 'https://github.com/dangoldin/poor-mans-data-pipeline/tarball/0.3', keywords = ['data', 'data-pipeline'], cl
assifiers = [], )
to statistics file verbose = 0 obstruents = {'b':'B', 'd':'D', 'g':'G'} nasals = ['m', 'n', 'N'] # Vocales vowels = ['a', 'e', 'i', 'o', 'u'] # Semivocales semivowels = ['%', '#', '@', '$', '&', '!', '*', '+', '-', '3'] # Voiced consonants voiced = ['b', 'B', 'd', 'D', 'g', 'G', 'm', 'n', 'N', '|', 'J', 'r', 'R'] # Track the number of utterances numUtterances = 0 # Track the number of words numWords = 0 #wordsPerUtterance = [] phonemesPerWord = [] def interVocalicRules(sent): newSent = sent # Create all the dipthongs that occur between words newSent = newSent.replace('a i', '- ') newSent = newSent.replace('a u', '+ ') # Do I indicate vowel lengthening? # newSent = newSent.replace('a a', 'aa ') newSent = newSent.replace('e i', '* ') # newSent = newSent.replace('e e', 'ee ') newSent = newSent.replace('i a', '% ') newSent = newSent.replace('i e', '# ') newSent = newSent.replace('i o', '@ ') # newSent = newSent.replace('i i', 'ii ') newSent = newSent.replace('o i', '3 ') # newSent = newSent.replace('o o', 'oo ') # This is not a dipthong replacement but it still needs to happen: # lo ultimo = [lultimo] newSent = newSent.replace('o u', 'u ') newSent = newSent.replace('u a', '& ') newSent = newSent.replace('u e', '$ ') newSent = newSent.replace('u i', '! ') # newSent = newSent.replace('u u', 'uu ') # Avoid creating onsets that are illegal newSent = newSent.replace(' nt','n t') newSent = newSent.replace(' nR','n R') newSent = newSent.replace(' zl','z l') newSent = newSent.replace(' zR','z R') newSent = newSent.replace(' ts','t s') newSent = newSent.replace(' tl','t l') newSent = newSent.replace(' tR','t R') newSent = newSent.replace(' nd','n d') newSent = newSent.replace(' ks','k s') newSent = newSent.replace(' kl','k l') # Turn b/d/g's into B/D/G's where appropriate strList = list(newSent) i = 0 prev = None for symbol in strList: if symbol in obstruents: if not prev or prev in nasals: i += 1 continue else: strList[i] = obstruents[symbol] if symbol in voiced: if prev == 's': strList[i-1] = 'z' prev = symbol i += 1 newSent = "".join(strList) return newSent def sententialRules(sentence): # Apply rules between words, like when a [b] occurs between vowels, turn it into a [B] # Vowels together.. a aser = aser # Apply rule for two vowels being together.. si aqui = s(ia dipthong)ki... # Split the sentence into chunks based on pauses. # This distinction exists because: chunks = sentence.split('[/]') # This has to be done here because I allow [/] to be remain up until this point # for the purpose of knowing where boundaries occur, but we don't want to count [/] newChunkList = [] for chunk in chunks: #wordsPerUtterance.append(len(chunk.split())) globals()["numWords"] += len(chunk.split()) newChunk = interVocalicRules(chunk) if verbose == 1: print newChunk newChunkList.append(newChunk) return newChunkList def main(): dictFile = "Spanish/dicts/dict_converted.txt" chaDir = "Spanish/cha_files/" file = open(dictFile, 'r') lines = file.readlines() file.close() # Word bank is a dictionary - lookup by its key retrieves its IPA translation word = {} # Split by whitespace since that's how it's set up for line in lines: x = line.split() word[x[0].lower()] = x[1] keyErrors = open("Spanish/dicts/keyErrors.txt", "w") outFile = open("Spanish/Spanish-phon.txt", 'w') outFileOrig = open("Spanish/Spanish-ortho.txt", 'w') for fileName in sorted(glob.glob(os.path.join(chaDir, '*.cha'))): # Skip file if it's not below 20 months if fileName.startswith(tuple([chaDir + str(28),chaDir + str(36)])): continue if verbose == 1: print fileName file = open(fileName, 'r') lines = file.readlines() file.close() #file = open(fileName.replace('.cha', '_ipa.txt'), 'w') for line in lines: # Only look at child-directed speech(from INV or PAR) if line.startswith('*INV') or line.startswith('*PAR') or line.startswith('*TEA') or line.startswith('*FAT'): if verbose == 1: print 'Original line: ' + line # Split on pauses to separate utterances and count them #numUtterances += len(line.split('[/]')) # Split the sentence into individual words words = line.split() # Build the IPA-translated sentence ipaSentence = "" # Look up individual words for x in words[1:]: # Ignore punctuation if x == '.' or x == '?' or x == '!': continue outFileOrig.write(x + ' ') # Need to make some character substitions to make dictionary search work x = re.sub('é','}',x) x = re.sub('á','{',x) x = re.sub('í','<',x) x = re.sub('ó','>',x) x = re.sub('ú','}',x) x = re.sub('ñ','|',x) x = re.sub('ü','=',x) x = re.sub(':','',x) x = re.sub('<.+>','',x) try: ipaSentence += word[x.lower()] ipaSentence += " " except KeyError: keyErrors.write("KeyError with: " + x.lower() + "\n") continue outFileOrig.write('\n') newChunks = sententialRules(ipaSentence) ipaSentence = "" for chunk in newChunks: ipaSentence += chunk ipaSentence += " " newChunks = ipaSentence.split() ipaSentence = "" for chunk in newChunks: ipaSentence += chunk ipaSentence += " " # Remove trailing whitespace ipaSentence = ipaSentence.rstrip() # Calculate phonemes per word ipaWords = ipaSentence.split() phonemesInWord = 0 for ipaWord in ipaWords: phonemesInWord += len(ipaWord) # Number of original words is the length of the "words" variable beyond the first # part that indicates the speaker(i.e. *INV:) gl
obals()["phonemesPerWord"].append(float(float(phonemesInWord) / float(len(words[1:]
)))) if verbose == 1: print ipaSentence if len(ipaSentence) > 0: outFile.write(ipaSentence + '\n') globals()["numUtterances"] += 1 #file.write(ipaSentence + '\n') #file.close() outFile.close() keyErrors.close() if verbose == 1: statisticsFile = open("statistics.txt", 'w') statisticsFile.write("Number of utterances: " + str(globals()["numUtterances"]) + "\n") statisticsFile.write("Number of words by tokens: " + str(globals()["numWords"]) + "\n") statisticsFile.write("Number of words by type: " + str(len(word)) + "\n") averageWordsPerUtterance = float(float(globals()["numWords"]) / float(numUtterances)) statisticsFile.write("Words per utterance on average: " + str(averageWordsPerUtterance) + "\n") averagePhonemesPerWord = float(float(sum(globals()["phonemesPerWord"])) / float(len(globals()["phonemesPerWord"]))) statisticsFile.write("Phonemes per word on average: " + str(averagePhonemesPerWord)) statisticsFil
#!/usr/bin/env python # # Copyright (c) 2013 In-Q-Tel, Inc/Lab41, 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. """ Created on 19 October 2013 @author: Lab41 Helper functions for creating visualizations """ import array import matplotlib.pyplot as plt import numpy as np import matplotlib def visualize_scatter(counts, codes, data, codebook, num_clusters, xlabel="", ylabel="", title=""): """ Generates a 2-d scatter plot visualization of two feature data for :param counts: dictionary of counts for the number of observations pairs for each cluster :param codes: list of codes for each observation row in the order returned by the original query :param data: list of observations returned from query in their original order :param codebook: the coordinates of the centroids :param num_clusters: number of specified clusters up to 8 :param xlabel: a label for the x axis (Default: None) :param ylabel: a label for the y axis (Default: None) """ if num_clusters > 8: print "Visualize scatter only supports up to 8 clusters" return num_features = 2 list_arrays = list() list_arr_idx = array.array("I", [0, 0, 0]) for idx in range(num_clusters): list_arrays.append(np.zeros((counts[idx], num_features))) for i, j in zip(codes, data): list_arrays[i][list_arr_idx[i]][0] = j[0] list_arrays[i][list_arr_idx[i]][1] = j[1] list_arr_idx[i] += 1 #plot the clusters first as relatively larger circles plt.scatter(codebook[:,0], codebook[:,1], color='orange', s=
260) colors = ['red', 'blue', 'green', 'purple', 'cyan', 'black', 'brown', 'grey'] for idx in range(num_clusters): plt.scatter(list_ar
rays[idx][:,0], list_arrays[idx][:,1], c=colors[idx]) plt.title(title) plt.ylabel(ylabel) plt.xlabel(xlabel) #plt.show() plt.savefig('/home/docker/foo.png') plt.close()
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual autho
rs. # # 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 an Outlook Registry parser.""" from plaso.lib import event from plaso.parsers.winreg_plugins import interface __author__ = 'David Nides (david.nides@gmail.com)' class OutlookSearchMRUPlugin(interface.KeyPlugin): """Windows Registry plugin parsing Outlook Search MRU keys.""" NAME = 'winreg_outlook_mru' DESCRIPTION = 'PST Paths' REG_KEYS = [ u'\\Software\\Microsoft\\Office\\15.0\\Outlook\\Search', u'\\Software\\Microsoft\\Office\\14.0\\Outlook\\Search'] # TODO: The catalog for Office 2013 (15.0) contains binary values not # dword values. Check if Office 2007 and 2010 have the same. Re-enable the # plug-ins once confirmed and OutlookSearchMRUPlugin has been extended to # handle the binary data or create a OutlookSearchCatalogMRUPlugin. # Registry keys for: # MS Outlook 2007 Search Catalog: # '\\Software\\Microsoft\\Office\\12.0\\Outlook\\Catalog' # MS Outlook 2010 Search Catalog: # '\\Software\\Microsoft\\Office\\14.0\\Outlook\\Search\\Catalog' # MS Outlook 2013 Search Catalog: # '\\Software\\Microsoft\\Office\\15.0\\Outlook\\Search\\Catalog' REG_TYPE = 'NTUSER' def GetEntries(self, key, **unused_kwargs): """Collect the values under Outlook and return event for each one.""" value_index = 0 for value in key.GetValues(): # Ignore the default value. if not value.name: continue # Ignore any value that is empty or that does not contain an integer. if not value.data or not value.DataIsInteger(): continue # TODO: change this 32-bit integer into something meaningful, for now # the value name is the most interesting part. text_dict = {} text_dict[value.name] = '0x{0:08x}'.format(value.data) if value_index == 0: timestamp = key.last_written_timestamp else: timestamp = 0 yield event.WinRegistryEvent( key.path, text_dict, timestamp=timestamp, source_append=': {0:s}'.format(self.DESCRIPTION)) value_index += 1
# -*- coding: utf-8 -*- import warnings from django import forms from django.contrib.admin.sites import site from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.contrib.staticfiles.templatetags.staticfiles import static from django.core.urlresolvers import reverse from django.db import models from django.template.loader import render_to_string from django.utils.safestring import mark_safe from filer.models import Folder from filer.utils.compatibility import truncate_words from filer.utils.model_label import get_model_label class AdminFolderWidget(ForeignKeyRawIdWidget): choices = None input_type = 'hidden' is_hidden = False def render(self, name, value, attrs=None): obj = self.obj_for_value(value) css_id = attrs.get('id') css_id_folder = "%s_folder" % css_id css_id_description_txt = "%s_description_txt" % css_id if attrs is None: attrs = {} related_url = None if value: try: folder = Folder.objects.get(pk=value) related_url = folder.get_admin_directory_listing_url_path() except Exception: pass if not related_url: related_url = reverse('admin:filer-directory_listing-last') params = self.url_parameters() params['select_folder'] = 1 if params: url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in list(params.items())]) else: url = '' if 'class' not in attrs: # The JavaScript looks for this hook. attrs['class'] = 'vForeignKeyRawIdAdminField' super_attrs = attrs.copy() hidden_input = super(ForeignKeyRawIdWidget, self).render(name, value, super_attrs) # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. context = { 'hidden_input': hidden_input, 'lookup_url': '%s%s' % (related_url, url), 'lookup_name': name, 'span_id': css_id_description_txt, 'object': obj, 'clear_id': '%s_clear' % css_id, 'descid': css_id_description_txt, 'noimg': 'filer/icons/nofile_32x32.png', 'foldid': css_id_folder, 'id': css_id, } html = render_to_string('admin/filer/widgets/admin_folder.html', context) return mark_safe(html) def label_for_value(self, value): obj = self.obj_for_value(value) return '&nbsp;<strong>%s</strong>' % truncate_words(obj, 14) def obj_for_value(self, value): try: key = self.rel.get_related_field().name obj = self.rel.to._default_manager.get(**{key: value})
except: obj = None return obj class Media(object): js = (static('filer/js/addons/popup_handling.js'),
) class AdminFolderFormField(forms.ModelChoiceField): widget = AdminFolderWidget def __init__(self, rel, queryset, to_field_name, *args, **kwargs): self.rel = rel self.queryset = queryset self.limit_choices_to = kwargs.pop('limit_choices_to', None) self.to_field_name = to_field_name self.max_value = None self.min_value = None kwargs.pop('widget', None) forms.Field.__init__(self, widget=self.widget(rel, site), *args, **kwargs) def widget_attrs(self, widget): widget.required = self.required return {} class FilerFolderField(models.ForeignKey): default_form_class = AdminFolderFormField default_model_class = Folder def __init__(self, **kwargs): # We hard-code the `to` argument for ForeignKey.__init__ dfl = get_model_label(self.default_model_class) if "to" in kwargs.keys(): # pragma: no cover old_to = get_model_label(kwargs.pop("to")) if old_to != dfl: msg = "%s can only be a ForeignKey to %s; %s passed" % ( self.__class__.__name__, dfl, old_to ) warnings.warn(msg, SyntaxWarning) kwargs['to'] = dfl super(FilerFolderField, self).__init__(**kwargs) def formfield(self, **kwargs): # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = { 'form_class': self.default_form_class, 'rel': self.rel, } defaults.update(kwargs) return super(FilerFolderField, self).formfield(**defaults) def south_field_triple(self): "Returns a suitable description of this field for South." # We'll just introspect ourselves, since we inherit. from south.modelsinspector import introspector field_class = "django.db.models.fields.related.ForeignKey" args, kwargs = introspector(self) # That's our definition! return (field_class, args, kwargs)
""" Copyright 2016 Andrea McIntosh 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 I
S" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views import generic from .models import Question, Choice class IndexView(generic.ListView): template_name = "polls/
index.html" context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except: return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations class Basic4d(Basic3d): def _calculate(self, x, y=None, weights=None, tensor=None, n_elem=1e7, is_training=False): return super(Basic4d, self)._calculate(x, y, weights, tensor, n_elem / 10, is_training) class CNN(Basic4d): def __init__(self, *args, **kwargs): self.height, self.width = kwargs.pop("height", None), kwargs.pop("width", None) super(CNN, self).__init__(*args, **kwargs) self._name_appendix = "CNN" self._generator_base = Generator4d self.conv_activations = None self.n_filters = self.filter_sizes = self.poolings = None def init_model_param_settings(self): super(CNN, self).init_model_param_settings() self.conv_activations = self.model_param_settings.get("conv_activations", "relu") def init_model_structure_settings(self): super(CNN, self).init_model_structure_settings() self.n_filters = self.model_structure_settings.get("n_filters", [32, 32]) self.filter_sizes = self.model_structure_settings.get("filter_sizes", [(3, 3), (3, 3)]) self.poolings = self.model_structure_settings.get("poolings", [None, "max_pool"]) if not len(self.filter_sizes) == len(self.poolings) == len(self.n_filters): raise ValueError("Length of filter_sizes, n_filters & pooling should be the same") if isinstance(self.conv_activations, str): self.conv_activations = [self.conv_activations] * len(self.filter_sizes) def init_from_data(self, x, y, x_test, y_test, sample_weights, names): if self.height is None or self.width is None: assert len(x.shape) == 4, "height and width are not provided, hence len(x.shape) should be 4" self.height, self.width = x.shape[1:3] if len(x.shape) == 2: x = x.reshape(len(x), self.height, self.width, -1) else: assert self.height == x.shape[1], "height is set to be {}, but {} found".format(self.height, x.shape[1]) assert self.width == x.shape[2], "width is set to be {}, but {} found".format(self.height, x.shape[2]) if x_test is not None and len(x_test.shape) == 2: x_test = x_test.reshape(len(x_test), self.height, self.width, -1) super(CNN, self).init_from_data(x, y, x_test, y_test, sample_weights, names) def _define_input_and_placeholder(self): self._is_training = tf.placeholder
(tf.bool, name="
is_training") self._tfx = tf.placeholder(tf.float32, [None, self.height, self.width, self.n_dim], name="X") self._tfy = tf.placeholder(tf.float32, [None, self.n_class], name="Y") def _build_model(self, net=None): self._model_built = True if net is None: net = self._tfx for i, (filter_size, n_filter, pooling) in enumerate(zip( self.filter_sizes, self.n_filters, self.poolings )): net = tf.layers.conv2d(net, n_filter, filter_size, padding="same") net = tf.layers.batch_normalization(net, training=self._is_training) activation = self.conv_activations[i] if activation is not None: net = getattr(Activations, activation)(net, activation) net = tf.layers.dropout(net, training=self._is_training) if pooling is not None: net = tf.layers.max_pooling2d(net, 2, 2, name="pool") fc_shape = np.prod([net.shape[i].value for i in range(1, 4)]) net = tf.reshape(net, [-1, fc_shape]) super(CNN, self)._build_model(net)
# Initialize App Engine and import the default settings (DB backend, etc.). # If you want to use a different backend you have to remove all occurences # of "djangoappengine" from this file. from djangoappengine.settings_base import * from private_settings import SECRET_KEY import os # Activate django-dbindexer for the default database DATABASES['native'] = DATAB
ASES['default'] DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'} AUTOLOAD_SITECONF = 'indexes' INSTALLED_APPS = ( # 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.markup', 'djangotoolbox', 'autoload', 'dbindexer', "simpleblog.content", # djangoappengine should c
ome last, so it can override a few manage.py commands 'djangoappengine', ) MIDDLEWARE_CLASSES = [ # This loads the index definitions, so it has to come first 'autoload.middleware.AutoloadMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] if not DEBUG: # Put the stats middleware after autoload MIDDLEWARE_CLASSES.insert( 1, 'google.appengine.ext.appstats.recording.AppStatsDjangoMiddleware') TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', ) # This test runner captures stdout and associates tracebacks with their # corresponding output. Helps a lot with print-debugging. TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner' TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),) ROOT_URLCONF = 'simpleblog.urls' if DEBUG: STATIC_URL = "/devstatic/" else: STATIC_URL = "/static/" STATICFILES_DIRS = ("staticfiles", ) STATIC_ROOT = "static_collected" PRE_DEPLOY_COMMANDS = ("collectstatic", ) LOGIN_URL = "/login" LOGIN_REDIRECT_URL = "/"
import utils import re import subprocess #regexes duration_regex = re.compile('Duration:\s*(?P<time>\d{2}:\d{2}:\d{2}.\d{2})') stream_regex = re.compile('Stream #(?P<stream_id>\d+:\d+)(\((?P<language>\w+)\))?: (?P<type>\w+): (?P<format>[\w\d]+)') crop_regex = re.compile('crop=(?P<widt
h>\d+):(?P<height>\d+):(?P<x>\d+):(?P<y>\d+)') # detect crop settings def detect_crop(src): proc = subprocess.Popen(['ffmpeg', '-i', src, '-t', str(100), '-filter:v', 'cropdetect', '-f', 'null', '-'], stderr=subprocess.PIPE) stdout, stderr = proc.communicate() crops = crop_regex.findall(stderr) return max(set(crops), key=crops.count) # detect duration def detect_duration(src): proc = subprocess.Popen(['ffmpeg', '-i', src], stderr=subprocess.PIPE) st
dout, stderr = proc.communicate() match = duration_regex.search(stderr) duration_str = match.group('time') duration_secs = utils.timestring_to_seconds(duration_str) return (duration_str, duration_secs) # detects stream IDs def detect_streams(src): proc = subprocess.Popen(['ffmpeg', '-i', src], stderr=subprocess.PIPE) stdout, stderr = proc.communicate() streams = [] for m in stream_regex.finditer(stderr): streams.append({ 'id': m.group('stream_id'), 'lang': m.group('language'), 'type': m.group('type'), 'fmt': m.group('format') }) return streams
elf._create_element(u'ins', content, attrs) # inline def a(self, content, attrs=None): """Create a element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'a', content, attrs) def em(self, content, attrs=None): """Create em element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'em', content, attrs) def strong(self, content, attrs=None): """Create strong element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'strong', content, attrs) def abbr(self, content, attrs=None): """Create abbr element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'abbr', content, attrs) def acronym(self, content, attrs=None): """Create acronym element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'acronym', content, attrs) def bdo(self, content, attrs=None): """Create bdo element. Keyword arguments:
content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'bdo', content, attrs) def cite(self, content, attrs=None): """Create cite element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None)
""" return self._create_element(u'cite', content, attrs) def code(self, content, attrs=None): """Create code element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'code', content, attrs) def dfn(self, content, attrs=None): """Create dfn element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'dfn', content, attrs) def kbd(self, content, attrs=None): """Create kbd element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'kbd', content, attrs) def q(self, content, attrs=None): """Create q element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'q', content, attrs) def samp(self, content, attrs=None): """Create samp element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'samp', content, attrs) def span(self, content, attrs=None): """Create span element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'span', content, attrs) def sub(self, content, attrs=None): """Create sub element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'sub', content, attrs) def sup(self, content, attrs=None): """Create sup element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'sup', content, attrs) def var(self, content, attrs=None): """Create var element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'var', content, attrs) def ruby(self, content, title, attrs=None): """Create ruby element. Keyword arguments: content -- some text title -- ruby title text attrs -- dict object that contains attributes (default None) """ return u'<ruby><rp>(</rp><rb>{0}</rb><rt>{1}</rb><rp>)</rp></ruby>'.format(content, title) # list def ol(self, content, attrs=None): """Create ol element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'ol', content, attrs) def start_ol(self, attrs=None): """Create start tag of ol element. Keyword arguments: attrs -- dict object that contains attributes (default None) """ return self._create_start_tag(u'ol', attrs) def end_ol(self): """Create end tag of ol element.""" return self._create_end_tag(u'ol') def ul(self, content, attrs=None): """Create ul element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'ul', content, attrs) def start_ul(self, attrs=None): """Create start tag of ul element. Keyword arguments: attrs -- dict object that contains attributes (default None) """ return self._create_start_tag(u'ul', attrs) def end_ul(self): """Create end tag of ul element.""" return self._create_end_tag(u'ul') def li(self, content, attrs=None): """Create li element. Keyword arguments: content -- some text or list contains some texts attrs -- dict object that contains attributes (default None) """ if isinstance(content, list) or isinstance(content, tuple): result = list() for li in content: result.append(self._create_element(u'li', li, attrs)) return u''.join(result) else: return self._create_element(u'li', content, attrs) def dl(self, content, attrs=None): """Create dl element. Keyword arguments: content -- some text or dict contains some texts attrs -- dict object that contains attributes (default None) """ if isinstance(content, dict): result = list() result.append(self.start_dl(attrs)) for di in content.keys(): result.append(self.dt(di)) result.append(self.dd(content[di])) result.append(self.end_dl()) return u''.join(result) else: return self._create_element(u'dl', content, attrs) def start_dl(self, attrs=None): """Create start tag of dl element. Keyword arguments: attrs -- dict object that contains attributes (default None) """ return self._create_start_tag(u'dl', attrs) def end_dl(self): """Create end tag of p element.""" return self._create_end_tag(u'dl') def dt(self, content, attrs=None): """Create dt element. Keyword arguments: content -- some text attrs -- dict object that contains attributes (default None) """ return self._create_element(u'dt', content, attrs) def dd(self, content, attrs=None): """Create dd element. Keyword arguments: content -- some text attrs -- dict object that contains att
# -*- coding: utf-8 -*- import logging from speaklater import make_lazy_string from quokka.modules.a
ccounts.models import User logger = logging.getLogger() def lazy_str_setting(key, default=None): from flask import current_app return make_lazy_string( lambda: current_app.config.get(key, default) ) def get_current_user(): from flask.ext.securi
ty import current_user try: if not current_user.is_authenticated(): return None except RuntimeError: # Flask-Testing will fail pass try: return User.objects.get(id=current_user.id) except Exception as e: logger.warning("No user found: %s" % e.message) return None
from .req import Req class Records(Req): def __init__(self, url, email, secret): super().__init__(url=url, email=email, secret=secret) def get(self, zone_id, layer='default'): return self.do_get("/zones/{}/{}/records".format(zone_id, layer)) def create(self, zone, layer, name, ttl, rtype, data, priority=0): url = "/zones/{}/{}/records".format(zone, layer) data = { 'layer': layer, 'name': name, 'ttl': ttl, 'record_type': rtype, 'value': data, 'priority': priority } return self.do_post(url, data=data) def delete(self
, zone, layer, record_id): url = "/zones/{}/{}/records/{}".format(zone, layer, record_id) return self.do_delete(url) def update(self, zone, layer, record_id, **params): url = "/zones/{}/{}/records/{}".fo
rmat(zone, layer, record_id) return self.do_put(url, data=params)
# crop.py # Derek Groenendyk # 2/15/2017 # reads input data from Excel workbook from collections import OrderedDict import logging import numpy as np import os import sys from cons2.cu import CONSUMPTIVE_USE # from utils import excel logger = logging.getLogger('crop') logger.setLevel(logging.DEBUG) class CROP(object): """docstring for CROP""" def __init__(self, shrtname, longname, crop_type, mmnum, directory, sp): self.sname = shrtname self.lname = longname self.crop_type = crop_type self.directory = directory if self.crop_type == 'ANNUAL': self.mmnum = mmnum if sp.et_method == 'fao': self.stages = {} self.kc = {} # self.read_cropdev() self.read_stages() self.read_kc() elif sp.et_method == 'scs': self.get_nckc() self.get_ckc() # methods = { # 'ANNUAL': ANNUAL, # 'PERENNIAL': PERENNIAL # } # self.cu = methods[crop_type](sp, self) self.cu = CONSUMPTIVE_USE(sp, self) def read_cropdev(self): try: infile = open(os.path.join(self.directory,'data','crop_dev_coef.csv'),'r') except TypeError: logger_fn.critical('crop_dev_coef.csv file not found.') raise lines = infile.readlines() infile.close() # sline = lines[1].split(',') # cname = sline[0].replace(' ','') # temp_cname = cname stage_flag = False kc_flag = False switch = False i = 1 # while i < len(lines): while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') # print(cname,self.sname) if cname != '': if cname == self.sname: # print(i) if not switch: stage = sline[1].lower() self.stages[stage] = np.array([float(item) for item in sline[2:6]]) # print(1.0-np.sum(self.stages[stage])) stage_flag = True else: num = int(sline[1].replace(' ','')) self.kc[num] = np.array([float(item) for item in sline[2:5]]) kc_flag = True else: if switch: break i += 1 switch = True i += 1 if stage_flag == False or kc_flag == False: logger.critical('Crop, ' + self.sname + ', not found in crop_dev_coef.csv.') # include site?? raise def read_stages(self): try: infile = open(os.path.join(self.directory,'data','fao_crop_stages.csv'),'r') except TypeError: logger_fn.critical('fao_crop_stages.csv file not found.') raise lines = infile.readlines() infile.close() flag = False i = 1 while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') if cname != '': if cname == self.sname: stage = sline[1].lower() self.stages[stage] = np.array([float(item) for item in sline[2:6]]) flag = True else: if flag: break flag = False i += 1 if not flag: logger.critical('Crop, ' + self.sname + ', not found in fao_crop_stages.csv.') # include site?? raise def read_kc(self): try: infile = open(os.path.join(self.directory,'data','fao_crop_coef.csv'),'r') except TypeError: logger_fn.critical('fao_crop_coef.csv file not found.') raise lines = infile.readlines() infile.close() flag = False i = 1 while i < len(lines): sline = lines[i].split(',') cname = sline[0].replace(' ','') if cname != '': if cname == self.sname: num = int(sline[1].replace(' ','')) self.kc[num] = np.array([float(item) for item in sline[2:5]]) flag = True else: if flag: break flag = False i += 1 if not flag: logger.critical('Crop, ' + self.sname + ', not found in fao_crop_coef.csv.') # include site?? raise def get_nckc(self): """ Reads in crop coefficients. Parameters ---------- name: string
Name of the crop Returns ------- nckc: list List of crop coefficients
""" try: infile = open(os.path.join(self.directory,'data','scs_crop_stages.csv'),'r') except TypeError: logger.critical('scs_crop_stages.csv file not found.') raise lines = infile.readlines() infile.close() nckca = [float(item) for item in lines[0].split(',')[1:]] nckcp = [float(item) for item in lines[1].split(',')[1:]] if self.crop_type == 'PERENNIAL': self.nckc= nckcp else: self.nckc = nckca def get_ckc(self): """ Reads in crop coefficients. Parameters ---------- name: string Name of the crop Returns ------- ckc: list List of crop coefficients """ try: infile = open(os.path.join(self.directory,'data','scs_crop_coef.csv'),'r') except TypeError: logger_fn.critical('scs_crop_coef.csv file not found.') raise else: lines = infile.readlines() infile.close() if self.crop_type == 'PERENNIAL': end = 26 else: end = 22 for line in lines: sline = line.split(',') sline[-1] = sline[-1][:-1] # print(sline[0],self.sname) if sline[0] == self.sname: vals = [float(item) for item in sline[1:end]] self.ckc = vals break
"""Auto-generated file, do not edit by hand. BS metadata""" from ..phonemetadata imp
ort NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BS = PhoneMetadata(id='BS', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='9\\d\\d', possible_length=(3,)), toll_free=PhoneNumberDesc(national_number_pattern='9(?:1[19]|88)', example_number='911', possible_length=(3,)), emergency=PhoneNumberDesc(national_number_pattern='91[19]', example_number='911', poss
ible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='9(?:1[19]|88)', example_number='911', possible_length=(3,)), short_data=True)
return res def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") r
eturn res def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. In Numpy versions <= 1.8 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned. Parameters ---------- a : array_like Array containing numbers whose sum is desired
. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the sum is computed. The default is to compute the sum of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. .. versionadded:: 1.8.0 out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. The casting of NaN to integer can yield unexpected results. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `mean` or `sum` methods of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- y : ndarray or numpy scalar See Also -------- numpy.sum : Sum across array propagating NaNs. isnan : Show which elements are NaN. isfinite: Show which elements are not NaN or +/-inf. Notes ----- If both positive and negative infinity are present, the sum will be Not A Number (NaN). Numpy integer arithmetic is modular. If the size of a sum exceeds the size of an integer accumulator, its value will wrap around and the result will be incorrect. Specifying ``dtype=double`` can alleviate that problem. Examples -------- >>> np.nansum(1) 1 >>> np.nansum([1]) 1 >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a) 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) >>> np.nansum([1, np.nan, np.inf]) inf >>> np.nansum([1, np.nan, np.NINF]) -inf >>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present nan """ a, mask = _replace_nan(a, 0) return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def nanprod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the product of array elements over a given axis treating Not a Numbers (NaNs) as zero. One is returned for slices that are all-NaN or empty. .. versionadded:: 1.10.0 Parameters ---------- a : array_like Array containing numbers whose sum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the product is computed. The default is to compute the product of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. The casting of NaN to integer can yield unexpected results. keepdims : bool, optional If True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- y : ndarray or numpy scalar See Also -------- numpy.prod : Product across array propagating NaNs. isnan : Show which elements are NaN. Notes ----- Numpy integer arithmetic is modular. If the size of a product exceeds the size of an integer accumulator, its value will wrap around and the result will be incorrect. Specifying ``dtype=double`` can alleviate that problem. Examples -------- >>> np.nanprod(1) 1 >>> np.nanprod([1]) 1 >>> np.nanprod([1, np.nan]) 1.0 >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanprod(a) 6.0 >>> np.nanprod(a, axis=0) array([ 3., 2.]) """ a, mask = _replace_nan(a, 1) return np.prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Compute the arithmetic mean along the specified axis, ignoring NaNs. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the means are computed. The default is to compute the mean of the flattened array. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for inexact inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passe
is invite was sent to from_actor = models.StringProperty() # ref - who sent this invite for_actor = models.StringProperty() # ref - invited to what, probs a channel status = models.StringProperty(default="active") # enum - active, blocked key_template = 'invite/%(code)s' class KeyValue(CachingModel): actor = models.StringProperty() keyname = models.StringProperty()
value = models.TextProperty() key_template = 'keyvalue/%(actor)s/%(keyname)s' class OAuthAccessToken(CachingModel): key_ = models.StringProperty() # the token key
secret = models.StringProperty() # the token secret consumer = models.StringProperty() # the consumer this key is assigned to actor = models.StringProperty() # the actor this key authenticates for created_at = properties.DateTimeProperty(auto_now_add=True) # when this was created perms = models.StringProperty() # read / write / delete key_template = 'oauth/accesstoken/%(key_)s' def to_string(self): token = oauth.OAuthToken(self.key_, self.secret) return token.to_string() class OAuthConsumer(CachingModel): key_ = models.StringProperty() # the consumer key secret = models.StringProperty() # the consumer secret actor = models.StringProperty() # the actor who owns this status = models.StringProperty() # active / pending / inactive type = models.StringProperty() # web / desktop / mobile commercial = models.IntegerProperty() # is this a commercial key? app_name = models.StringProperty() # the name of the app this is for, # to be displayed to the user created_at = properties.DateTimeProperty(auto_now_add=True) key_template = 'oauth/consumer/%(key_)s' def url(self): return '/api/keys/%s' % self.key_ class OAuthNonce(CachingModel): nonce = models.StringProperty() # the nonce consumer = models.StringProperty() # the consumer this nonce is for token = models.StringProperty() # the token this nonce is for created_at = properties.DateTimeProperty(auto_now_add=True) # when this was created class OAuthRequestToken(CachingModel): key_ = models.StringProperty() # the token key secret = models.StringProperty() # the token secret consumer = models.StringProperty() # the consumer this key is assigned to actor = models.StringProperty() # the actor this key authenticates for authorized = models.IntegerProperty() # has the actor authorized this token? created_at = properties.DateTimeProperty(auto_now_add=True) # when this was created perms = models.StringProperty() # read / write / delete key_template = 'oauth/requesttoken/%(key_)s' def to_string(self): token = oauth.OAuthToken(self.key_, self.secret) return token.to_string() class Presence(CachingModel): """This represents all the presence data for an actor at a moment in time. extra: status - string; message (like an "away message") location - string; TODO(tyler): Consider gps / cell / structured data availability - string; TODO(tyler): Define structure """ actor = models.StringProperty() # The actor whose presence this is updated_at = properties.DateTimeProperty(auto_now_add=True) # The moment we got the update uuid = models.StringProperty() extra = properties.DictProperty() # All the rich presence # TODO(termie): can't do key_template here yet because we include # current and history keys :/ class Task(CachingModel): actor = models.StringProperty() # ref - the owner of this queue item action = models.StringProperty() # api call we are iterating through action_id = models.StringProperty() # unique identifier for this queue item args = models.StringListProperty() # *args kw = properties.DictProperty() # *kw expire = properties.DateTimeProperty() # when our lock will expire progress = models.StringProperty() # a string representing the offset to # which we've progressed so far created_at = properties.DateTimeProperty(auto_now_add=True) key_template = 'task/%(actor)s/%(action)s/%(action_id)s' class Relation(CachingModel): owner = models.StringProperty() # ref - actor nick relation = models.StringProperty() # what type of relationship this is target = models.StringProperty() # ref - actor nick key_template = 'relation/%(relation)s/%(owner)s/%(target)s' class Stream(DeletedMarkerModel): """ extra: see api.stream_create() """ owner = models.StringProperty() # ref title = models.StringProperty() type = models.StringProperty() slug = models.StringProperty() read = models.IntegerProperty() # TODO: document this write = models.IntegerProperty() extra = properties.DictProperty() key_template = 'stream/%(owner)s/%(slug)s' def is_public(self): return self.read == PRIVACY_PUBLIC def is_restricted(self): return self.read == PRIVACY_CONTACTS def keyname(self): """Returns the key name""" return self.key().name() class StreamEntry(DeletedMarkerModel): """ extra : title - location - icon - content - entry_stream - entry_stream_type - entry_title - entry_uuid - comment_count - """ stream = models.StringProperty() # ref - the stream this belongs to owner = models.StringProperty() # ref - the actor who owns the stream actor = models.StringProperty() # ref - the actor who wrote this entry = models.StringProperty() # ref - the parent of this, # should it be a comment uuid = models.StringProperty() created_at = properties.DateTimeProperty(auto_now_add=True) extra = properties.DictProperty() key_template = '%(stream)s/%(uuid)s' def url(self, with_anchor=True, request=None, mobile=False): if self.entry: # TODO bad? slug = self.entry.split("/")[-1] anchor = "#c-%s" % self.uuid else: # TODO(termie): add slug property slug = self.uuid anchor = "" path = "/%s/%s" % ('presence', slug) if with_anchor: path = "%s%s" % (path, anchor) return actor_url(_get_actor_urlnick_from_nick(self.owner), _get_actor_type_from_nick(self.owner), path=path, request=request, mobile=mobile) def keyname(self): """Returns the key name""" return self.key().name() def title(self): """ build a title for this entry, for a presence entry it will just be the title, but for a comment it will look like: Comment from [commenter nick] on [entry title] by [nick] Comment from [commenter nick] on [entry title] by [nick] to #[channel name] """ if not self.is_comment(): return self.extra.get('title') template = "Comment from %(actor)s on %(entry_title)s by %(entry_actor)s" actor = _get_actor_urlnick_from_nick(self.actor) entry_title = self.extra.get('entry_title') entry_actor = _get_actor_urlnick_from_nick(self.extra.get('entry_actor')) entry_owner_nick = util.get_user_from_topic(self.entry) entry_type = _get_actor_type_from_nick(entry_owner_nick) v = {'actor': actor, 'entry_title': entry_title, 'entry_actor': entry_actor, } if entry_type == 'channel': template += ' to #%(channel)s' channel = _get_actor_urlnick_from_nick(entry_owner_nick) v['channel'] = channel return template % v def is_comment(self): return (self.entry != None) def is_channel(self): return self.owner.startswith('#') def entry_actor(self): if self.entry: return util.get_user_from_topic(self.entry) return None class Subscription(CachingModel): """this represents a topic, usually a stream, that a subscriber (usually an inbox) would like to receive updates to """ topic = models.StringProperty() # ref - the strea
########################################################################## # # Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. # Copyright (c) 2011-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 CONTRAC
T, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF TH
E USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## from __future__ import with_statement import IECore import Gaffer import GafferUI ## A dialogue which allows a user to edit the parameters of an # IECore.Op instance and then execute it. class OpDialogue( GafferUI.Dialogue ) : def __init__( self, opInstance, title=None, sizeMode=GafferUI.Window.SizeMode.Manual, **kw ) : if title is None : title = IECore.CamelCase.toSpaced( opInstance.typeName() ) GafferUI.Dialogue.__init__( self, title, sizeMode=sizeMode, **kw ) self.__node = Gaffer.ParameterisedHolderNode() self.__node.setParameterised( opInstance ) frame = GafferUI.Frame() frame.setChild( GafferUI.NodeUI.create( self.__node ) ) self._setWidget( frame ) self.__cancelButton = self._addButton( "Cancel" ) self.__cancelButtonConnection = self.__cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ) ) executeLabel = "OK" with IECore.IgnoredExceptions( KeyError ) : executeLabel = opInstance.userData()["UI"]["buttonLabel"].value self.__executeButton = self._addButton( executeLabel ) self.__executeButtonConnection = self.__executeButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ) ) self.__opExecutedSignal = Gaffer.Signal1() ## A signal called when the user has pressed the execute button # and the Op has been successfully executed. This is passed the # result of the execution. def opExecutedSignal( self ) : return self.__opExecutedSignal ## Causes the dialogue to enter a modal state, returning the result # of executing the Op, or None if the user cancelled the operation. Any # validation or execution errors will be reported to the user and return # to the dialogue for them to cancel or try again. def waitForResult( self, **kw ) : # block our button connection so we don't end up executing twice with Gaffer.BlockedConnection( self.__executeButtonConnection ) : while 1 : button = self.waitForButton( **kw ) if button is self.__executeButton : result = self.__execute() if result is not None : return result else : return None def __execute( self ) : try : self.__node.setParameterisedValues() result = self.__node.getParameterised()[0]() self.opExecutedSignal()( result ) ## \todo Support Op userData for specifying closing of Dialogue? self.close() return result except : GafferUI.ErrorDialogue.displayException( parentWindow=self ) return None def __buttonClicked( self, button ) : if button is self.__executeButton : self.__execute() else : self.close()
: John Dennis <jdennis@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # 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 <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------- # Module exports __all__ = ['log_mgr', 'root_logger', 'standard_logging_setup', 'IPA_ROOT_LOGGER_NAME', 'ISO8601_UTC_DATETIME_FMT', 'LOGGING_FORMAT_STDERR', 'LOGGING_FORMAT_STDOUT', 'LOGGING_FORMAT_FILE'] #------------------------------------------------------------------------------- import sys import re import copy from log_manager import LogManager, parse_log_level #------------------------------------------------------------------------------- # Our root logger, all loggers will be descendents of this. IPA_ROOT_LOGGER_NAME = 'ipa' # Format string for time.strftime() to produce a ISO 8601 date time # formatted string in the UTC time zone. ISO8601_UTC_DATETIME_FMT = '%Y-%m-%dT%H:%M:%SZ' # Logging format string for use with logging stderr handlers LOGGING_FORMAT_STDERR = 'ipa: %(levelname)s: %(message)s' # Logging format string for use with logging stdout handlers LOGGING_FORMAT_STDOUT = '[%(asctime)s %(name)s] <%(levelname)s>: %(message)s' # Logging format string for use with logging file handlers LOGGING_FORMAT_FILE = '\t'.join([ '%(asctime)s', '%(process)d', '%(threadName)s', '%(name)s', '%(levelname)s', '%(message)s', ]) # Used by standard_logging_setup() for console message LOGGING_FORMAT_STANDARD_CONSOLE = '%(name)-12s: %(levelname)-8s %(message)s' # Used by standard_logging_setup() for file message LOGGING_FORMAT_STANDARD_FILE = '%(asctime)s %(levelname)s %(message)s' #------------------------------------------------------------------------------- class IPALogManager(LogManager): ''' Subclass the LogManager to enforce some IPA specfic logging conventions. * Default to timestamps in UTC. * Default to ISO 8601 timestamp format. * Default the message format. ''' log_logger_level_config_re = re.compile(r'^log_logger_level_(debug|info|warn|warning|error|critical|\d+)$') def __init__(self, configure_state=None): ''' :parameters: configure_state Used by clients of the log manager to track the configuration state, may be any object. ''' super(IPALogManager, self).__init__(IPA_ROOT_LOGGER_NAME, configure_state) def configure_from_env(self, env, configure_state=None): ''' Read the loggger configuration from the Env config. The following items may be configured: Logger Levels *log_logger_XXX = comma separated list of regexps* Logger levels can be explicitly specified for specific loggers as opposed to a global logging level. Specific loggers are indiciated by a list of regular expressions bound to a level. If a logger's name matches the regexp then it is assigned that level. The keys in the Env config must begin with "log_logger_level\_" and then be followed by a symbolic or numeric log level, for example:: log_logger_level_debug = ipapython\.dn\..* log_logger_level_35 = ipalib\.plugins\.dogtag The first line says any logger belonging to the ipapython.dn module will have it's level configured to debug. The second line say the ipa.plugins.dogtag logger will be configured to level 35. Note: logger names are a dot ('.') separated list forming a path in the logger tree. The dot character is also a regular expression metacharacter (matches any character) therefore you will usually need to escape the dot in the logger names by preceeding it with a backslash. The return value of this function is a dict with the following format: logger_regexps List of (regexp, level) tuples :parameters: env Env object configuration values are read from. configure_state If other than None update the log manger's configure_state variable to this object. Clients of the log manager can use configure_state to track the state of the log manager. ''' logger_regexps = [] config = {'logger_regexps' : logger_regexps, } for attr in ('debug', 'verbose'): value = getattr(env, attr, None) if value is not None: config[attr] = value for attr in list(env): # Get logger level configuration match = IPALogManager.log_logger_level_config_re.search(attr) if match: value = match.group(1) level = parse_log_level(value) value = getattr(env, attr) regexps = re.split('\s*,\s*', value) # Add the regexp, it maps to the configured level for regexp in regexps: logger_regexps.append((regexp, level)) continue self.configure(config, configure_state) return config def create_log_handlers(self, configs, logger=None, configure_state=None): 'Enforce some IPA specific configurations' configs = copy.copy(configs) for cfg in configs: if not 'time_zone_converter' in cfg: cfg['time_zo
ne_converter'] = 'utc' if not 'datefmt' in cfg: cfg['datefmt'] = ISO8601_UTC_DATETIME_FMT if not 'format' in cfg:
cfg['format'] = LOGGING_FORMAT_STDOUT return super(IPALogManager, self).create_log_handlers(configs, logger, configure_state) #------------------------------------------------------------------------------- def standard_logging_setup(filename=None, verbose=False, debug=False, filemode='w', console_format=LOGGING_FORMAT_STANDARD_CONSOLE): handlers = [] # File output is always logged at debug level if filename is not None: file_handler = dict(name='file', filename=filename, filemode=filemode, permission=0o600, level='debug', format=LOGGING_FORMAT_STANDARD_FILE) handlers.append(file_handler) if log_mgr.handlers.has_key('console'): log_mgr.remove_handler('console') level = 'error' if verbose: level = 'info' if debug: level = 'debug' console_handler = dict(name='console', stream=sys.stderr, level=level, format=console_format) handlers.append(console_handler) # default_level must be debug becuase we want the file handler to # always log at the debug level. log_mgr.configure(dict(default_level='debug', handlers=handlers), configure_state='standard') return log_mgr.root_logger #------------------------------------------------------------------------------- # Single shared instance of log manager # # By default always starts with stderr console handler at error level # so messages generated before logging is fully configured have some # place to got and won't get lost. log_mgr = IPALogManager() log_mgr.configure(dict(default_level='error', handlers=[dict(name='console',
option1=foo\n") # Check that we get a TypeError when setting non-string values # in an existing section: self.assertRaises(TypeError, cf.set, "sect", "option1", 1) self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0) self.assertRaises(TypeError, cf.set, "sect", "option1", object()) self.assertRaises(TypeError, cf.set, "sect", "option2", 1) self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0) self.assertRaises(TypeError, cf.set, "sect", "option2", object()) def test_add_section_default_1(self): cf = self.newconfig() self.assertRaises(ValueError, cf.add_section, "default") def test_add_section_default_2(self): cf = self.newconfig() self.assertRaises(ValueError, cf.add_section, "DEFAULT") class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase): allow_no_value = True class TestChainMap(unittest.TestCase): def test_issue_12717(self): d1 = dict(red=1, green=2) d2 = dict(green=3, blue=4) dcomb = d2.copy() dcomb.update(d1) cm = ConfigParser._Chainmap(d1, d2) self.assertIsInstance(cm.keys(), list) self.assertEqual(set(cm.keys()), set(dcomb.keys())) # keys() self.assertEqual(set(cm.values()), set(dcomb.values())) # values() self.assertEqual(set(cm.items()), set(dcomb.items())) # items() self.assertEqual(set(cm), set(dcomb)) # __iter__ () self.assertEqual(cm, dcomb) # __eq__() self.assertEqual([cm[k] for k in dcomb], dcomb.values()) # __getitem__() klist = 'red green blue black brown'.split() self.assertEqual([cm.get(k, 10) for k in klist], [dcomb.get(k, 10) for k in klist]) # get() self.assertEqual([k in cm for k in klist], [k in dcomb for k in klist]) # __contains__() with test_support.check_py3k_warnings(): self.assertEqual([cm.has_key(k) for k in klist], [dcomb.has_key(k) for k in klist]) # has_key() class Issue7005TestCase(unittest.TestCase): """Test output when None is set() as a value and allow_no_value == False. http://bugs.python.org/issue7005 """ expected_output = "[section]\noption = None\n\n" def prepare(self, config_class): # This is the default, but that's the point. cp = config_class(allow_no_value=False) cp.add_section("section") cp.set("section", "option", None) sio = StringIO.StringIO() cp.write(sio) return sio.getvalue() def test_none_as_value_stringified(self): output = self.prepare(ConfigParser.ConfigParser) self.assertEqual(output, self.expected_output) def test_none_as_value_stringified_raw(self): output = self.prepare(ConfigParser.RawConfigParser) self.assertEqual(output, self.expected_output) class SortedTestCase(RawConfigParserTestCase): def newconfig(self, defaults=None): self.cf = self.config_class(defaults=defaults, dict_type=SortedDict) return self.cf def test_sorted(self): self.fromstring("[b]\n" "o4=1\n" "o3=2\n" "o2=3\n" "o1=4\n" "[a]\n" "k=v\n") output = StringIO.StringIO() self.cf.write(output) self.assertEqual(output.getvalue(), "[a]\n" "k = v\n\n" "[b]\n" "o1 = 4\n" "o2 = 3\n" "o3 = 2\n" "o4 = 1\n\n") class ExceptionPicklingTestCase(unittest.TestCase): """Tests for issue #13760: ConfigParser exceptions are not picklable.""" def test_error(self): import pickle e1 = ConfigParser.Error('value') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(repr(e1), repr(e2)) def test_nosectionerror(self): import pickle e1 = ConfigParser.NoSectionError('section') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(repr(e1), repr(e2)) def test_nooptionerror(self): import pickle e1 = ConfigParser.NoO
ptionError('option', 'section') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.mes
sage, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(e1.option, e2.option) self.assertEqual(repr(e1), repr(e2)) def test_duplicatesectionerror(self): import pickle e1 = ConfigParser.DuplicateSectionError('section') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(repr(e1), repr(e2)) def test_interpolationerror(self): import pickle e1 = ConfigParser.InterpolationError('option', 'section', 'msg') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(e1.option, e2.option) self.assertEqual(repr(e1), repr(e2)) def test_interpolationmissingoptionerror(self): import pickle e1 = ConfigParser.InterpolationMissingOptionError('option', 'section', 'rawval', 'reference') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(e1.option, e2.option) self.assertEqual(e1.reference, e2.reference) self.assertEqual(repr(e1), repr(e2)) def test_interpolationsyntaxerror(self): import pickle e1 = ConfigParser.InterpolationSyntaxError('option', 'section', 'msg') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(e1.option, e2.option) self.assertEqual(repr(e1), repr(e2)) def test_interpolationdeptherror(self): import pickle e1 = ConfigParser.InterpolationDepthError('option', 'section', 'rawval') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(e1.option, e2.option) self.assertEqual(repr(e1), repr(e2)) def test_parsingerror(self): import pickle e1 = ConfigParser.ParsingError('source') e1.append(1, 'line1') e1.append(2, 'line2') e1.append(3, 'line3') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.filename, e2.filename) self.assertEqual(e1.errors, e2.errors) self.assertEqual(repr(e1), repr(e2)) def test_missingsectionheadererror(self): import pickle e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled
"""This example shows how to create a scatter p
lot using the `shell` package. """ # Major library imports from numpy import linspace, random, pi # Enthought library imports from chaco.shell import plot,
hold, title, show # Create some data x = linspace(-2*pi, 2*pi, 100) y1 = random.random(100) y2 = random.random(100) # Create some scatter plots plot(x, y1, "b.") hold(True) plot(x, y2, "g+", marker_size=2) # Add some titles title("simple scatter plots") # This command is only necessary if running from command line show()
# -*- coding: utf-8 -*- """ Created on Wed Feb 05 17:10:34 2014 @author: Ning """ from util import * from util.log import _logger from feat.terms.term_categorize import term_category import codecs de
f parse(sentence): for term in sentence.split(): yield term_category(term) def tokenize(): rows = tsv.reader(conv.redirect("data|train.dat")) with codecs.open("train.tokenized.dat",'w',encoding='utf-8') as fl: for row in rows: fl.write("%s\t%s\n" %
(' '.join(list(parse(row[0]))) , row[1]) ) rows = tsv.reader(conv.redirect("data|test.dat")) with codecs.open("test.tokenized.dat",'w',encoding='utf-8') as fl: for row in rows: fl.write("%s\t%s\n" % (' '.join(list(parse(row[0]))) , row[1]) ) if __name__ == "__main__": tokenize()
, (None, None, False), ], # Format 10 = ((a[&Z=1,Y=2]:1.0[&X=3], b[&Z=1,Y=2]:3.0[&X=2]):1.0[&L=1,W=0], ... # NHX Like mrbayes NEXUS common 10: [ ('name', str, True), ('dist', str, True), ('name', str, True), ('dist', str, True), ] } def parse_network(net, disconnect=True, root=None): """ Parse network to extract the major topology. This leaves the hybrid nodes in the tree and labels each with .name="H{int}" and .gamma={float}. root: list of tip names used to root the tree. If "None" then roots on a random tip. """ # if net is a file then read the first line if os.path.exists(net): with open(net, 'r') as infile: net = infile.readline() # trim off loglik and anything after it (TODO: keep loglik) if ";" in net: net = net.split(";")[0] + ';' # sub :xxx:: to be ::: b/c I don't care about admix edge bls net = re.sub(r":\d.\w*::", ":::", net) # change H nodes to proper format while ",#" in net: pre, post = net.split(",#", 1) npre, npost = post.split(")", 1) newpre = npre.split(":")[0] + "-" + npre.split(":")[-1] net = pre + ")#" + newpre + npost net = net.replace(":::", "-") # parse cleaned newick and set empty gamma on all nodes net = toytree.tree(net, tree_format=1) # store admix data admix = {} # root on tips if provided by user -- otherwise pick a non-H root if not root: # if not rooted choose any non-H root if not net.is_rooted(): net = net.root( [i for i in net.get_tip_labels() if not i.startswith("#H")][0] ) else: net = net.root(root) # Traverse tree to find hybrid nodes. If a hybrid node is labeled as a # distinct branch in the tree then it is dropped from the tree and for node in net.treenode.traverse("postorder"): # find hybrid nodes as internal nchild=1, or external with H in name if (len(node.children) == 1) or node.name.startswith("#H"): # assign name and gamma to hybrid nodes aname, aprop = node.name.split("-") aname = aname.lstrip("#") node.name = aname # assign hybrid to closest nodes up and down from edge # node.children[0].hybrid = int(aname[1:]) # node.gamma = round(float(aprop), 3) # node.up.hybrid = int(aname[1:]) # if root is a hybrid edge (ugh) if node.up is None: small, big = sorted(node.children, key=lambda x: len(x)) root = toytree.TreeNode.TreeNode(name='root') node.children = [small] small.up = node
node.up = root big.up = root root.children = [node, big] net.treenode = root
# disconnect node by connecting children to parent if disconnect: # if tip is a hybrid if not node.children: # get sister node sister = [i for i in node.up.children if i != node][0] # connect sister to gparent sister.up = node.up.up node.up.up.children.remove(node.up) node.up.up.children.append(sister) # if hybrid is internal else: node.up.children.remove(node) for child in node.children: child.up = node.up node.up.children.append(child) # store admix data by descendants but remove hybrid tips desc = node.get_leaf_names() if aname in desc: desc = [i for i in node.up.get_leaf_names() if i != aname] desc = [i for i in desc if not i.startswith("#H")] # put this node into admix if aname not in admix: admix[aname] = (desc, aprop) # matching edge in admix, no arrange into correct order by minor else: # this is the minor edge if aprop < admix[aname][1]: admix[aname] = ( admix[aname][0], desc, 0.5, {}, str(round(float(aprop), 3)), ) # this is the major edge else: admix[aname] = ( desc, admix[aname][0], 0.5, {}, str(round(float(admix[aname][1]), 3)), ) # update coords needed if node disconnection is turned back on. net._coords.update() net = net.ladderize() return net, admix class Annotator(object): """ Add annotations as a new mark on top of an existing toytree mark. """ def __init__(self, tree, axes, mark): self.tree = tree self.axes = axes self.mark = mark def draw_clade_box( self, names=None, regex=None, wildcard=None, yspace=None, xspace=None, **kwargs): """ Draw a rectangle around a clade on a toytree. Parameters: ----------- names, regex, wildcard: Choose one of these three methods to select one or more tipnames. The clade composing all descendants of their common ancestor will be highlighted. yspace (float or None): The extent to which boxes extend above and below the root and tip nodes. If None then this is automatically generated. xspace (float or None): The extent to which the clade box extends to the sides (out of the clade towards other tips.) If None default uses 0.5. kwargs: Additional styling options are supported: color, opacity, etc. Returns: ------------ Toyplot.mark.Range """ # get the common ancestor nidx = self.tree.get_mrca_idx_from_tip_labels( names=names, regex=regex, wildcard=wildcard) # get tips descended from mrca tips = self.tree.idx_dict[nidx].get_leaves() tidxs = [i.idx for i in tips] # extent to which box bounds extend outside of the exact clade size. if not yspace: yspace = self.tree.treenode.height / 15. if not xspace: xspace = 0.45 # left and right positions if self.mark.layout == 'r': xmin = self.mark.ntable[nidx, 0] - yspace xmax = max(self.mark.ntable[tidxs, 0]) + yspace ymin = min(self.mark.ntable[tidxs, 1]) - xspace ymax = max(self.mark.ntable[tidxs, 1]) + xspace if self.mark.layout == 'l': xmin = self.mark.ntable[nidx, 0] + yspace xmax = max(self.mark.ntable[tidxs, 0]) - yspace ymin = max(self.mark.ntable[tidxs, 1]) + xspace ymax = min(self.mark.ntable[tidxs, 1]) - xspace elif self.mark.layout == 'd': ymax = self.mark.ntable[nidx, 1] + yspace ymin = min(self.mark.ntable[tidxs, 1]) - yspace xmin = min(self.mark.ntable[tidxs, 0]) - xspace xmax = max(self.mark.ntable[tidxs, 0]) + xspace elif self.mark.layout == 'u': ymin = self.mark.ntable[nidx, 1] - yspace ymax = min(self.mark.ntable[tidxs, 1]) + yspace xmin = min(self.mark.ntable[tidxs, 0]) - xspace xmax = max(self.mark.ntable[tidxs, 0]) + xspace # draw the rectangle newmark = self.axes.rectangle(xmin, xmax, ymin, ymax, **kwargs) # put tree at the top of the scenegraph self.axes._scenegraph.remove_edge(self.axes, 'render', self.mark) self.axes._scenegraph.add_edge(self.axes, 'render', self.mark) return newmark # def draw_tip_box(
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.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 <http://www.gnu.org/licenses/>. # ############################################################################### { 'name': 'XMLRPC Operation Invoice', 'version': '0.1', 'category': 'ETL', 'description': '''
XMLRPC Import invoice ''', 'author': 'Micronaet S.r.l. - Nicola Riolini', 'website': 'http://www.micronaet.it', 'license': 'AGPL-3', 'depends': [ 'base',
'xmlrpc_base', 'account', ], 'init_xml': [], 'demo': [], 'data': [ 'security/xml_groups.xml', #'operation_view.xml', 'invoice_view.xml', 'data/operation.xml', ], 'active': False, 'installable': True, 'auto_install': False, }
import re from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerat
or import Atom1Feed from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from .models import LoggedAction lock_re = re.compile(r'^(?:Unl|L)ock
ed\s*constituency (.*) \((\d+)\)$') class RecentChangesFeed(Feed): site_name = Site.objects.get_current().name title = _("{site_name} recent changes").format(site_name=site_name) description = _("Changes to {site_name} candidates").format(site_name=site_name) link = "/feeds/changes.xml" feed_type = Atom1Feed def items(self): return LoggedAction.objects.order_by('-updated')[:50] def item_title(self, item): m = lock_re.search(item.source) if m: return u"{0} - {1}".format( m.group(1), item.action_type ) else: return u"{0} - {1}".format( item.person_id, item.action_type ) def item_description(self, item): updated = _(u"Updated at {0}").format(str(item.updated)) description = u"{0}\n\n{1}\n".format(item.source, updated) return description def item_link(self, item): # As a hack for the moment, constituencies are just mentioned # in the source message: m = lock_re.search(item.source) if m: return reverse('constituency', kwargs={ 'post_id': m.group(2), 'ignored_slug': slugify(m.group(1)) }) else: if item.person_id: return reverse('person-view', args=[item.person_id]) else: return '/'
import json import random import time import urllib import re from scrapy.utils.misc import load_object from scrapy.http import Request from scrapy.conf import settings import redis from crawler.schedulers.redis.dupefilter import RFPDupeFilter from crawler.schedulers.redis.queue import RedisPriorityQueue try: import cPickle as pickle except ImportError: import pickle class DistributedScheduler(object): ''' Scrapy request scheduler that utilizes Priority Queues to moderate scrape requests within a distributed scrapy cluster ''' redis_conn = None # the redis connection queue = None # the queue to use for crawling spider = None # the spider using this scheduler queue_class = None # the class to use for the queue dupefilter = None # the redis dupefilter item_retries = 0 # the number of extra tries to get an item def __init__(self, server, persist, timeout, retries): ''' Initialize the scheduler ''' self.redis_conn = server self.persist = persist self.rfp_timeout = timeout self.item_retires = retries def setup(self): ''' Used to initialize things when using mock spider.name is not set yet ''' self.queue = RedisPriorityQueue(self.redis_conn, self.spider.name + ":queue") @classmethod def from_settings(cls, settings): server = redis.Redis(h
ost=settings.get('REDIS_HOST'), port=settings.get('REDIS_PORT')) persist = settings.get('SCHEDULER_PERSIST', True) timeout = settings.get('DUPEFILTER_TIMEOUT', 600) retries = settings.get('SCHEDULER_ITEM_RETRIES', 3) return cls(server, persist, timeout, retries) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.set
tings) def open(self, spider): self.spider = spider self.setup() self.dupefilter = RFPDupeFilter(self.redis_conn, self.spider.name + ':dupefilter', self.rfp_timeout) def close(self, reason): if not self.persist: self.dupefilter.clear() self.queue.clear() def is_blacklisted(self, appid, crawlid): ''' Checks the redis blacklist for crawls that should not be propagated either from expiring or stopped @return: True if the appid crawlid combo is blacklisted ''' key_check = '{appid}||{crawlid}'.format(appid=appid, crawlid=crawlid) redis_key = self.spider.name + ":blacklist" return self.redis_conn.sismember(redis_key, key_check) def enqueue_request(self, request): ''' Pushes a request from the spider back into the queue ''' if not request.dont_filter and self.dupefilter.request_seen(request): return req_dict = self.request_to_dict(request) if not self.is_blacklisted(req_dict['meta']['appid'], req_dict['meta']['crawlid']): key = "{sid}:queue".format(sid=req_dict['meta']['spiderid']) curr_time = time.time() # insert if crawl never expires (0) or time < expires if req_dict['meta']['expires'] == 0 or \ curr_time < req_dict['meta']['expires']: self.queue.push(req_dict, req_dict['meta']['priority']) def request_to_dict(self, request): ''' Convert Request object to a dict. modified from scrapy.utils.reqser ''' req_dict = { # urls should be safe (safe_string_url) 'url': request.url.decode('ascii'), 'method': request.method, 'headers': dict(request.headers), 'body': request.body, 'cookies': request.cookies, 'meta': request.meta, '_encoding': request._encoding, 'priority': request.priority, 'dont_filter': request.dont_filter, } return req_dict def find_item(self): ''' Finds an item from the queue ''' count = 0 while count <= self.item_retries: item = self.queue.pop() if item: # very basic limiter time.sleep(1) return item # we want the spiders to get slightly out of sync # with each other for better performance time.sleep(random.random()) count = count + 1 return None def next_request(self): ''' Logic to handle getting a new url request ''' t = time.time() item = self.find_item() if item: try: req = Request(item['url']) except ValueError: # need absolute url # need better url validation here req = Request('http://' + item['url']) if 'meta' in item: item = item['meta'] # defaults if "attrs" not in item: item["attrs"] = {} if "allowed_domains" not in item: item["allowed_domains"] = () if "allow_regex" not in item: item["allow_regex"] = () if "deny_regex" not in item: item["deny_regex"] = () if "deny_extensions" not in item: item["deny_extensions"] = None if 'curdepth' not in item: item['curdepth'] = 0 if "maxdepth" not in item: item["maxdepth"] = 0 if "priority" not in item: item['priority'] = 0 if "retry_times" not in item: item['retry_times'] = 0 if "expires" not in item: item['expires'] = 0 for key in ('attrs', 'allowed_domains', 'curdepth', 'maxdepth', 'appid', 'crawlid', 'spiderid', 'priority', 'retry_times', 'expires', 'allow_regex', 'deny_regex', 'deny_extensions'): req.meta[key] = item[key] return req return None def has_pending_requests(self): ''' We never want to say we have pending requests If this returns True scrapy sometimes hangs. ''' return False
from sklearntools.kfold import ThresholdHybridCV import numpy as np from six.moves import reduce from operator import __add__ from numpy.testing.utils import assert_array_equal from nose.tools impor
t assert_equal def test_hybrid_cv(): X = np.random.normal(size=(100,10)) y = np.random.normal(size=100) cv = ThresholdHybridCV(n_folds=10, upper=1.) folds = list(cv._iter_test_masks(X, y)) assert_array_equal(reduce(__add__, folds), np.ones(100, dtype=int)) assert_equal(len(folds), cv.get_n_splits(X, y)) if __name__ == '__main__': import sys import nose # This code will run the test in this file.' module_name = sys.modules[__name__].__file__ result = nose.run(a
rgv=[sys.argv[0], module_name, '-s', '-v'])
string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = randrange(100000) msgid = '<%s.%s.%s@%s>' % (utcdate, pid, randint, domain) return msgid # cache the domain_from_email calculation # This is just a tuple of (email, email-domain) _from_email_domain_cache = (None, None) def get_from_email_domain(): global _from_email_domain_cache from_ = options.get('mail.from') if not _from_email_domain_cache[0] == from_: _from_email_domain_cache = (from_, domain_from_email(from_)) return _from_email_domain_cache[1] def get_email_addresses(user_ids, project=None): pending = set(user_ids) results = {} if project: queryset = UserOption.objects.filter( project=project, user__in=pending, key='mail:email', ) for option in (o for o in queryset if o.value): results[option.user_id] = option.value pending.discard(option.user_id) if pending: queryset = UserOption.objects.filter( user__in=pending, key='alert_email', ) for option in (o for o in queryset if o.value): results[option.user_id] = option.value pending.discard(option.user_id) if pending: queryset = User.objects.filter(pk__in=pending, is_active=True) for (user_id, email) in queryset.values_list('id', 'email'): if email: results[user_id] = email pending.discard(user_id) if pending: logger.warning('Could not resolve email addresses for user IDs in %r, discarding...', pending) return results class ListResolver(object): """ Manages the generation of RFC 2919 compliant list-id strings from varying objects types. """ class UnregisteredTypeError(Exception): """ Error raised when attempting to build a list-id from an unregisted object type. """ def __init__(self, namespace, type_handlers): assert is_valid_dot_atom(namespace) # The list-id-namespace that will be used when generating the list-id # string. This should be a domain name under the control of the # generator (see RFC 2919.) self.__namespace = namespace # A mapping of classes to functions that accept an instance of that # class, returning a tuple of values that will be used to generate the # list label. Returned values must be valid RFC 2822 dot-atom-text # values. self.__type_handlers = type_handlers def __call__(self, instance): """ Build a list-id string from an instance. Raises ``UnregisteredTypeError`` if there is no registered handler for the instance type. Raises ``AssertionError`` if a valid list-id string cannot be generated from the values returned by the type handler. """ try: handler = self.__type_handlers[type(instance)] except KeyError: raise self.UnregisteredTypeError( 'Cannot generate mailing list identifier for {!r}'.format(instance) ) label = '.'.join(map(str, handler(instance))) assert is_valid_dot_atom(label) return '{}.{}'.format(label, self.__namespace) default_list_type_handlers = { Activity: attrgetter('project.slug', 'project.organization.slug'), Project: attrgetter('slug', 'organization.slug'), Group: attrgetter('project.slug', 'organization.slug'), Event: attrgetter('project.slug', 'organization.slug'), } make_listid_from_instance = ListResolver( options.get('mail.list-namespace'), default_list_type_handlers, ) class MessageBuilder(object): def __init__(self, subject, context=None, template=None, html_template=None, body=None, html_body=None, headers=None, reference=None, reply_reference=None, from_email=None, type=None): assert not (body and template) assert not (html_body and html_template) assert context or not (template or html_template) if headers is None: headers = {} self.subject = subject self.context = context or {} self.template = template self.html_template = html_template self._txt_body = body self._html_body = html_body self.headers = headers self.reference = reference # The object that generated this message self.reply_reference = reply_reference # The object this message is replying about self.from_email = from_email or options.get('mail.from') self._send_to = set() self.type = type if type else 'generic' if reference is not None and 'List-Id' not in headers: try: headers['List-Id'] = make_listid_from_instance(reference) except ListResolver.UnregisteredTypeError as error: logger.debug(str(error)) except AssertionError as error: logger.warning(str(error)) def __render_html_body(self): html_body = None if self.html_template: html_body = render_to_string(self.html_template, self.context) else: html_body = self._html_body if html_body is not None: return inline_css(html_body) def __render_text_body(self): if self.template: return render_to_string(self.template, self.context) return self._txt_body def add_users(self, user_ids, project=None): self._send_to.update( get_email_addresses(user_ids, project).values() ) def build(self, to, reply_to=None, cc=None, bcc=None): if self.headers is None: headers = {} else: headers = self.headers.copy() if options.get('mail.enable-replies') and 'X-Sentry-Reply-To' in headers: reply_to = headers['X-Sentry-Reply-To'] else: reply_to = set(reply_to or ()) reply_to.remove(to) reply_to = ', '.join(reply_to) if reply_to: headers.set
default('Reply-To', reply_to) # Every message sent needs a unique message id message_id = make_msgid(get_from_email_domain()) headers.setdefault('Message-Id', message_id)
subject = self.subject if self.reply_reference is not None: reference = self.reply_reference subject = 'Re: %s' % subject else: reference = self.reference if isinstance(reference, Group): thread, created = GroupEmailThread.objects.get_or_create( email=to, group=reference, defaults={ 'project': reference.project, 'msgid': message_id, }, ) if not created: headers.setdefault('In-Reply-To', thread.msgid) headers.setdefault('References', thread.msgid) msg = EmailMultiAlternatives( subject=subject, body=self.__render_text_body(), from_email=self.from_email, to=(to,), cc=cc or (), bcc=bcc or (), headers=headers, ) html_body = self.__render_html_body() if html_body: msg.attach_alternative(html_body, 'text/html') return msg def get_built_messages(self, to=None, bcc=None): send_to = set(to or ()) send_to.update(self._send_to) results = [self.build(to=email, reply_to=send_to, bcc=bcc) for email in send_to if email] if not results: logger.debug('Did not build any messages, no users to send to.') return results def format_to(self, to): if not to: return '' if len(to) > MAX_RECIPIENTS: to
#!/usr/bin/env python """plot_softmax_results.py: Plot results of mnist softmax tests.""" from helper_scripts.mnist_read_log import plot_results import matplotlib.pyplot as plt # Produce cross entropy and accuracy plots for softmax models. # Requires the training data for each of the models. files = [r"""../mnist_softmax_models\softmax_alpha=0.1_keepp
rob=0.9\log\validation""" ] scalar_names = ['accuracy_1', 'cross_entropy_1'] ylabels = ['Validation Accuracy', 'Cross Entropy (Validation Set)'] legend = [r'$\alpha=0.1, keep\_prob=0.9$'] plot_results(files, scalar_names, ylabels,
legend, 'Softmax Models') plt.show()
# -*- coding: utf-8 -*- # # mfp documentation build configuration file, created by # sphinx-quickstart. # # 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 os import sys # 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('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # 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 = 'index' # General information about the project. project = u'mfp' copyright = u'2014, Simcha Levental' # 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.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # 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'] # 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 prepende
d 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 = [] # -- 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 = '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 # "<project> v<release> 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 = ['_static'] # 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. # html_sidebars = {} # 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 <link> 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 = 'visualizerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'visualizer.tex', u'mfp Documentation', u'Simcha Levental', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'visualizer', u'mfp Documentation', [u'Simcha Levental'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- 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 = [ ('index', 'visualizer', u'mfp Documentation', u'Simcha Levental', 'mfp', 'Mapping and data visualization toolkit.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
#!/usr/bin/env python2.5 from optparse import OptionParser from rosettautil.rosetta import rosettaScore usage = "%prog [options] --term=scoreterm silent files" parser=OptionParser(usage) parser.add_option("--term",dest="term",help="score term to use") (options,args) = parser.parse_args() if len(args) < 1: parser.error("you must specify at least one silent file") #score_gen = scores.score_generator(options.term) best_models = {} # key is a structure ID, value is a pair in form (tag,score) for silent_file in args: #file = silent_file scores=rosettaScore.SilentScoreTable() scores.add_file(silent_file) score_gen = scores.score_generator(options.term) for tag,score in score_gen: split_tag = tag.split("_") model_id = "_".join(split_tag[0:len(split_tag)-1]) #file = scores.get_file_from_tag(tag) try: (cu
rrent_file,current_best_tag,current_best_score) = best_models[model_id] except KeyError: best_models[model_id] = (silent_file,tag,sco
re) continue if score < current_best_score: #print "changed" best_models[model_id] = (silent_file,tag,score) #print best_models #print silent_file #print file,score , current_best_score print "file","tag",options.term for tag in best_models: print best_models[tag][0],best_models[tag][1],best_models[tag][2]
#### #### Give a report on the "sanity" of the users and groups YAML #### metadata files. #### #### Example usage to analyze the usual suspects: #### python3 sanity-check-users-and-groups.py --help #### Get report of current problems: #### python3 ./scripts/sanity-check-users-and-groups.py --users metadata/users.yaml --groups metadata/groups.yaml #### Attempt to repair file (note that we go through json2yaml as libyaml output does not seem compatible with kwalify): #### python3 ./scripts/sanity-check-users-and-groups.py --users metadata/users.yaml --groups metadata/groups.yaml --repair --output /tmp/output.json && json2yaml --depth 10 /tmp/output.json > /tmp/users.yaml #### Check new yaml: #### kwalify -E -f metadata/users.schema.yaml /tmp/users.yaml #### Run report on new yaml. #### reset && python3 ./scripts/sanity-check-users-and-groups.py --users /tmp/users.yaml --groups metadata/groups.yaml import sys import argparse import logging import yaml import json ## Logger basic setup. logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger('sanity') LOGGER.setLevel(logging.WARNING) ## Make sure we exit in a way that will get Jenkins's attention. DIED_SCREAMING_P = False def die_screaming(string): """ Die and take our toys home. """ global DIED_SCREAMING_P LOGGER.error(string) DIED_SCREAMING_P = True #sys.exit(1) def main(): ## Deal with incoming. parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='More verbose output') parser.add_argument('-u', '--users', help='The users.yaml file to act on') parser.add_argument('-g', '--groups', help='The groups.yaml file to act on') parser.add_argument("-r", "--repair", action="store_true", help="Attempt to repair groups and update old permissions") parser.add_argument("-o", "--output", help="The file to output internal structure to (if repairing)") args = parser.parse_args() if args.verbose: LOGGER.setLevel(logging.INFO) LOGGER.info('Verbose: on') ## Ensure targets. if not args.users: die_screaming('need a users argument') LOGGER.info('Will operate on users: ' + args.users) if not args.groups: die_screaming('need a groups argument') LOGGER.info('Will operate on groups: ' + args.groups) ## Read. users = None with open(args.users) as mhandle: users = yaml.safe_load(mhandle.read()) groups_linear = None with open(args.groups) as mhandle: groups_linear = yaml.safe_load(mhandle.read()) ## Switch linear groups to lookup by URI. groups_lookup = {} for group in groups_linear: groups_lookup[group['id']] = group['label'] violations = { "uri": [], "groups": [], } ## Cycle through users and see if we find any violations. for index, user in enumerate(users): nick = user.get('nickname', '???') ## Update old authorizations type. if args.repair: if user.get("authorizations", {}).get("noctua-go", False): print('REPAIR?: Update perms for ' + nick) auths = user["authorizations"]["noctua-go"] del user["authorizations"]["noctua-go"] # delete old way user["authorizations"]["noctua"] = { "go": auths } users[index] = user # save new back into list ## Does the user have noctua perms? if user.get('authorizations', False): auth = user.get('authorizations', {})
if auth.get('noctua-go', False) or \ (auth.get('noctua', False) and auth['noctua']
.get('go', False)): #print('Has perms: ' + user.get('nickname', '???')) ## 1: If so, do they have a URI? if not user.get('uri', False): die_screaming(user.get('nickname', '???') +\ ' has no "uri"') #print(nick + ' has no "uri"') violations["uri"].append(nick) else: ## 2: Is it an ORCID? if user.get('uri', 'NIL').find('orcid') == -1: die_screaming(user.get('nickname', '???') +\ ' "uri" is not an ORCID.') #print(nick + ' "uri" is not an ORCID.') violations["uri"].append(nick) ## 3: If so, do they have a populated groups? if not user.get('groups', False) or len(user["groups"]) == 0: die_screaming(user.get('nickname', '???') +\ ' has no "groups"') #print(nick + ' has no "groups"') if user.get("organization", False): org = user["organization"] print(nick + " could try org {}".format(org)) matching_groups = list(filter(lambda g: org == g["label"] or org == g["shorthand"], groups_linear)) if len(matching_groups) > 0: print("REPAIR?: Use group: {}".format(matching_groups[0]["id"])) if args.repair: user["groups"] = [matching_groups[0]["id"]] users[index] = user else: violations["groups"].append(nick) else: ## 4: If so, are all entries in groups? for gid in user.get('groups'): if not groups_lookup.get(gid, False): die_screaming(user.get('nickname', '???') +\ ' has mistaken group entry: ' + gid) #print(nick + ' has mistaken group entry: ' + gid) violates_both = set(violations["uri"]).intersection(violations["groups"]) just_uri = set(violations["uri"]).difference(violates_both) just_groups = set(violations["groups"]).difference(violates_both) ## Check privs. for index, user in enumerate(users): if user["nickname"] in just_uri or user["nickname"] in just_groups: # If we have an auth with noctua-go with allow-edit set to True if user.get("authorizations", {}).get("noctua", {}).get("go", {}).get("allow-edit", False): print("REPAIR?: Revoke {} noctua-go edit privileges.".format(user["nickname"])) if args.repair: del user["authorizations"] users[index] = user print("\nNo URI, or no ORCID:") print("===================") print("\n".join(just_uri)) print("\nNo Groups:") print("===================") print("\n".join(just_groups)) print("\nBoth Bad:") print("===================") print("\n".join(violates_both)) #print(json.dumps(users)) #print(yaml.dump(users, default_flow_style=False)) #yaml.dump(data, default_flow_style=False) if args.output: with open(args.output, 'w+') as fhandle: fhandle.write(json.dumps(users, sort_keys=True, indent=4)) ## TODO: implement hard checks above later. if DIED_SCREAMING_P: print('Errors happened, alert the sheriff.') sys.exit(1) else: print('Non-failing run.') ## You saw it coming... if __name__ == '__main__': main()
import requests from Norman.errors import HttpMethodError class BaseAPI(object): """ """ _content_type = "application/json" def __init__(self): pass def _json_par
ser(self, json_response): response = json_response.json() return response def exec_reques
t(self, method, url, data=None): method_map = { 'GET': requests.get, 'POST': requests.post, 'PUT': requests.put, 'DELETE': requests.delete } payload = data if data else data request = method_map.get(method) if not request: raise HttpMethodError( "Request method not recognised or implemented") response = request( url=url, json=payload, verify=True) return response.content base = BaseAPI()
f.ctx.node) e2 = z3.Const('__webproxy_e2_%s'%(self.proxy), self.ctx.node) e3 = z3.Const('__webproxy_e3_%s'%(self.proxy), self.ctx.node) e4 = z3.Const('__webproxy_e4_%s'%(self.proxy), self.ctx.node) e5 = z3.Const('__webproxy_e5_%s'%(self.proxy), self.ctx.node) e6 = z3.Const('__webproxy_e6_%s'%(self.proxy), self.ctx.node) # \forall e, p: send(w, e, p) \Rightarrow hostHasAddr(w, p.src) # \forall e_1, p_1: send(w, e, p_1) \Rightarrow \exists e_2, p_2: recv(e_2, w, p_2) \land # p_2.origin == p_1.origin \land p_2.dest == p_1.dest \land hostHasAddr(p_2.origin, p_2.src) self.constraints.append(z3.ForAll([eh, p], z3.Implies(self.ctx.send(self.proxy, eh, p), \ self.ctx.hostHasAddr(self.proxy, self.ctx.packet.src(p))))) cached_packet = z3.And(self.cached(self.ctx.packet.dest(p2), self.ctx.packet.body(p2)), \ self.ctx.etime(self.proxy, p2, self.ctx.recv_event) > \ self.ctime(self.ctx.packet.dest(p2), self.ctx.packet.body(p2)), \ self.ctx.etime(self.proxy, p, self.ctx.send_event) > \ self.ctx.etime(self.proxy, p2, self.ctx.recv_event), \ self.ctx.packet.body(p) == self.cresp(self.ctx.packet.dest(p2), self.ctx.packet.body(p2)), \ self.ctx.packet.orig_body(p) == self.corigbody(self.ctx.packet.dest(p2), self.ctx.packet.body(p2)), \ self.ctx.packet.dest(p) == self.ctx.packet.src(p2), \ self.ctx.dest_port(p) == self.ctx.src_port(p2), \ self.ctx.src_port(p) == self.ctx.dest_port(p2), \ self.ctx.packet.options(p) == 0, \ self.ctx.packet.origin(p) == self.corigin(self.ctx.packet.dest(p2), self.ctx.packet.body(p2))) request_constraints = [z3.Not(self.ctx.hostHasAddr(self.proxy, self.ctx.packet.dest(p2))), \ self.ctx.packet.origin(p2) == self.ctx.packet.origin(p), self.ctx.packet.dest(p2) == self.ctx.packet.dest(p), \ self.ctx.packet.body(p2) == self.ctx.packet.body(p), \ self.ctx.packet.orig_body(p2) == self.ctx.packet.orig_body(p), \ self.ctx.packet.options(p) == 0, \ self.ctx.packet.seq(p2) == self.ctx.packet.seq(p), \ self.ctx.hostHasAddr(self.ctx.packet.origin(p2), self.ctx.packet.src(p2)), \ self.ctx.dest_port(p2) == self.ctx.dest_port(p), \ self.ctx.etime(self.proxy, p, self.ctx.send_event) > \ self.ctx.etime(self.proxy, p2, self.ctx.recv_event), \ self.ctx.hostHasAddr(self.proxy, self.ctx.packet.src(p))] if len(self.acls) != 0: acl_constraint = map(lambda (s, d): \ z3.Not(z3.And(self.ctx.packet.src(p2) == s, \ self.ctx.packet.dest(p2) == d)), self.acls) request_constraints.extend(acl_constraint) self.constraints.append(z3.ForAll([eh, p], z3.Implies(self.ctx.send(self.proxy, eh, p), \ z3.Or(\ z3.Exists([p2, eh2], \ z3.And(self.ctx.recv(eh2, self.proxy, p2), \ z3.Not(self.ctx.hostHasAddr(self.proxy, self.ctx.packet.src(p2))),\ z3.And(request_constraints))), \ z3.Exists([p2, eh2], \ z3.And(self.ctx.recv(eh2, self.proxy, p2), \ z3.Not(self.ctx.hostHasAddr(self.proxy, self.ctx.packet.src(p2))),\ cached_packet)))))) cache_conditions = \ z3.ForAll([a, i], \ z3.Implies(self.cached(a, i), \ z3.And(\ z3.Not(self.ctx.hostHasAddr (self.proxy, a)), \ z3.Exists([e1, e2, e3, p, p2, p3], \ z3.And(\ self.ctx.recv(e1, self.proxy, p2), \ self.ctx.packet.dest(p2) == a, \ self.ctx.packet.body(p2) == i, \ self.ctx.packet.body(p) == i, \ self.ctx.packet.dest(p) == a, \ self.ctx.dest_port(p) == self.ctx.dest_port(p2), \ self.creqpacket(a, i) == p2, \ self.creqopacket(a, i) == p, \ self.ctime(a, i) > self.ctx.etime(self.proxy, p2, self.ctx.recv_event), \ self.ctx.send(self.proxy, e2, p), \ self.ctime(a, i) > self.ctx.etime(self.proxy, p, self.ctx.send_event), \ self.ctx.recv(e3, self.proxy, p3), \ self.crespacket(a, i) == p3, \ self.ctx.src_port(p3) == self.ctx.dest_port(p), \ self.ctx.dest_port(p3) == self.ctx.src_port(p), \ self.ctx.packet.src(p3) == self.ctx.packet.dest(p), \ self.ctx.packet.dest(p3) == self.ctx.packet.src(p), \ z3.Exists([e5, e6], \ z3.And( self.ctx.hostHasAddr (e5, a), \ self.ctx.recv(e6, e5, p), \ z3.ForAll([e4], \ z3.Or(self.ctx.etime(e4, p3, self.ctx.send_event) == 0, \ self.ctx.etime(e4, p3, self.ctx.send_event) > self.ctx.etime(e5, p, self.ctx.recv_event))))), \ self.cresp(a, i) == self.ctx.packet.body(p3), \ self.corigbody(a, i) == self.ctx.packet.orig_body(p3), \ self.corigin(a, i) == self.ctx.packet.origin(p3), \ self.ctime(a, i) == self.ctx.etime(self.proxy, p3, self.ctx.recv_event), \ *request_constraints))))) self.constraints.append(cache_conditions) def _webProxyFunctions (self): self.cached = z3.Function('__webproxy_cached_%s'%(self.proxy), self.ctx.address, z3.IntSort(), z3.BoolSort()) self.ctime = z3.Function('__webproxy_ctime_%s'%(self.proxy), self.ctx.address, z3.IntSort(), z3.IntSort()) self.cresp = z3.Function('__webproxy_cresp_%s'%(self.proxy), self.ctx.address, z3.IntSort(), z3.IntSort()) self.corigbody = z3.Function('__webproxy_corigbody_%s'%(self.proxy), self.ctx.address, z3.IntSort(), z3.IntSort()) self.corigin = z3.Function('__webproxy_corigin_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.node) self.crespacket = z3.Function('__webproxy_crespacket_%s'%(self.proxy), self.ctx.address, z3.IntSort(),
self.ctx.packet)
self.creqpacket = z3.Function('__webproxy_creqpacket_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.packet) self.creqopacket = z3.Function('__webproxy_creqopacket_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.packet) #self.corigbody = z3.Function('__webproxy_corigbody_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.packet) a = z3.Const('__webproxyfunc_cache_addr_%s'%(self.proxy), self.ctx.address) i = z3.Const('__webproxyfunc_cache_body_%s'%(self.proxy), z3.IntSort()) # Model cache as a function # If not cached, cache time is 0 self.constraints.append(z3.ForAll([a, i], z3.Not(self.c
import sys import random, string import os numberOfEmailsToGenerate = sys.argv[1] try: int(numberOfEmailsToGenerate) print('Generating a CSV with ' + numberOfEmailsToGenerate + ' random emails') print('This make take some time if the CSV is large ...') except: sys.exit('Pl
ease pass a number as the first arg') numberOfEmailsToGenerate = int(numberOfEmailsToGenerate) # Delete ./generated.csv, then create it os.system('touch ./generated.csv') for x in range(0, numberOfEmailsToGenerate): randomString = ''.joi
n(random.choice(string.lowercase) for i in range(20)) os.system('echo ' + randomString + '@email.com' ' >> ./generated.csv')
stance(base, dict): raise AssertionError("`base` must be of type <dict>") if not isinstance(other, dict): raise AssertionError("`other` must be of type <dict>") combined = dict() for key, value in iteritems(base): if isinstance(value, dict): if key in other: item = other.get(key) if item is not None: if isinstance(other[key], Mapping): combined[key] = dict_merge(value, other[key]) else: combined[key] = other[key] else: combined[key] = item else: combined[key] = value elif isinstance(value, list): if key in other: item = other.get(key) if item is not None: try: combined[key] = list(set(chain(value, item))) except TypeError: value.extend([i for i in item if i not in value]) combined[key] = value else: combined[key] = item else: combined[key] = value else: if key in other: other_value = other.get(key) if other_value is not None: if sort_list(base[key]) != sort_list(other_value): combined[key] = other_value else: combined[key] = value else: combined[key] = other_value else: combined[key] = value for key in set(other.keys()).difference(base.keys()): combined[key] = other.get(key) return combined def param_list_to_dict(param_list, unique_key="name", remove_key=True): """Rotates a list of dictionaries to be a dictionary of dictionaries. :param param_list: The aforementioned list of dictionaries :param unique_key: The name of a key which is present and unique in all of param_list's dictionaries. The value behind this key will be the key each dictionary can be found at in the new root dictionary :param remove_key: If True, remove unique_key from the individual dictionaries before returning. """ param_dict = {} for params in param_list: params = params.copy() if remove_key: name = params.pop(unique_key) else: name = params.get(unique_key) param_dict[name] = params return param_dict def conditional(expr, val, cast=None): match = re.match(r'^(.+)\((.+)\)$', str(expr), re.I) if match: op, arg = match.groups() else: op = 'eq' if ' ' in str(expr): raise AssertionError('invalid expression: cannot contain spaces') arg = expr if cast is None and val is not None: arg = type(val)(arg) elif callable(cast): arg = cast(arg) val = cast(val) op = next((oper for alias, oper in ALIASES if op == alias), op) if not hasattr(operator, op) and op not in OPERATORS: raise ValueError('unknown operator: %s' % op) func = getattr(operator, op) return func(val, arg) def ternary(value, true_val, false_val): ''' value ? true_val : false_val ''' if value: return true_val else: return false_val def remove_default_spec(spec): for item in spec: if 'default' in spec[item]: del spec[item]['default'] def validate_ip_address(address): try: socket.inet_aton(address) except socket.error: return False return address.count('.') == 3 def validate_ip_v6_address(address): try: socket.inet_pton(socket.AF_INET6, address) except socket.error: return False return True def validate_prefix(prefix): if prefix and not 0 <= int(prefix) <= 32: return False return True def load_provider(spec, args): provider = args.get('provider') or {} for key, value in iteritems(spec): if key not in provider: if 'fallback' in value: provider[key] = _fallback(value['fallback']) elif 'default' in value: provider[key] = value['default'] else: provider[key] = None if 'authorize' in provider: # Coerce authorize to provider if a string has somehow snuck in. provider['authorize'] = boolean(provider['authorize'] or False) args['provider'] = provider return provider def _fallback(fallback): strategy = fallback[0] args = [] kwargs = {} for item in fallback[1:]: if isinstance(item, dict): kwargs = item else: args = item try: return strategy(*args, **kwargs) except basic.AnsibleFallbackNotFound: pass def generate_dict(spec): """ Generate dictionary which is in sync with argspec :param spec: A dictionary that is the argspec of the module :rtype: A dictionary :returns: A dictionary in sync with argspec with default value """ obj = {} if not spec: return obj for key, val in iteritems(spec): if 'default' in val: dct = {key: val['default']} elif 'type' in val and val['type'] == 'dict': dct = {key: generate_dict(val['options'])} else: dct = {key: None} obj.update(dct) return obj def parse_conf_arg(cfg, arg): """ Parse config based on argument :param cfg: A text string which is a line of configuration. :param arg: A text string which is to be matched. :rtype: A text string :returns: A text string if match is found """ match = re.search(r'%s (.+)(\n|$)' % arg, cfg, re.M) if match: result = match.group(1).strip() else: result = None return result def parse_conf_cmd_arg(cfg, cmd, res1, res2=None, delete_str='no'): """ Parse config based on command :param cfg: A text string which is a line of configuration. :param cmd: A text string which is the command to be matched :param res1: A text string to be returned if the command is present :param res2: A text string to be returned if the negate command is present :param delete_str: A text string to identify the start of the negate command :rtype: A text string :returns: A text string if match is found """ match = re.search(r'\n\s+%s(\n|$)' % cmd, cfg) if match: return res1 if res2 is not None: match = re.search(r'\n\s+%s %s(\n|$)' % (delete_str, cmd), cfg) if match: return res2 return None def get_xml_conf_arg(cfg, path, data='text'): """ :param cfg: The top level configuration lxml Element tree object :param path: The relative xpath w.r.t to top level element (cfg) to be searched in the xml hierarchy :param data: The type of data to be returned for the matched xml node. Valid values are text, tag, attrib, with default as text. :return: Returns the required type for the matched xml node or else None """ match = cfg.xpath(path) if len(match): if data == 'tag': result = getattr(match[0], 'tag') elif data == 'attrib': result = getattr(match[0], 'attrib') else: result = getattr(match[0], 'text') else: result = None return result def remove_empties(cfg_dict): """ Generate final config dictionary :param cfg_dict: A dictionary parsed in the facts system
:rtype: A dictionary :returns: A dictionary by eliminating keys that have null values """ final_cfg = {} if not cfg_dict: return final_cfg for key, val in iteritems(cfg_dict): dct = None if isinstance(val, dict):
child_val = remove_empties(val) if child_val: dct = {key: child_val} elif (isinstance(val, list) and val and all([isinstance(x, dict) for x in val])):
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_storage_class import V1beta1StorageClass class TestV1beta1StorageClass(unittes
t.TestCase): """ V1beta1StorageClass unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1StorageClass(self): """ Test V1beta1StorageClass """ mo
del = kubernetes.client.models.v1beta1_storage_class.V1beta1StorageClass() if __name__ == '__main__': unittest.main()
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from .....testing import assert_equal from ..histogrammatching import HistogramMatching def test_HistogramMatching_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, u
sedefault=True, ), inputVolume=dict(argstr='%s', position=-3,
), numberOfHistogramLevels=dict(argstr='--numberOfHistogramLevels %d', ), numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d', ), outputVolume=dict(argstr='%s', hash_files=False, position=-1, ), referenceVolume=dict(argstr='%s', position=-2, ), terminal_output=dict(nohash=True, ), threshold=dict(argstr='--threshold ', ), ) inputs = HistogramMatching.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_HistogramMatching_outputs(): output_map = dict(outputVolume=dict(position=-1, ), ) outputs = HistogramMatching.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable from ..util import MNS, create_element from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element class GetFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/getfolder-operation""" SERVICE_NAME = "GetFolder" element_container_name = f"{{{MNS}}}Folders" ERRORS_TO_CATCH_IN_RESPONSE = EWSAccountService.ERRORS_TO_CATCH_IN_RESPONSE + ( ErrorFolderNotFound, ErrorNoPublicFolderReplicaAvailable, ErrorInvalidOperation, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.folders = [] # A hack to communicate parsing args to _elems_to_objs() def call(self, folders, additional_fields, shape): """Take a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order """ # We can't easily find the correct folder class from the returned XML. Instead, return objects with the same # class as the folder instance it was requested with. self.folders = list(folders) # Convert to a list, in case 'folders' is a generator. We're iterating twice. return self._elems_to_objs( self._chunked_get_elements( self.get_payload, items=self.folders, additional_fields=additional_fields, shape=shape, ) ) def _elems_to_objs(self, elems): for folder, elem in zip(self.folders, elems): if isinstance(elem, Exception): yield elem continue yield parse_folder_elem(elem=elem, fold
er=folder, account=self.account) def get_payload(self, folders, additional_fields, shape): payload = create_element(f"m:{self.SERVICE_NAME}") payload.append( shape_element( tag="m:
FolderShape", shape=shape, additional_fields=additional_fields, version=self.account.version ) ) payload.append(folder_ids_element(folders=folders, version=self.account.version)) return payload
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -----------------------------------------
--------------------------------- from msrest.serialization import Model class Bar(Model): """ The URIs that are used to perform a retrieval of a public blob, queue or table object. :param recursive_point: Recursive Endpoints :type recursive_point: :class:`Endpoints <fixtures.acceptancetestsstoragemanagementclient.models.Endpoints>` """ _attribute
_map = { 'recursive_point': {'key': 'RecursivePoint', 'type': 'Endpoints'}, } def __init__(self, recursive_point=None, **kwargs): self.recursive_point = recursive_point
# # gPrime - a web-based genealogy program # # Copyright (c) 2015 Gramps 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from .forms import Form class NameForm(Form): """ A form for listing, viewing, and editing user settings. """ table = "Person" def __init__(self, handler, instance, handle, row): super().__init__(handler, instance) self.tview = self._("Name") self.view = "Name" self.row = row self.handle = handle if int(row) == 1: self.path = "primary_name" else: self.path = "alternate_name.%s" % (int(self.row) - 2) self.edit_fields = [] if int(row) == 1: for field in [ 'primary_name.type', 'primary_name.first_name', 'primary_name.call', 'primary_name.nick',
'primary_name.famnick', 'primary_name.private', 'primary_name.date', 'primary_name.suffix', 'primary_name.title', 'primary_name.group_as', 'primary_name.sort_as', 'primary_name.display_as', ]: self.edit_fields.append(field) else:
for field in [ 'alternate_names.%s.type', 'alternate_names.%s.first_name', 'alternate_names.%s.call', 'alternate_names.%s.nick', 'alternate_names.%s.famnick', 'alternate_names.%s.private', 'alternate_names.%s.date', 'alternate_names.%s.suffix', 'alternate_names.%s.title', 'alternate_names.%s.group_as', 'alternate_names.%s.sort_as', 'alternate_names.%s.display_as', ]: self.edit_fields.append(field % (int(self.row) - 2))
rc = img.attrib['src'] if settings.STATIC_URL in src: source = os.path.join( settings.STATIC_ROOT, src.replace(settings.STATIC_URL, '') ) else: source = os.path.join( settings.MEDIA_ROOT, src.replace(settings.MEDIA_URL, '') ) if not os.path.isfile(source): raise IOError("Couldn't find %s (Tried: %s)" % ( img.attrib['src'], source )) filename = os.path.basename(source) destination = os.path.join( tmp_dir, filename ) if os.path.isfile(destination): age = time.time() - os.stat(destination)[stat.ST_MTIME] if settings.DEBUG or age > 60 * 60: shutil.copyfile(source, destination) else: shutil.copyfile(source, destination) if settings.STATIC_URL not in src: copied_media_files.append(destination) html = html.replace(img.attrib['src'], filename) with open(input_file, 'w') as f: f.write(html) _here = os.path.dirname(__file__) rasterize_full_path = os.path.join( _here, 'rasterize.js' ) pdf_program = getattr( settings, 'PDF_PROGRAM', 'phantomjs --debug=true %s' % rasterize_full_path ) if 'rasterize.js' in pdf_program: cmd = ( pdf_program + ' "%(input_file)s"' ' "%(output_file)s"' ' "10.2cm*5.7cm"' ) else: raise NotImplementedError(pdf_program) cmd = cmd % { 'input_file': input_file, 'output_file': output_file, 'orientation': 'landscape', } proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out, err = proc.communicate() if settings.DEBUG_PDF_PROGRAM: stderr_output_file = output_file + '.stderr.log' with open(stderr_output_file, 'w') as f: f.write('COMMAND:\n') f.write(cmd) f.write('\n\n') f.write(err) stdout_output_file = output_file + '.stdout.log' with open(stdout_output_file, 'w') as f: f.write('COMMAND:\n') f.write(cmd) f.write('\n\n') f.write(err) print "For your debugging pleasures, cr
eated..." print input_file print output_file print stdout_output_file print stderr_output_file print if os.path.isfile(output_file): # response['Content-Disposition'] = ( # 'filename="%s.pdf"' % os.path.basename(output_file) # ) response = http.HttpResponse(mimetype='application/pdf') # so we can print from an iframe response['X-Frame-Options'] = 'SAMEORIGIN' response.write(op
en(output_file).read()) if not settings.DEBUG_PDF_PROGRAM: os.remove(input_file) os.remove(output_file) for media_file in copied_media_files: os.remove(media_file) return response return http.HttpResponse("PDF could not be created") @non_mortals_required def stats_start(request): data = {} return render(request, 'main/stats-start.html', data) @non_mortals_required def stats(request, location=None): if location == 'ALL': location = None if location: location = get_object_or_404(Location, slug=location) request.session['default-location'] = location.slug _months = defaultdict(int) visitors = VisitorCount.objects.all() active_visitors = Visitor.objects.all() if location: visitors = visitors.filter(location=location) active_visitors = active_visitors.filter(location=location) _rows = defaultdict(list) for v in active_visitors.order_by('created'): _row_key = v.created.strftime('%Y-%m-%d') before = _rows.get(_row_key, {'count': 0}) _rows[_row_key] = { 'year': v.created.year, 'month': v.created.month, 'day': v.created.day, 'date': v.created, 'count': 1 + before['count'] } for vc in visitors.order_by('year', 'month', 'day'): date = datetime.date(vc.year, vc.month, vc.day) count = vc.count _row_key = date.strftime('%Y-%m-%d') before = _rows.get(_row_key, {'count': 0}) count = before['count'] + vc.count _rows[_row_key] = { 'year': vc.year, 'month': vc.month, 'day': vc.day, 'date': date, 'count': count, } _month_key = date.strftime('%Y-%m') _months[_month_key] += count for v in active_visitors.order_by('created'): _month_key = v.created.strftime('%Y-%m') _months[_month_key] += 1 months = [] for key in sorted(_months.keys()): y, m = [int(x) for x in key.split('-')] date = datetime.date(y, m, 1) months.append({ 'year': date.year, 'month': date.month, 'date': date, 'count': _months[key], }) rows = [] for _row_key in sorted(_rows): rows.append(_rows[_row_key]) context = { 'location': location, 'days': int(settings.RECYCLE_MINIMUM_HOURS / 24.0), 'rows': rows, 'months': months, } return render(request, 'main/stats.html', context) def debugger(request): r = http.HttpResponse() r.write('absolute_uri: %s\n' % request.build_absolute_uri()) r.write('DEBUG: %s\n\n' % settings.DEBUG) if request.is_secure(): r.write('request.is_secure()\n') r.write( 'Expect SITE_URL to contain HTTPS: %s\n' % ( settings.SITE_URL, ) ) r.write( 'Expect SESSION_COOKIE_SECURE to be True: %s\n' % ( settings.SESSION_COOKIE_SECURE, ) ) else: r.write('NOT request.is_secure()\n') r.write( 'Expect SITE_URL to contain HTTP: %s\n' % ( settings.SITE_URL, ) ) r.write( 'Expect SESSION_COOKIE_SECURE to be False: %s\n' % ( settings.SESSION_COOKIE_SECURE, ) ) if cache.get('foo'): r.write('\nCache seems to work!\n') else: r.write('\nReload to see if cache works\n') cache.set('foo', 'bar', 60) r['content-type'] = 'text/plain' return r @transaction.commit_on_success @non_mortals_required def csv_upload(request): context = {} def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') if request.method == 'POST': form = forms.CSVUploadForm(request.POST, request.FILES) if form.is_valid(): created = 0 location = form.cleaned_data['location'] tz = pytz.timezone(location.timezone) if form.cleaned_data['format'] == 'eventbrite': stream = StringIO( unicode(form.cleaned_data['file'].read(), 'utf-8'), newline='\r' ) reader = unicode_csv_reader(stream) first = True for i, row in enumerate(reader): if first: first = False continue visitor = Visitor( location=location, first_name=row[0], # Name job_title=row[2], # Title ) if f
""" Progress Tab Serializers """ from rest_framework import serializers from rest_framework.rever
se import reverse class GradedTotalSerializer(serializers.Serializer): earned = serializers.FloatField() possible = serializers.FloatField() class SubsectionSerializer(serializers.Serializer): display_name = serializers.CharField() due = serializers.DateTimeField() format = serializers.CharField()
graded = serializers.BooleanField() graded_total = GradedTotalSerializer() # TODO: override serializer percent_graded = serializers.FloatField() problem_scores = serializers.SerializerMethodField() show_correctness = serializers.CharField() show_grades = serializers.SerializerMethodField() url = serializers.SerializerMethodField() def get_url(self, subsection): relative_path = reverse('jump_to', args=[self.context['course_key'], subsection.location]) request = self.context['request'] return request.build_absolute_uri(relative_path) def get_problem_scores(self, subsection): problem_scores = [ { 'earned': score.earned, 'possible': score.possible, } for score in subsection.problem_scores.values() ] return problem_scores def get_show_grades(self, subsection): return subsection.show_grades(self.context['staff_access']) class ChapterSerializer(serializers.Serializer): """ Serializer for chapters in coursewaresummary """ display_name = serializers.CharField() subsections = SubsectionSerializer(source='sections', many=True) class CertificateDataSerializer(serializers.Serializer): cert_status = serializers.CharField() cert_web_view_url = serializers.CharField() download_url = serializers.CharField() msg = serializers.CharField() title = serializers.CharField() class CreditRequirementSerializer(serializers.Serializer): """ Serializer for credit requirement objects """ display_name = serializers.CharField() min_grade = serializers.SerializerMethodField() status = serializers.CharField() status_date = serializers.DateTimeField() def get_min_grade(self, requirement): if requirement['namespace'] == 'grade': return requirement['criteria']['min_grade'] * 100 else: return None class CreditCourseRequirementsSerializer(serializers.Serializer): """ Serializer for credit_course_requirements """ dashboard_url = serializers.SerializerMethodField() eligibility_status = serializers.CharField() requirements = CreditRequirementSerializer(many=True) def get_dashboard_url(self, _): relative_path = reverse('dashboard') request = self.context['request'] return request.build_absolute_uri(relative_path) class VerificationDataSerializer(serializers.Serializer): """ Serializer for verification data object """ link = serializers.URLField() status = serializers.CharField() status_date = serializers.DateTimeField() class ProgressTabSerializer(serializers.Serializer): """ Serializer for progress tab """ certificate_data = CertificateDataSerializer() credit_course_requirements = CreditCourseRequirementsSerializer() credit_support_url = serializers.URLField() courseware_summary = ChapterSerializer(many=True) enrollment_mode = serializers.CharField() studio_url = serializers.CharField() user_timezone = serializers.CharField() verification_data = VerificationDataSerializer()
## p7.py - parallel processing microframework ## (c) 2017 by mobarski (at) gmail (dot) com ## licence: MIT ## version: ex4 (simple fan-in of subprocess outputs) from __future__ import print_function # CONFIG ################################################################################### HEAD_LEN_IN = 2 HEAD_LEN_OUT = 100 BUFSIZE = 4096 CMD = "python -c 'import sys; sys.stdout.write(sys.stdin.read())'" N = 4 # END OF CONFIG ############################################################################ import subprocess import threading import shlex import sys from select import select from time import time IN = sys.stdin OUT = sys.stdout OUT = open('test/out.txt','wb') LOG = sys.stderr c
tx = {} args = shlex.split(CMD) PIPE = subprocess.PIPE for i in range(N): ctx[i] = {} proc = subprocess.Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=BUFSIZE) ctx[i]['proc'] = proc # metadata ctx[i]['pid'] = proc.pid ctx[i]['t_start'] = time() ctx[i]['head_cnt_in'] = 0 ctx[i]['head_cnt_out'] = 0 def pump_input(): while True: for i in range(N): p = ctx[i]['proc'] head = IN.read(HEAD_LEN_IN) p.stdin.write(head) ctx[i]['head_cnt_in
'] += 1 if len(head)<HEAD_LEN_IN: # End Of File break tail = IN.readline() p.stdin.write(tail) else: continue # not EOF # EOF -> close all input streams for i in range(N): ctx[i]['proc'].stdin.close() break def pump_output(): done = set() while True: for i in range(N): if i in done: continue p = ctx[i]['proc'] head = p.stdout.read(HEAD_LEN_OUT) OUT.write(head) ctx[i]['head_cnt_out'] += 1 if len(head)<HEAD_LEN_OUT: # End Of File done.add(i) p.wait() # End Of Process ctx[i]['t_stop'] = time() ctx[i]['run_time'] = ctx[i]['t_stop'] - ctx[i]['t_start'] continue tail = p.stdout.readline() OUT.write(tail) if len(done)==N: return # RUN DATA PUMPS input_pump = threading.Thread(target=pump_input) output_pump = threading.Thread(target=pump_output) input_pump.start() output_pump.start() input_pump.join() output_pump.join() from pprint import pprint pprint(ctx)
ent 'generate' interface for output Python intermediate code generating. """ def __init__(self, text, indent, block): self.text = text self.indent = indent self.block = block def generate(self): raise NotImplementedError() class TextNode(BaseNode): """ Node for normal text. """ def generate(self): return '{0}_stdout.append(\'\'\'{1}\'\'\')\n'.format(' '*self.indent, self.text) class VariableNode(BaseNode): """ Node for variables: such as {{ name }}. """ def generate(self): return '{0}_stdout.append({1})\n'.format(' '*self.indent, self.text) class KeyNode(BaseNode): """ Node for keywords like if else... """ def generate(self): return '{0}{1}\n'.format(' '*self.indent, self.text) class TemplateException(Exception): pass class Template(object): """ Main class for compiled template instance. A initialized template instance will parse and compile all the template source to Python intermediate code, and instance function `render` will use Python builtin function `exec` to execute the intermediate code in Python runtime. As function `exec` own very strong power and the ability to execute all the python code in the runtime with given namespace dict, so this template engine can perform all the python features even lambda function. But, function `exec` also has a huge problem in security, so be careful and be serious, and I am very serious too. """ def __init__(self, source, path='', autoescape=False): if not source: raise ValueError('Invalid parameter') self.scanner = Scanner(source) # path for extends and include self.path = path self.nodes = [] # parent template self.parent = None self.autoescape = autoescape self._parse() # compiled intermediate code. self.intermediate = self._compile() def _parse(self): python_keywords = ['if', 'for', 'while', 'try', 'else', 'elif', 'except', 'finally'] indent = 0 block_stack = [] def block_stack_top(): return block_stack[-1] if block_stack else None while not self.scanner.empty: token = self.scanner.next_token() if not token: self.nodes.append(TextNode(self.scanner.remain, indent, block_stack_top())) break # get the pre-text before token. if self.scanner.pretext: self.nodes.append(TextNode(self.scanner.pretext, indent, block_stack_top())) variable, endtag, tag, statement, keyword, suffix = token.groups() if variable: node_text = 'escape(str({0}))'.format(variable) if self.autoescape else variable self.nodes.append(VariableNode(node_text, indent, block_stack_top())) elif endtag: if tag != 'block': indent -= 1 continue # block placeholder in parent template nodes if not self.parent: node_text = 'endblock%{0}'.format(block_stack_top()) self.nodes.append(KeyNode(node_text, indent, block_stack_top())) block_stack.pop() elif statement: if keyword == 'include': filename = re.sub(r'\'|\"', '', suffix) nodes = Loader(self.path).load(filename).nodes for node in nodes: node.indent += indent self.nodes.extend(nodes) elif keyword == 'extends': if self.nodes: raise TemplateException('Template syntax error: extends tag must be ' 'at the beginning of the file.') filename = re.sub(r'\'|\"', '', suffix) self.parent = Loader(self.path).load(filename) elif keyword == 'block': block_stack.append(suffix) if not self.parent: node_text = 'block%{0}'.format(suffix) self.nodes.append(KeyNode(node_text, indent, block_stack_top())) elif keyword in python_keywords: node_text = '{0}:'.format(statement) if keyword in ['else', 'elif', 'except', 'finally']: key_indent = indent - 1 else: key_indent = indent indent += 1 self.nodes.append(KeyNode(node_text, key_indent, block_stack_top())) else: raise TemplateException('Invalid keyword: {0}.'.format(keyword)) else: raise TemplateException('Template syntax error.') def _compile(self): block = {} if self.parent: generate_code = ''.join(node.generate() for node in self.parent.nodes) pattern = re.compile(r'block%(?P<start_block>\w+)(?P<block_code>.*?)endblock%(?P<end_block>\w+)', re.S) for node in self.nodes: block.setdefault(node.block, []).append(node.generate()) for token in pattern.finditer(generate_code): block_name = token.group('start_block') if block_name != token.group('end_block'): raise TemplateException('Template syntax error.') block_code = ''.join(block[block_name]) if block_name in block.keys() else token.group('block_code') generate_code = generate_code.replace(token.group(), block_code) else: generate_code = ''.join(node.generate() for node in self.nodes) return compile(generate_code, '<string>', 'exec') def render(self, **context): # `context['_stdout']`: Compiled template source code # which is a Python list, contain all the output # statement of Python
code. context.update({'_stdout': [], 'escape': escape}) exec(self.intermediate, context) return re.sub(r'(\s+\n)+', r'\n', ''.join(map(str, context['_stdout']))) class LRUCache(object): """ Simple LRU cache for template instance caching. in fact, the OrderedDict in collections module or @functools.lru_cache is working well too. """ def __init__
(self, capacity): self.capacity = capacity self.cache = collections.OrderedDict() def get(self, key): """ Return -1 if catched KeyError exception.""" try: value = self.cache.pop(key) self.cache[key] = value return value except KeyError: return -1 def set(self, key, value): try: self.cache.pop(key) except KeyError: if len(self.cache) >= self.capacity: self.cache.popitem(last=False) self.cache[key] = value class Loader(object): """ A template Loader which loads the environments of main application, or just give the template system a root directory to search the template files. loader = template.Loader("home/to/root/of/templates/") loader.load("index.html").render() Loader class use a LRU cache system to cache the recently used templates for performance consideration. """ def __init__(self, path='', engine=Template, cache_capacity=_CACHE_CAPACITY): self.path = path self.engine = engine self.cache = LRUCache(capacity=cache_capacity) def load(self, filename): if not self.path.endswith(os.sep) and self.path != '': self.path = self.path + os.sep p = ''.join([self.path, filename]) cache_instance = self.cache.get(p) if cache_instance != -1: return cache_instance if not os.path.isfile(p): raise TemplateException('Template file {0} is not exist.'.format(p)) with open(p) as f: self.cache.set(p, self.engine(f.read(), path=self.path)) return self.
"""Django middlewares.""" try: # Python 2.x from urlparse import urlsplit, urlunsplit except ImportError: # Python 3.x from urllib.parse import urlsplit from urllib.parse import urlunsplit from django.conf import settings from django.http import HttpResponsePermanentRedirect try: # Django 1.10 from django.utils.deprecation import MiddlewareMixin except ImportError: # Django <1.10 class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request)
if hasattr(self, 'process_response'): response = self.process_response(request, response) return response class SSLifyMiddleware(MiddlewareMixin): """Force all requests to use HTTPs. If we get an HTTP request, we'll just force a redirect to HTTPs. .. note:: You can also disable this middleware when testing by setting ``settings.SSLIFY_DISABLE`` to True. """ @staticmethod def process_request(request): # If the user has exp
licitly disabled SSLify, do nothing. if getattr(settings, 'SSLIFY_DISABLE', False): return None # Evaluate callables that can disable SSL for the current request per_request_disables = getattr(settings, 'SSLIFY_DISABLE_FOR_REQUEST', []) for should_disable in per_request_disables: if should_disable(request): return None # If we get here, proceed as normal. if not request.is_secure(): url = request.build_absolute_uri(request.get_full_path()) url_split = urlsplit(url) scheme = 'https' if url_split.scheme == 'http' else url_split.scheme ssl_port = getattr(settings, 'SSLIFY_PORT', 443) url_secure_split = (scheme, "%s:%d" % (url_split.hostname or '', ssl_port)) + url_split[2:] secure_url = urlunsplit(url_secure_split) return HttpResponsePermanentRedirect(secure_url)
import argparse import codecs import sys from .auth import parse_authentication from .confluence_api import create_confluence_api from .confluence import ConfluencePageManager from .constants import DEFAULT_CONFLUENCE_API_VERSION def main(): parser = argparse.ArgumentParser(description='Dumps Confluence page in storage format') parser.add_argument('page_id', type=str, help='Configuration file') parser.add_argument('-u', '--url', type=str, help='Confluence Url') auth_group = parser.add_mutually_exclusive_group(required=True) auth_group.add_argument('-a', '--auth', type=str, help='Base64 encoded user:password string') auth_group.add_argument('-U', '--user', type=str, help='Username (prompt password)') parser.add_argument('-o', '--output', type=str, help='Output file|stdout|stderr', default='stdout') args = parser.parse_args() auth = parse_authentication(args.auth, args.user) confluence_api = create_confluence_api(DEFAULT_CONFLUENCE_API_VERSION, args.url, auth) page_manager = ConfluencePageManager(confluence_api) page = page_manager.load(args.page_id) if args.output.lower() == 'stdout': f = sys.stdout elif args.output.lower() == 'stderr': f = sys.stderr else: f = codecs.open(args.output, 'w', encoding='utf-8') with f: f.write(page.body) if __name__ == '__m
ain__': mai
n()
#!/usr/bin/env python3 import fnmatch import os import re import ntpath import sys import argparse def get_private_declare(content): priv_declared = [] srch = re.compile('private.*') priv_srch_declared = srch.findall(content) priv_srch_declared = sorted(set(priv_srch_declared)) priv_dec_str = ''.join(priv_srch_declared) srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z0-9]*?)[ ,\}\]\)";]') priv_split = srch.findall(priv_dec_str) priv_split = sorted(set(priv_split)) priv_declared += priv_split; srch = re.compile('params \[.*\]|PARAMS_[0-9].*|EXPLODE_[0-9]_PVT.*|DEFAULT_PARAM.*|KEY_PARAM.*|IGNORE_PRIVATE_WARNING.*') priv_srch_declared = srch.findall(content) priv_srch_declared = sorted(set(priv_srch_declared
)) priv_dec_str = ''.join(priv_srch_declared) srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z0-9]*?)[ ,\}\]\)";]') priv_split = srch.findall(priv_dec_str) priv_split = sorted(set(priv_split)) priv_declared += priv_split; srch = re.compile('(?i)[\s]*local[\s]+(_[\w\d]*)[\s]*=.*') priv_local = s
rch.findall(content) priv_local_declared = sorted(set(priv_local)) priv_declared += priv_local_declared; return priv_declared def check_privates(filepath): bad_count_file = 0 def pushClosing(t): closingStack.append(closing.expr) closing << Literal( closingFor[t[0]] ) def popClosing(): closing << closingStack.pop() with open(filepath, 'r') as file: content = file.read() priv_use = [] priv_use = [] # Regex search privates srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z0-9]*?)[ =,\^\-\+\/\*\%\}\]\)";]') priv_use = srch.findall(content) priv_use = sorted(set(priv_use)) # Private declaration search priv_declared = get_private_declare(content) if '_this' in priv_declared: priv_declared.remove('_this') if '_this' in priv_use: priv_use.remove('_this') if '_x' in priv_declared: priv_declared.remove('_x') if '_x' in priv_use: priv_use.remove('_x') if '_forEachIndex' in priv_declared: priv_declared.remove('_forEachIndex') if '_forEachIndex' in priv_use: priv_use.remove('_forEachIndex') if '_foreachIndex' in priv_declared: priv_declared.remove('_foreachIndex') if '_foreachIndex' in priv_use: priv_use.remove('_foreachIndex') if '_foreachindex' in priv_declared: priv_declared.remove('_foreachindex') if '_foreachindex' in priv_use: priv_use.remove('_foreachindex') missing = [] for s in priv_use: if s.lower() not in map(str.lower,priv_declared): if s.lower() not in map(str.lower,missing): missing.append(s) if len(missing) > 0: print (filepath) private_output = 'private['; first = True for bad_priv in missing: if first: first = False private_output = private_output + '"' + bad_priv else: private_output = private_output + '", "' + bad_priv private_output = private_output + '"];'; print (private_output) for bad_priv in missing: print ('\t' + bad_priv) bad_count_file = bad_count_file + 1 return bad_count_file def main(): print("#########################") print("# Search your Privates #") print("#########################") sqf_list = [] bad_count = 0 parser = argparse.ArgumentParser() parser.add_argument('-m','--module', help='only search specified module addon folder', required=False, default=".") args = parser.parse_args() for root, dirnames, filenames in os.walk('../addons' + '/' + args.module): for filename in fnmatch.filter(filenames, '*.sqf'): sqf_list.append(os.path.join(root, filename)) for filename in sqf_list: bad_count = bad_count + check_privates(filename) print ("Bad Count {0}".format(bad_count)) if __name__ == "__main__": main()
from django.db import models from django.utils.translation import ugettext_lazy as _ class HelperShift(models.Model): """ n-m relation between helper and shift. This model then can be used by other apps to "attach" more data with OneToOne fields and signals. The fields `present` and `manual_presence` belong to the gifts app. They are directly inserted here as it would be too complicated to add another model for just two booleans. Additionally, this has the advantage that the `present` flag can directly used by other apps. Columns: :helper: The helper :shift: The shift :timestamp: Timestamp when the helper registered for this shift :present: Flag set when the helper is there (manually or automatically) :manual_presence: `present` flag was manually set """ class Meta: unique_together = ('helper', 'shift',) helper = models.ForeignKey( 'Helper', on_delete=models.CASCADE, ) shift = models.ForeignKey( 'Shift', on_delete=models.CASCADE, ) timestamp = models.DateTimeField( auto_now_add=True, verbose_name=_("Registration time for this shift
") ) present = models.BooleanField( default=False, verbose_name=_("Present"), help_text=_("Helper was at shift") ) manual_presence = models.BooleanField( default=False, editable=False
, verbose_name=_("Presence was manually set"), ) def __str__(self): return "{} - {} - {}".format(self.helper.event, self.helper, self.shift)
""" Tests the implementation of the solution to the Euclidean Minimum Spanning Tree (EMST) problem """ import pytest from exhaustive_search.point import Point from exhaustive_search.euclidean_mst import solve, edist def compare_solutions(actual, expected): assert len(actual) == len(expected), "expected %d to equal %d" % (len(actual), len(expected)) assert sorted(actual, key=keyfunc) == sorted(expected, key=keyfunc) def keyfunc(tpl): left, right = tpl return edist(left, right) def test_empty_mst_list(): """ the (E)MST solution to an empty list is an empty list """ assert solve([]) == [], __doc__ def test_non_list(): """ this function should reject non-lists (invalid inputs) by raising a TypeError """ with pytest.raises(TypeError): solve(True) def test_list_of_one(): """ the (E)MST solution to a list of one is an empty list """ assert solve([Point(0, 0)]) == [], __doc__ def test_list_of_two(): """ the (E)MST solution to a list of two points (i.e. [a, b]) is a list containing a tuple of points (i.e. [(a, b)]) """ one, two = Point(3, 1), Point(1, 3) actual = solve([one, two]) compare_solutions(actual, [(one, two)]) def test_triangle(): """ Given a list of points L: L = [Point(0, 0), Point(3, 0), Point(0, 6)] The solution is: [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))] """ graph = [Point(0, 0), Point(3, 0), Point(6, 0)] actual = solve(graph) compare_solutions(actual, [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]) for result in actual: left, right = result if left == Point(0, 0) or left == Point(6, 0): assert right == Point(3, 0), \ "expected
right (%s) to
== %s (left is %s)" % (right, Point(3, 0), left) else: assert right == Point(0, 0) or right == Point(6, 0), \ "expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0))
# Copyright 2014-2020 The PySCF Developers. 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: Oliver J. Backhouse <olbackhouse@gmail.com> # George H. Booth <george.booth@kcl.ac.uk> # import unittest import numpy as np from pyscf.agf2 import aux, _agf2 class KnownValues(unittest.TestCase): @classmethod def setUpClass(self): self.nmo = 100 self.nocc = 20 self.nvir = 80 self.naux = 400 np.random.seed(1) @classmethod def tearDownClass(self): del self.nmo, self.nocc, self.nvir, self.naux np.random.seed() def test_c_ragf2(self): xija = np.random.random((self.nmo, self.nocc, self.nocc, self.nvir)) gf_occ = aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)) gf_vir = aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)) vv1, vev1 = _agf2.build_mats_ragf2_outcore(xija, gf_occ.energy, gf_vir.energy) vv2, vev2 = _agf2.build_mats_ragf2_incore(xija, gf_occ.energy, gf_vir.energy) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertA
lmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_dfragf2(self): qxi = np.random.random((self.naux, self.nmo*self.nocc)) / self.naux qja = np.random.random((self.naux, self.nocc*self.nvir)) / self.naux
gf_occ = aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)) gf_vir = aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)) vv1, vev1 = _agf2.build_mats_dfragf2_outcore(qxi, qja, gf_occ.energy, gf_vir.energy) vv2, vev2 = _agf2.build_mats_dfragf2_incore(qxi, qja, gf_occ.energy, gf_vir.energy) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_uagf2(self): xija = np.random.random((2, self.nmo, self.nocc, self.nocc, self.nvir)) gf_occ = (aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)), aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))) gf_vir = (aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)), aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir))) vv1, vev1 = _agf2.build_mats_uagf2_outcore(xija, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) vv2, vev2 = _agf2.build_mats_uagf2_incore(xija, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_dfuagf2(self): qxi = np.random.random((2, self.naux, self.nmo*self.nocc)) / self.naux qja = np.random.random((2, self.naux, self.nocc*self.nvir)) / self.naux gf_occ = (aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)), aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))) gf_vir = (aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)), aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir))) vv1, vev1 = _agf2.build_mats_dfuagf2_outcore(qxi, qja, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) vv2, vev2 = _agf2.build_mats_dfuagf2_incore(qxi, qja, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) if __name__ == '__main__': print('AGF2 C implementations') unittest.main()
#!/usr/bin/python from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(PauseAction(3000)) sequence.append(KeyComboAction("F10")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("space")) sequence.append(PauseAction(3000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_8")) sequence.append(utils.AssertPresentationAction( "1. Review current line", ["BRAILLE LINE: 'Start $l'", " VISIBLE: 'Start $l', cursor=1", "SPEECH OU
TPUT: 'Start'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("space")) sequence.append(utils.AssertPresentationAction( "2. Activate timer", ["BRAILLE LINE: 'gnome-clocks application Clocks frame Pause push button'", " VISIBLE: 'Pause push button', cursor=1", "BRAILLE LINE: 'gnome-clocks application Clocks frame Pause push button'", " VISIBLE: 'Pause push button', cursor=1", "SPEECH OUTPUT: 'Cl
ocks frame'", "SPEECH OUTPUT: 'Pause push button'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_8")) sequence.append(utils.AssertPresentationAction( "3. Review current line", ["BRAILLE LINE: 'Pause Reset $l'", " VISIBLE: 'Pause Reset $l', cursor=1", "SPEECH OUTPUT: 'Pause Reset'"])) sequence.append(PauseAction(5000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_7")) sequence.append(utils.AssertPresentationAction( "4. Review previous line", ["BRAILLE LINE: '00 ∶ 04 ∶ 5[0-9] \\$l'", " VISIBLE: '00 ∶ 04 ∶ 5[0-9] \\$l', cursor=1", "SPEECH OUTPUT: '00 ∶ 04 ∶ 5[0-9]'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_7")) sequence.append(utils.AssertPresentationAction( "5. Review previous line", ["BRAILLE LINE: '& y World & y Alarm & y Stopwatch &=y Timer $l'", " VISIBLE: '& y World & y Alarm & y Stopwatc', cursor=1", "SPEECH OUTPUT: 'not selected World not selected Alarm not selected Stopwatch selected Timer'"])) sequence.append(PauseAction(5000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_9")) sequence.append(utils.AssertPresentationAction( "6. Review next line", ["BRAILLE LINE: '00 ∶ 04 ∶ 4[0-9] \\$l'", " VISIBLE: '00 ∶ 04 ∶ 4[0-9] \\$l', cursor=1", "SPEECH OUTPUT: '00 ∶ 04 ∶ 4[0-9]'"])) sequence.append(PauseAction(5000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_8")) sequence.append(utils.AssertPresentationAction( "7. Review current line", ["BRAILLE LINE: '00 ∶ 04 ∶ 3[0-9] \\$l'", " VISIBLE: '00 ∶ 04 ∶ 3[0-9] \\$l', cursor=1", "SPEECH OUTPUT: '00 ∶ 04 ∶ 3[0-9]'"])) sequence.append(PauseAction(5000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_8")) sequence.append(utils.AssertPresentationAction( "8. Review current line", ["BRAILLE LINE: '00 ∶ 04 ∶ 2[0-9] \\$l'", " VISIBLE: '00 ∶ 04 ∶ 2[0-9] \\$l', cursor=1", "SPEECH OUTPUT: '00 ∶ 04 ∶ 2[0-9]'"])) sequence.append(utils.AssertionSummaryAction()) sequence.start()
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView, \ ArchiveIndexView, DateDetailView, \ DayArchiveView, MonthArchiveView, \ TodayArchiveView, WeekArchiveView, \ YearArchiveView from baseapp.models import Class_Studying from django.contrib import auth, messages class Class_StudyingView(object): model = Class_Studying def get_template_names(self): """Nest templates within class_studying directory.""" tpl = super(Class_StudyingView, self).get_template_names()[0] app = self.model._meta.app_label mdl = 'class_studying' self.template_name = tpl.replace(app, '{0}/{1}'.format(app, mdl)) return [self.template_name] class Class_StudyingDateView(Class_StudyingView): date_field = 'created_date' month_format = '%m' class Class_StudyingBaseListView(Class_StudyingView): paginate_by = 10 class Class_StudyingArchiveIndexView( Class_StudyingDateView, Class_StudyingBaseListView, ArchiveIndexView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingCreateView(Class_StudyingView, CreateView): def get_success_url(self): from django.core.urlresolvers import reverse messages.add_message( self.request, messages.SUCCESS,"Successfully created." ) return reverse('baseapp_class_studying_list') class Class_StudyingDateDetailView(Class_StudyingDateView, DateDetailView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingDayArchiveView( Class_StudyingDateView, Class_StudyingBaseListView, DayArchiveView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingDeleteView(Class_StudyingView, DeleteView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingDetailView(Class_StudyingView, DetailView): def get_success_url(self): from django.core.urlresolvers import reverse retu
rn reverse('baseapp_class_studying_list') class Class_StudyingListView(Class_StudyingBaseListView, ListView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Clas
s_StudyingMonthArchiveView( Class_StudyingDateView, Class_StudyingBaseListView, MonthArchiveView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingTodayArchiveView( Class_StudyingDateView, Class_StudyingBaseListView, TodayArchiveView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingUpdateView(Class_StudyingView, UpdateView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingWeekArchiveView( Class_StudyingDateView, Class_StudyingBaseListView, WeekArchiveView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_class_studying_list') class Class_StudyingYearArchiveView( Class_StudyingDateView, Class_StudyingBaseListView, YearArchiveView): make_object_list = True
### extends 'class_empty.py' ### block ClassImports # NOTICE: Do not edit anything here, it is generated code from . import gxapi_cy from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref ### endblock ClassImports ### block Header # NOTICE: The code generator will not replace the code in this block ### endblock Header ### block ClassImplementation # NOTICE: Do not edit anything here, it is generated code class GXRA(gxapi_cy.WrapRA): """ GXRA class. The `GXRA <geosoft.gxapi.GXRA>` class is used to access ASCII files sequentially or by line number. The files are opened in read-only mode, so no write operations are defined """ def __init__(self, handle=0): super(GXRA, self).__init__(GXContext._get_tls_geo(), handle) @classmethod def null(cls): """ A null (undefined) instance of `GXRA <geosoft.gxapi.GXRA>` :returns: A null `GXRA <geosoft.gxapi.GXRA>` :rtype: GXRA """ return GXRA() def is_null(self): """ Check if this is a null (undefined) instance :returns: True if this is a null (undefined) instance, False otherwise. :rtype: bool """ return self._internal_handle() == 0 # Miscellaneous @classmethod def create(cls, file): """ Creates `GXRA <geosoft.gxapi.GXRA>` :param file: Name of the file :type file: str :returns: `GXRA <geosoft.gxapi.GXRA>` Object :rtype: GXRA .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = gxapi_cy.WrapRA._create(GXContext._get_tls_geo(), file.encode()) return GXRA(ret_val) @classmethod def create_sbf(cls, sbf, file): """ Creates `GXRA <geosoft.gxapi.GXRA>` on an `GXSBF <geosoft.gxapi.GXSBF>` :param sbf: Storage :param file: Name of the f
ile :type sbf: GXSBF :type file: str :returns: `GXRA <geosoft.gxapi.GXRA>` Object :rtype: GXRA .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** This method allows you to open an `GXRA <geosoft.gxapi.GXRA>` in a structured file storage (an `
GXSBF <geosoft.gxapi.GXSBF>`). SBFs can be created inside other data containers, such as workspaces, maps, images and databases. This lets you store application specific information together with the data to which it applies. .. seealso:: sbf.gxh """ ret_val = gxapi_cy.WrapRA._create_sbf(GXContext._get_tls_geo(), sbf, file.encode()) return GXRA(ret_val) def gets(self, strbuff): """ Get next full line from `GXRA <geosoft.gxapi.GXRA>` :param strbuff: Buffer in which to place string :type strbuff: str_ref :returns: 0 - Ok 1 - End of file :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val, strbuff.value = self._gets(strbuff.value.encode()) return ret_val def len(self): """ Returns the total number of lines in `GXRA <geosoft.gxapi.GXRA>` :returns: # of lines in the `GXRA <geosoft.gxapi.GXRA>`. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._len() return ret_val def line(self): """ Returns current line #, 0 is the first :returns: The current read line location. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** This will be the next line read. """ ret_val = self._line() return ret_val def seek(self, line): """ Position next read to specified line # :param line: Line #, 0 is the first. :type line: int :returns: 0 if seeked line is within the range of lines, 1 if outside range, line pointer will not be moved. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._seek(line) return ret_val ### endblock ClassImplementation ### block ClassExtend # NOTICE: The code generator will not replace the code in this block ### endblock ClassExtend ### block Footer # NOTICE: The code generator will not replace the code in this block ### endblock Footer